| 1: | <?php |
| 2: | |
| 3: | namespace nightmare\crypto; |
| 4: | |
| 5: | class aes_256_cbc |
| 6: | { |
| 7: | public static function get_key($input_key) |
| 8: | { |
| 9: | return hash('sha256', $input_key, true); |
| 10: | } |
| 11: | |
| 12: | public static function encrypt($plaintext, $input_key) |
| 13: | { |
| 14: | $key = self::get_key($input_key); |
| 15: | $iv = openssl_random_pseudo_bytes(16); |
| 16: | |
| 17: | $ciphertext = openssl_encrypt( |
| 18: | $plaintext, |
| 19: | 'AES-256-CBC', |
| 20: | $key, |
| 21: | OPENSSL_RAW_DATA, |
| 22: | $iv |
| 23: | ); |
| 24: | |
| 25: | $result = base64_encode($iv . $ciphertext); |
| 26: | |
| 27: | return $result; |
| 28: | } |
| 29: | |
| 30: | public static function decrypt($encrypted_data, $input_key) |
| 31: | { |
| 32: | $key = self::get_key($input_key); |
| 33: | $raw = base64_decode($encrypted_data); |
| 34: | $iv = substr($raw, 0, 16); |
| 35: | $ciphertext = substr($raw, 16); |
| 36: | |
| 37: | $decrypted = openssl_decrypt( |
| 38: | $ciphertext, |
| 39: | 'AES-256-CBC', |
| 40: | $key, |
| 41: | OPENSSL_RAW_DATA, |
| 42: | $iv |
| 43: | ); |
| 44: | |
| 45: | return $decrypted; |
| 46: | } |
| 47: | } |
| 48: |