aes php

Solutions on MaxInterview for aes php by the best coders in the world

showing results for - "aes php"
Sophie
26 Mar 2019
1function encrypt($plaintext, $password) {
2    $method = "AES-256-CBC";
3    $key = hash('sha256', $password, true);
4    $iv = openssl_random_pseudo_bytes(16);
5
6    $ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
7    $hash = hash_hmac('sha256', $ciphertext . $iv, $key, true);
8
9    return $iv . $hash . $ciphertext;
10}
11
12function decrypt($ivHashCiphertext, $password) {
13    $method = "AES-256-CBC";
14    $iv = substr($ivHashCiphertext, 0, 16);
15    $hash = substr($ivHashCiphertext, 16, 32);
16    $ciphertext = substr($ivHashCiphertext, 48);
17    $key = hash('sha256', $password, true);
18
19    if (!hash_equals(hash_hmac('sha256', $ciphertext . $iv, $key, true), $hash)) return null;
20
21    return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
22}
23
24//Example usage:
25$encrypted = encrypt('Plaintext string.', 'password'); // this yields a binary string
26
27echo decrypt($encrypted, 'password');
28// decrypt($encrypted, 'wrong password') === null