Last active
November 11, 2021 15:24
-
-
Save yuriy-yarvinen/46aef842ca6995ee7e77d9d984ce42b8 to your computer and use it in GitHub Desktop.
шифрование php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
define('ENCRYPTION_KEY', 'EncryptDecryptPHP201908Y'); | |
// Encrypt | |
function encrypt($plaintext){ | |
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC"); | |
$iv = openssl_random_pseudo_bytes($ivlen); | |
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv); | |
$hmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true); | |
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw ); | |
return $ciphertext; | |
} | |
// Decrypt | |
function decrypt($ciphertext){ | |
$c = base64_decode($ciphertext); | |
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC"); | |
$iv = substr($c, 0, $ivlen); | |
$hmac = substr($c, $ivlen, $sha2len=32); | |
$ciphertext_raw = substr($c, $ivlen+$sha2len); | |
$plaintext = openssl_decrypt($ciphertext_raw, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv); | |
$calcmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true); | |
if (hash_equals($hmac, $calcmac)) | |
{ | |
return $plaintext; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment