|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | +██████╗ ██╗███████╗███╗ ███╗ |
| 5 | +██╔══██╗██║██╔════╝████╗ ████║ |
| 6 | +██████╔╝██║█████╗ ██╔████╔██║ |
| 7 | +██╔══██╗██║██╔══╝ ██║╚██╔╝██║ |
| 8 | +██║ ██║██║███████╗██║ ╚═╝ ██║ |
| 9 | +╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ |
| 10 | +*/ |
| 11 | + |
| 12 | + |
| 13 | +class riem { |
| 14 | + function encrypt ($pure_string, $encryption_key) { |
| 15 | + $cipher = 'AES-256-CBC'; |
| 16 | + $options = OPENSSL_RAW_DATA; |
| 17 | + $hash_algo = 'sha256'; |
| 18 | + $sha2len = 32; |
| 19 | + $ivlen = openssl_cipher_iv_length($cipher); |
| 20 | + $iv = openssl_random_pseudo_bytes($ivlen); |
| 21 | + $ciphertext_raw = openssl_encrypt($pure_string, $cipher, $encryption_key, $options, $iv); |
| 22 | + $hmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true); |
| 23 | + return $iv.$hmac.$ciphertext_raw; |
| 24 | + } |
| 25 | + function decrypt ($encrypted_string, $encryption_key) { |
| 26 | + $cipher = 'AES-256-CBC'; |
| 27 | + $options = OPENSSL_RAW_DATA; |
| 28 | + $hash_algo = 'sha256'; |
| 29 | + $sha2len = 32; |
| 30 | + $ivlen = openssl_cipher_iv_length($cipher); |
| 31 | + $iv = substr($encrypted_string, 0, $ivlen); |
| 32 | + $hmac = substr($encrypted_string, $ivlen, $sha2len); |
| 33 | + $ciphertext_raw = substr($encrypted_string, $ivlen+$sha2len); |
| 34 | + $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $encryption_key, $options, $iv); |
| 35 | + $calcmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true); |
| 36 | + if(function_exists('hash_equals')) { |
| 37 | + if (hash_equals($hmac, $calcmac)) return $original_plaintext; |
| 38 | + } else { |
| 39 | + if ($this->hash_equals_custom($hmac, $calcmac)) return $original_plaintext; |
| 40 | + } |
| 41 | + } |
| 42 | + /** |
| 43 | + * (Опционально) |
| 44 | + * hash_equals() функция многолифиллинга. |
| 45 | + */ |
| 46 | + function hash_equals_custom($knownString, $userString) { |
| 47 | + if (function_exists('mb_strlen')) { |
| 48 | + $kLen = mb_strlen($knownString, '8bit'); |
| 49 | + $uLen = mb_strlen($userString, '8bit'); |
| 50 | + } else { |
| 51 | + $kLen = strlen($knownString); |
| 52 | + $uLen = strlen($userString); |
| 53 | + } |
| 54 | + if ($kLen !== $uLen) { |
| 55 | + return false; |
| 56 | + } |
| 57 | + $result = 0; |
| 58 | + for ($i = 0; $i < $kLen; $i++) { |
| 59 | + $result |= (ord($knownString[$i]) ^ ord($userString[$i])); |
| 60 | + } |
| 61 | + return 0 === $result; |
| 62 | + } |
| 63 | +} |
| 64 | + |
0 commit comments