亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用 PHP 加密,用 C 解密

用 PHP 加密,用 C 解密

PHP
MM們 2023-07-08 20:22:38
我想用 PHP 加密一個字符串,然后用 C 解密它。我陷入了解密部分。(PHP)我首先加密字符串:function encrypt($plaintext, $key) {? ? $iv = 'aaaaaaaaaaaaaaaa';? ? $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);? ? return $ciphertext;}echo encrypt('This is a test', 'test');// output: 7q?7h_??8? ??L(C) 然后我想解密它,我使用tiny-AES-c庫來實現以下功能:int test_decrypt_cbc(void) {? ? uint8_t key[] = "test";? ? uint8_t iv[]? = "aaaaaaaaaaaaaaaa";? ? uint8_t str[] = "7q?7h_??8? ??L";? ? printf("%s", str);? ? printf("\n Decrypted buffer\n");? ? struct AES_ctx ctx;? ? AES_init_ctx_iv(&ctx, key, iv);? ? AES_CBC_decrypt_buffer(&ctx, str, sizeof(str));? ??? ? printf("%s", str);? ? printf("\n");? ? return 1;}這輸出:7q?7h_??8? ??L?Decrypted buffer?L?????m??D??'?&??c?W它應該輸出“這是一個測試”。我怎樣才能解決這個問題?
查看完整描述

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);


查看完整回答
反對 回復 2023-07-08
  • 1 回答
  • 0 關注
  • 183 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號