编辑aes128加解密代码 c语言
时间: 2024-11-09 13:26:14 浏览: 28
AES(Advanced Encryption Standard)是一种高级加密标准,常用于保护数据的安全传输。在C语言中使用AES-128进行加解密,通常需要依赖外部库,如OpenSSL或者Crypto++,因为AES本身是一个复杂的算法,不适合直接嵌入到核心代码中。
以下是一个简单的示例,展示了如何使用OpenSSL库来进行AES-128-CBC模式的加解密:
```c
#include <stdio.h>
#include <string.h>
#include <openssl/aes.h>
// AES-128 key and IV (16 bytes each)
const unsigned char myKey[] = { 'K', 'e', 'y', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '0', 'A', 'B', 'C' };
const unsigned char myIV[] = { 'I', 'V', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0', 'A', 'B', 'C', 'D' };
void aes_encrypt(unsigned char *input, size_t len, const unsigned char *key,
const unsigned char *iv) {
AES_KEY aes_key;
AES_set_encrypt_key(key, 128, &aes_key); // 128 bits for AES-128
unsigned char output[len];
AES_cbc_encrypt(input, output, len, &aes_key, iv, AES_ENCRYPT);
// Write encrypted data to another buffer or file
}
void aes_decrypt(unsigned char *input, size_t len, const unsigned char *key,
const unsigned char *iv) {
AES_KEY aes_key;
AES_set_decrypt_key(key, 128, &aes_key); // 128 bits for AES-128
unsigned char output[len];
AES_cbc_encrypt(input, output, len, &aes_key, iv, AES_DECRYPT);
// Read decrypted data from the buffer or file and compare with original
}
int main() {
unsigned char plaintext[] = "Hello, World!";
size_t plaintext_len = strlen(plaintext);
unsigned char ciphertext[plaintext_len]; // Room for encryption
aes_encrypt(plaintext, plaintext_len, myKey, myIV);
// Now you can write ciphertext to a file or send it over network.
// To decrypt:
unsigned char decryptedtext[plaintext_len];
aes_decrypt(ciphertext, plaintext_len, myKey, myIV);
printf("Decrypted: %s\n", decryptedtext);
return 0;
}
```
注意:这只是一个基本示例,实际使用时你需要处理错误、输入验证以及文件操作等。此外,AES的CBC模式需要一个初始化向量(IV),通常在每次加密前随机生成并妥善保存。
阅读全文