|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Shimoning\Encryption; |
| 4 | + |
| 5 | +class Encryption |
| 6 | +{ |
| 7 | + /** |
| 8 | + * Default encryption method. |
| 9 | + */ |
| 10 | + public const DEFAULT_METHOD = 'AES-256-CBC'; |
| 11 | + |
| 12 | + /** |
| 13 | + * Default key for encryption. |
| 14 | + * |
| 15 | + * \base64_encode(\openssl_random_pseudo_bytes(\openssl_cipher_iv_length('AES-256-CBC'))) |
| 16 | + */ |
| 17 | + public const DEFAULT_KEY = '06ShagteTfh1cKgu0GI0iA=='; |
| 18 | + |
| 19 | + /** |
| 20 | + * Default IV for encryption. |
| 21 | + * |
| 22 | + * \base64_encode(\openssl_random_pseudo_bytes(\openssl_cipher_iv_length('AES-256-CBC'))) |
| 23 | + */ |
| 24 | + public const DEFAULT_IV = 'lSwJdjw1PUnjyw5OwhAUIA=='; |
| 25 | + |
| 26 | + /** |
| 27 | + * 暗号化を行う |
| 28 | + * |
| 29 | + * @param string $string |
| 30 | + * @param string|null $method |
| 31 | + * @param string|null $base64key |
| 32 | + * @param string|null $base64iv |
| 33 | + * @return string |
| 34 | + */ |
| 35 | + public static function encrypt( |
| 36 | + string $string, |
| 37 | + ?string $method = null, |
| 38 | + ?string $base64key = null, |
| 39 | + ?string $base64iv = null, |
| 40 | + ): string { |
| 41 | + return \base64_encode( |
| 42 | + \openssl_encrypt( |
| 43 | + $string, |
| 44 | + $method ?? static::DEFAULT_METHOD, |
| 45 | + \base64_decode($base64key ?? static::DEFAULT_KEY), |
| 46 | + \OPENSSL_RAW_DATA, |
| 47 | + \base64_decode($base64iv ?? static::DEFAULT_IV), |
| 48 | + ), |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * 復号化を行う |
| 54 | + * |
| 55 | + * @param string $string |
| 56 | + * @param string|null $method |
| 57 | + * @param string|null $base64key |
| 58 | + * @param string|null $base64iv |
| 59 | + * @return string |
| 60 | + */ |
| 61 | + public static function decrypt( |
| 62 | + string $string, |
| 63 | + ?string $method = null, |
| 64 | + ?string $base64key = null, |
| 65 | + ?string $base64iv = null, |
| 66 | + ): string { |
| 67 | + return \openssl_decrypt( |
| 68 | + \base64_decode($string), |
| 69 | + $method ?? static::DEFAULT_METHOD, |
| 70 | + \base64_decode($base64key ?? static::DEFAULT_KEY), |
| 71 | + \OPENSSL_RAW_DATA, |
| 72 | + \base64_decode($base64iv ?? static::DEFAULT_IV), |
| 73 | + ); |
| 74 | + } |
| 75 | +} |
0 commit comments