C语言 MbedTLS AES 加密解密示例代码
下面是一个使用 mbedTLS 库和 C 语言编写的 AES 加密和解密的例子代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mbedtls/aes.h>
int main()
{
// 设置密钥和明文
unsigned char key[16] = '0123456789abcdef';
unsigned char plaintext[16] = 'Hello, World!';
// 初始化AES上下文
mbedtls_aes_context aes;
mbedtls_aes_init(&aes);
// 设置密钥
mbedtls_aes_setkey_enc(&aes, key, 128);
// 加密明文
unsigned char ciphertext[16];
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, plaintext, ciphertext);
printf('Ciphertext: ');
for (int i = 0; i < 16; i++) {
printf('%02x ', ciphertext[i]);
}
printf('
');
// 解密密文
unsigned char decrypted[16];
mbedtls_aes_setkey_dec(&aes, key, 128);
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_DECRYPT, ciphertext, decrypted);
printf('Decrypted: ');
for (int i = 0; i < 16; i++) {
printf('%c', decrypted[i]);
}
printf('
');
// 清理AES上下文
mbedtls_aes_free(&aes);
return 0;
}
这个例子使用了 ECB 模式的 AES 加密和解密。密钥和明文都是 16 字节长度的数组。加密过程中,首先需要初始化 AES 上下文,然后设置密钥,接着使用 mbedtls_aes_crypt_ecb 函数进行加密,将结果保存在 ciphertext 数组中。解密过程中,需要再次设置密钥为解密模式,然后调用 mbedtls_aes_crypt_ecb 函数进行解密,将结果保存在 decrypted 数组中。
请注意,ECB 模式不是安全的加密模式,因为相同的明文块会被加密为相同的密文块,容易受到攻击。在实际应用中,建议使用更安全的加密模式,如 CBC 模式。
原文地址: https://www.cveoy.top/t/topic/qEQC 著作权归作者所有。请勿转载和采集!