I'm not a programmer by trade, so please bear with me...
I have an application I am using that unfortunately stores passwords in plaintext in MySQL, which is something I do not want. As the program does makes use of the OpenSSL library, I have access to the aes functions.
Below I've cobbled together demo code that uses these functions to encrypt a test string and uses MD5 to hash it (since the encrypted text is binary):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#include <openssl/md5.h>
char *str2md5(const char *str, int length) {
int n;
MD5_CTX c;
unsigned char digest[16];
char *out = (char*)malloc(33);
MD5_Init(&c);
while (length > 0) {
if (length > 512) {
MD5_Update(&c, str, 512);
} else {
MD5_Update(&c, str, length);
}
length -= 512;
str += 512;
}
MD5_Final(digest, &c);
for (n = 0; n < 16; ++n) {
snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
}
return out;
}
int main(int argc, char* argv[]) {
AES_KEY aesKey_;
unsigned char userKey_[16];
unsigned char in_[16];
unsigned char out_[16];
strcpy(userKey_,"1234567890abcdef");
strcpy(in_,"texttoencrypt");
fprintf(stdout,"Original message: %s
", in_);
AES_set_encrypt_key(userKey_, 128, &aesKey_);
AES_encrypt(in_, out_, &aesKey_);
char *output = str2md5(out_, strlen(out_));
fprintf(stdout,"MD5 of Encrypted message: %s
", output);
AES_set_decrypt_key(userKey_, 128, &aesKey_);
AES_decrypt(out_, in_,&aesKey_);
fprintf(stdout,"Recovered Original message: %s
", in_);
return 0;
}
This outputs:
Original message: texttoencrypt
MD5 of Encrypted message: 3675b450ae0415e5a8521b9bb7ee01ba
Recovered Original message: texttoencrypt
Now in PHP I am using this code to generate the various AES-128 encrypted strings and similarly, MD5ing the result:
<?php
$methods = openssl_get_cipher_methods();
$plain = "texttoencrypt";
$password = "1234567890abcdef";
foreach ($methods as $method) {
if (preg_match('/AES-128/', $method)) {
$encrypted = openssl_encrypt($plain, $method, $password);
$decrypted = openssl_decrypt($encrypted, $method, $password);
echo $method . ' : ' . md5($encrypted) . ' ; ' . $decrypted . "
";
}
}
?>
Output:
AES-128-CBC : 08d6f8e2ae21a7a506fabf91adcc3b63 ; texttoencrypt
AES-128-CFB : ce10ea28d7607bd6514e478e025e47c6 ; texttoencrypt
AES-128-CFB1 : 6adde484b8bee26f9b1ca7856634586d ; texttoencrypt
AES-128-CFB8 : aea100f1473c0a3d6380dd0f28585e19 ; texttoencrypt
AES-128-ECB : 08d6f8e2ae21a7a506fabf91adcc3b63 ; texttoencrypt
AES-128-OFB : ce10ea28d7607bd6514e478e025e47c6 ; texttoencrypt
Unfortunately, I am not getting a match to the 3675b450ae0415e5a8521b9bb7ee01ba generated by the C code. I've tried just about every comment I've seen on the PHP manual pages and here on SE, but can't get a match.
I can't modify the C code, just the PHP... so any pointers on how to get PHP to match the C output is certainly appreciated!