I am trying to decrypt an email address using AES-256-ECB. Its been a bit of a struggle as every source is showing a different method and I get a different result. Of course, I don’t get the result I want. Please take it easy commenting on the code I tried – this function changed about a million times by now.
Crap code:
function my_simple_crypt( $string, $action = 'e' ) { $secret_key = hex2bin('9cc25c7879fc94d5a19eeb8e47573b8423becb608a9a4e9d3c25c20aa7e04357'); $output = false; $encrypt_method = "AES-256-ECB"; //$secret_key = openssl_digest($secret_key, $encrypt_method, true); //$key = hash( 'sha256', $secret_key ); if( $action == 'e' ) { $output = openssl_encrypt( $string, $encrypt_method, $secret_key, 3 ); //$output = bin2hex($output); //$output = unpack('H*', $output); } else if( $action == 'd' ) { $output = openssl_decrypt( $string, $encrypt_method, $secret_key, 3 ); //$output = base64_encode($output); $output = bin2hex($output); } return $output; } echo '<pre>'; print_r(my_simple_crypt( 'testuser@gmail.com', 'e' )); echo '</pre>'; echo 'Encrypt: ' . my_simple_crypt( 'testuser@gmail.com', 'e' ) . '<br>'; echo 'Decrypt: ' . my_simple_crypt( hex2bin('8dd714df21027133cd422d0301af3cb973374ee72008c3f9bd255f6d236da65e'), 'd' );
Advertisement
Answer
As your key and ciphertext are in hex encoding you need to convert them back to binary data before you can feed them to the decryption function.
The following code gives this output:
plaintext decrypted: testuser@gmail.com plaintext expected: testuser@gmail.com
**Security warning: the following code uses the UNSECURE ECB mode:
<?php $keyHex = '9cc25c7879fc94d5a19eeb8e47573b8423becb608a9a4e9d3c25c20aa7e04357'; $ciphertextHex = '8dd714df21027133cd422d0301af3cb973374ee72008c3f9bd255f6d236da65e'; $plaintextExpected = 'testuser@gmail.com'; $key = hex2bin($keyHex); $ciphertext = hex2bin($ciphertextHex); $plaintext = openssl_decrypt($ciphertext, 'aes-256-ecb', $key, true); echo 'plaintext decrypted: ' . $plaintext . PHP_EOL; echo 'plaintext expected: ' . $plaintextExpected . PHP_EOL;