| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* This class provides the functionality to encrypt |
| 5 |
* and decrypt access tokens stored by the application |
| 6 |
* @author Ben Tadiar <ben@handcraftedbyben.co.uk> |
| 7 |
* @link https://github.com/benthedesigner/dropbox |
| 8 |
* @package Dropbox\Oauth |
| 9 |
* @subpackage Storage |
| 10 |
*/ |
| 11 |
|
| 12 |
class Dropbox_Encrypter |
| 13 |
{ |
| 14 |
// Encryption settings - default settings yield encryption to AES (256-bit) standard |
| 15 |
// @todo Provide PHPDOC for each class constant |
| 16 |
const CIPHER = MCRYPT_RIJNDAEL_128; |
| 17 |
const MODE = MCRYPT_MODE_CBC; |
| 18 |
const KEY_SIZE = 32; |
| 19 |
const IV_SIZE = 16; |
| 20 |
const IV_SOURCE = MCRYPT_DEV_URANDOM; |
| 21 |
|
| 22 |
/** |
| 23 |
* Encryption key |
| 24 |
* @var null|string |
| 25 |
*/ |
| 26 |
private $key = null; |
| 27 |
|
| 28 |
/** |
| 29 |
* Check Mcrypt is loaded and set the encryption key |
| 30 |
* @param string $key |
| 31 |
* @return void |
| 32 |
*/ |
| 33 |
public function __construct($key) |
| 34 |
{ |
| 35 |
if (!extension_loaded('mcrypt')) { |
| 36 |
throw new Dropbox_Exception('The storage encrypter requires the MCrypt extension'); |
| 37 |
} elseif (($length = mb_strlen($key, '8bit')) !== self::KEY_SIZE) { |
| 38 |
throw new Dropbox_Exception('Expecting a ' . self::KEY_SIZE . ' byte key, got ' . $length); |
| 39 |
} else { |
| 40 |
// Set the encryption key |
| 41 |
$this->key = $key; |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Encrypt the OAuth token |
| 47 |
* @param \stdClass $token Serialized token object |
| 48 |
* @return string |
| 49 |
*/ |
| 50 |
public function encrypt($token) |
| 51 |
{ |
| 52 |
$iv = mcrypt_create_iv(self::IV_SIZE, self::IV_SOURCE); |
| 53 |
$cipherText = mcrypt_encrypt(self::CIPHER, $this->key, $token, self::MODE, $iv); |
| 54 |
return base64_encode($iv . $cipherText); |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Decrypt the ciphertext |
| 59 |
* @param string $cipherText |
| 60 |
* @return object \stdClass Unserialized token |
| 61 |
*/ |
| 62 |
public function decrypt($cipherText) |
| 63 |
{ |
| 64 |
$cipherText = base64_decode($cipherText); |
| 65 |
$iv = substr($cipherText, 0, self::IV_SIZE); |
| 66 |
$cipherText = substr($cipherText, self::IV_SIZE); |
| 67 |
$token = mcrypt_decrypt(self::CIPHER, $this->key, $cipherText, self::MODE, $iv); |
| 68 |
return $token; |
| 69 |
} |
| 70 |
} |
| 71 |
|