3
從AES_ENCRYPT輸出我不是通過貿易程序員,所以請多多包涵......不能讓PHP的openssl_encrypt匹配用C
我有我使用的,不幸的是存儲在明文口令的應用在MySQL中,這是我不想要的。由於該程序確實使用了OpenSSL庫,因此我可以訪問aes功能。
下面我拼湊起來使用這些函數來加密測試字符串,並使用MD5哈希它(因爲加密的文本是二進制)演示代碼:
#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\n", 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\n", output);
AES_set_decrypt_key(userKey_, 128, &aesKey_);
AES_decrypt(out_, in_,&aesKey_);
fprintf(stdout,"Recovered Original message: %s\n", in_);
return 0;
}
此輸出:
Original message: texttoencrypt
MD5 of Encrypted message: 3675b450ae0415e5a8521b9bb7ee01ba
Recovered Original message: texttoencrypt
在PHP
現在我使用這個代碼來生成各種AES-128加密的字符串並且類似地,MD5ing結果:
<?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 . "\r\n";
}
}
?>
輸出:
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
不幸的是,我沒有得到一個匹配由C代碼生成的3675b450ae0415e5a8521b9bb7ee01ba。我已經嘗試了幾乎所有在PHP手冊頁和SE上看到的評論,但無法獲得匹配結果。
我不能修改C代碼,只是PHP ...所以任何有關如何讓PHP匹配C輸出的指針肯定是值得讚賞的!
我的歉意......我只是想或多或少地從應用程序複製代碼。它只使用基本的aes_encrypt/decrypt和密鑰設置函數作爲aes.h中的參考。 這對我來說都是新的......我想我已經越過了我的腦海! – frischky