1 回答

TA貢獻1853條經驗 獲得超18個贊
在 PHP 代碼中,使用 AES-256。tiny-AES-c默認僅支持 AES-128。為了支持 AES-256,必須在 aes.h 中定義相應的常量,即必須在here
//#define AES256 1
中注釋該行。PHP 默認使用 PKCS7 填充。應在 C 代碼中刪除填充。
PHP 隱式地將太短的鍵用零值填充到指定的長度。由于PHP代碼中指定了AES-256-CBC,因此密鑰測試擴展如下:
test\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0
在 C 代碼中,必須使用此擴展密鑰(另請參閱@r3mainer 的注釋)。
為了在兩個代碼之間傳輸密文,必須使用合適的編碼,例如 Base64 或十六進制(另請參閱@?rel 的注釋)。對于后者,
bin2hex
可以應用于PHP代碼中的密文。一個可能的 C 實現是:
// Pad the key with zero values
uint8_t key[] = "test\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
uint8_t iv[] = "aaaaaaaaaaaaaaaa";
uint8_t ciphertextHex[] = "3771e837685ff5d4173801900de6e14c";
// Hex decode (e.g. https://stackoverflow.com/a/3409211/9014097)
uint8_t ciphertext[sizeof(ciphertextHex) / 2], * pos = ciphertextHex;
for (size_t count = 0; count < sizeof ciphertext / sizeof * ciphertext; count++) {
? ? sscanf((const char*)pos, "%2hhx", &ciphertext[count]);
? ? pos += 2;
}
// Decrypt
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CBC_decrypt_buffer(&ctx, ciphertext, sizeof(ciphertext));
// Remove the PKCS7 padding
uint8_t ciphertextLength = sizeof(ciphertext);
uint8_t numberOfPaddingBytes = ciphertext[ciphertextLength - 1];
ciphertext[ciphertextLength - numberOfPaddingBytes] = 0;
printf("%s", ciphertext);
- 1 回答
- 0 關注
- 183 瀏覽
添加回答
舉報