2024年6月1日发(作者:)

aes128加密算法c代码

以下是一个使用AES-128加密算法的C代码示例:

c.

#include

#include

#include

#include

// 加密函数。

void encryptAES(const unsigned char plaintext, int

plaintext_len, const unsigned char key, unsigned char

ciphertext) {。

AES_KEY aesKey;

AES_set_encrypt_key(key, 128, &aesKey);

AES_encrypt(plaintext, ciphertext, &aesKey);

}。

// 解密函数。

void decryptAES(const unsigned char ciphertext, int

ciphertext_len, const unsigned char key, unsigned char

plaintext) {。

AES_KEY aesKey;

AES_set_decrypt_key(key, 128, &aesKey);

AES_decrypt(ciphertext, plaintext, &aesKey);

}。

int main() {。

unsigned char key[16] = "ABCDEF"; // 128

位密钥。

unsigned char plaintext[] = "Hello, World!"; // 明

文。

int plaintext_len = strlen((char )plaintext);

// 计算加密后的密文长度。

int ciphertext_len = (plaintext_len +

AES_BLOCK_SIZE 1) / AES_BLOCK_SIZE AES_BLOCK_SIZE;

unsigned char ciphertext = malloc(ciphertext_len);

// 加密。

encryptAES(plaintext, plaintext_len, key,

ciphertext);

printf("Ciphertext: ");

for (int i = 0; i < ciphertext_len; i++) {。

printf("%02x", ciphertext[i]);

}。

printf("n");

// 解密。

unsigned char decryptedtext =

malloc(ciphertext_len);

decryptAES(ciphertext, ciphertext_len, key,

decryptedtext);

printf("Decrypted text: %sn", decryptedtext);

free(ciphertext);

free(decryptedtext);

return 0;

}。

此示例使用了OpenSSL库中的AES函数进行加密和解密。在代

码中,我们定义了一个128位的密钥和一个明文字符串。首先,我

们计算出加密后的密文长度,并为密文和解密后的明文分配内存空

间。然后,使用`encryptAES`函数对明文进行加密,将结果存储在

`ciphertext`中。最后,使用`decryptAES`函数对密文进行解密,

将结果存储在`decryptedtext`中。最后,我们打印出密文和解密后

的明文。

请注意,这只是一个简单的示例,实际使用中需要注意密钥的

安全性和适当的错误处理。另外,为了编译此代码,您需要安装

OpenSSL库并将编译命令中添加`-lssl -lcrypto`选项。