aes五种加密模式c语言代码
时间: 2023-08-26 09:02:19 浏览: 247
AES(Advanced Encryption Standard)是一种对称加密算法,它有五种加密模式:电子密码本模式(Electronic Codebook Mode,ECB)、加密块链接模式(Cipher Block Chaining Mode,CBC)、加密反馈模式(Cipher Feedback Mode,CFB)、输出反馈模式(Output Feedback Mode,OFB)和计数器模式(Counter Mode,CTR)。下面是用C语言实现这五种加密模式的代码:
1. 电子密码本模式(ECB):
```c
#include <openssl/aes.h>
int main()
{
AES_KEY key;
unsigned char plaintext[16] = "This is a test";
unsigned char ciphertext[16];
unsigned char keystr[16] = "0123456789abcdef";
AES_set_encrypt_key(keystr, 128, &key);
AES_encrypt(plaintext, ciphertext, &key);
return 0;
}
```
2. 加密块链接模式(CBC):
```c
#include <openssl/aes.h>
int main()
{
AES_KEY key;
unsigned char plaintext[16] = "This is a test";
unsigned char ciphertext[16];
unsigned char iv[16] = "0123456789abcdef";
unsigned char keystr[16] = "0123456789abcdef";
AES_set_encrypt_key(keystr, 128, &key);
AES_cbc_encrypt(plaintext, ciphertext, 16, &key, iv, AES_ENCRYPT);
return 0;
}
```
3. 加密反馈模式(CFB):
```c
#include <openssl/aes.h>
int main()
{
AES_KEY key;
unsigned char plaintext[16] = "This is a test";
unsigned char ciphertext[16];
unsigned char iv[16] = "0123456789abcdef";
unsigned char keystr[16] = "0123456789abcdef";
AES_set_encrypt_key(keystr, 128, &key);
AES_cfb_encrypt(plaintext, ciphertext, 16, &key, iv, NULL, AES_ENCRYPT);
return 0;
}
```
4. 输出反馈模式(OFB):
```c
#include <openssl/aes.h>
int main()
{
AES_KEY key;
unsigned char plaintext[16] = "This is a test";
unsigned char ciphertext[16];
unsigned char iv[16] = "0123456789abcdef";
unsigned char keystr[16] = "0123456789abcdef";
AES_set_encrypt_key(keystr, 128, &key);
AES_ofb128_encrypt(plaintext, ciphertext, 16, &key, iv, NULL);
return 0;
}
```
5. 计数器模式(CTR):
```c
#include <openssl/aes.h>
int main()
{
AES_KEY key;
unsigned char plaintext[16] = "This is a test";
unsigned char ciphertext[16];
unsigned char iv[16] = "0123456789abcdef";
unsigned char ecount_buf[16];
unsigned int num = 0;
unsigned char keystr[16] = "0123456789abcdef";
AES_set_encrypt_key(keystr, 128, &key);
AES_ctr128_encrypt(plaintext, ciphertext, 16, &key, iv, ecount_buf, &num);
return 0;
}
```
以上就是用C语言实现AES五种加密模式的代码。请注意,这里使用了OpenSSL库进行AES加密操作,你需要提前安装好OpenSSL库并链接到你的项目中。
阅读全文