codeblocks使用mbedtls加密字符串aes代码
以下是一个使用mbedtls库进行AES加密的示例代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mbedtls/aes.h"
void print_hex(const char *label, const unsigned char *buf, size_t len) {
size_t i;
printf("%s:", label);
for (i = 0; i < len; i++)
printf(" %02x", buf[i]);
printf("\n");
}
int main() {
const unsigned char key[16] = "0123456789abcdef"; // 128-bit AES key
const unsigned char iv[16] = "0123456789abcdef"; // 128-bit IV
const char *plaintext = "Hello, world!";
unsigned char ciphertext[64] = {0};
unsigned char decrypted[64] = {0};
mbedtls_aes_context ctx;
mbedtls_aes_init(&ctx);
mbedtls_aes_setkey_enc(&ctx, key, 128);
// 加密
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, strlen(plaintext), iv, (unsigned char *)plaintext, ciphertext);
print_hex("Ciphertext", ciphertext, strlen(plaintext));
// 解密
mbedtls_aes_setkey_dec(&ctx, key, 128);
mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, strlen(plaintext), iv, ciphertext, decrypted);
print_hex("Decrypted", decrypted, strlen(plaintext));
mbedtls_aes_free(&ctx);
return 0;
}
请记得在编译之前,确保已经安装了mbedtls库,并将其头文件和库文件正确地链接到项目中
原文地址: https://www.cveoy.top/t/topic/iSbp 著作权归作者所有。请勿转载和采集!