Activator.php
2 months ago
Assets.php
1 month ago
Blocks.php
10 months ago
Database.php
8 months ago
Encrypt.php
7 months ago
Encrypt.php
45 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Reach\Setup; |
| 4 | |
| 5 | class Encrypt { |
| 6 | public const ENCRYPT_METHOD = 'AES-256-CBC'; |
| 7 | |
| 8 | public static function encrypt( string $value ): string { |
| 9 | if ( ! self::can_encrypt() ) { |
| 10 | return base64_encode( $value ); |
| 11 | } |
| 12 | |
| 13 | $key = hash( 'sha256', AUTH_KEY, true ); |
| 14 | $iv = openssl_random_pseudo_bytes( openssl_cipher_iv_length( self::ENCRYPT_METHOD ) ); |
| 15 | $encrypted = openssl_encrypt( $value, self::ENCRYPT_METHOD, $key, 0, $iv ); |
| 16 | |
| 17 | return base64_encode( $iv . $encrypted ); |
| 18 | } |
| 19 | |
| 20 | public static function decrypt( string $value ): string { |
| 21 | if ( ! self::can_encrypt() ) { |
| 22 | return base64_decode( $value ); |
| 23 | } |
| 24 | $iv_length = openssl_cipher_iv_length( self::ENCRYPT_METHOD ); |
| 25 | $data = base64_decode( $value ); |
| 26 | $iv = substr( $data, 0, $iv_length ); |
| 27 | $encrypted = substr( $data, $iv_length ); |
| 28 | $key = hash( 'sha256', AUTH_KEY, true ); |
| 29 | |
| 30 | return openssl_decrypt( $encrypted, self::ENCRYPT_METHOD, $key, 0, $iv ); |
| 31 | } |
| 32 | |
| 33 | private static function get_auth_key(): string { |
| 34 | if ( ! DEFINED( 'AUTH_KEY' ) ) { |
| 35 | return ''; |
| 36 | } |
| 37 | |
| 38 | return AUTH_KEY; |
| 39 | } |
| 40 | |
| 41 | private static function can_encrypt(): bool { |
| 42 | return extension_loaded( 'openssl' ) && self::get_auth_key(); |
| 43 | } |
| 44 | } |
| 45 |