1 | <?php |
||
27 | class Aes extends Cryptobase |
||
28 | { |
||
29 | |||
30 | /** |
||
31 | * AES-256 cipher identifier that will be passed to openssl |
||
32 | * |
||
33 | * @var string |
||
34 | */ |
||
35 | const CIPHER = 'aes-256-cbc'; |
||
36 | |||
37 | /** |
||
38 | * Size of initialization vector in bytes |
||
39 | * |
||
40 | * @var int |
||
41 | */ |
||
42 | const IVSIZE = 16; |
||
43 | |||
44 | /** |
||
45 | * Size of checksum in bytes |
||
46 | * |
||
47 | * @var int |
||
48 | */ |
||
49 | const CKSIZE = 32; |
||
50 | |||
51 | /** |
||
52 | * This string is used when hashing to ensure cross compatibility between |
||
53 | * dcrypt\mcrypt and dcrypt\aes. |
||
54 | */ |
||
55 | const RIJNDA = 'rijndael-128'; |
||
56 | |||
57 | /** |
||
58 | * Decrypt cyphertext |
||
59 | * |
||
60 | * @param string $cyphertext Cyphertext to decrypt |
||
61 | * @param string $password Password that should be used to decrypt input data |
||
62 | * @param int $cost Number of extra HMAC iterations to perform on key |
||
63 | * |
||
64 | * @return string |
||
65 | */ |
||
66 | 8 | public static function decrypt($cyphertext, $password, $cost = 0) |
|
89 | |||
90 | /** |
||
91 | * Encrypt plaintext |
||
92 | * |
||
93 | * @param string $plaintext Plaintext string to encrypt. |
||
94 | * @param string $password Password used to encrypt data. |
||
95 | * @param int $cost Number of extra HMAC iterations to perform on key |
||
96 | * |
||
97 | * @return string |
||
98 | */ |
||
99 | 7 | public static function encrypt($plaintext, $password, $cost = 0) |
|
100 | { |
||
101 | // Generate IV of appropriate size. |
||
102 | 7 | $iv = Random::bytes(self::IVSIZE); |
|
103 | |||
104 | // Derive key from password |
||
105 | 7 | $key = self::key($password, $iv, $cost, self::RIJNDA, self::mode()); |
|
106 | |||
107 | // Encrypt the plaintext |
||
108 | 7 | $message = \openssl_encrypt($plaintext, static::CIPHER, $key, 1, $iv); |
|
109 | |||
110 | // If message could not be encrypted then throw an exception |
||
111 | 7 | if ($message === false) { |
|
112 | throw new \exception('Could not encrypt the data.'); // @codeCoverageIgnore |
||
113 | } |
||
114 | |||
115 | // Create the cypher text prefix (iv + checksum) |
||
116 | 7 | $prefix = $iv . self::checksum($message, $iv, $key, self::RIJNDA, self::mode()); |
|
117 | |||
118 | // Return prefix + cyphertext |
||
119 | 7 | return $prefix . $message; |
|
120 | } |
||
121 | |||
122 | /** |
||
123 | * Return the encryption mode string. "cbc" or "ctr" |
||
124 | * |
||
125 | * @return string |
||
126 | */ |
||
127 | 9 | protected static function mode() |
|
131 | |||
132 | } |
||
133 |