openssl对称加密和解密示例代码
时间: 2023-07-05 07:08:04 浏览: 74
下面是使用 OpenSSL 进行对称加密和解密的示例代码:
加密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define BITS 128
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <key> <plaintext>\n", argv[0]);
return 1;
}
unsigned char key[BITS/8];
memset(key, 0, sizeof(key));
strncpy(key, argv[1], sizeof(key));
unsigned char plaintext[256];
memset(plaintext, 0, sizeof(plaintext));
strncpy(plaintext, argv[2], sizeof(plaintext));
unsigned char iv[AES_BLOCK_SIZE];
memset(iv, 0, sizeof(iv));
AES_KEY aes_key;
AES_set_encrypt_key(key, BITS, &aes_key);
unsigned char ciphertext[sizeof(plaintext)];
memset(ciphertext, 0, sizeof(ciphertext));
AES_cbc_encrypt(plaintext, ciphertext, sizeof(plaintext), &aes_key, iv, AES_ENCRYPT);
printf("Ciphertext: %s\n", ciphertext);
return 0;
}
```
解密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define BITS 128
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <key> <ciphertext>\n", argv[0]);
return 1;
}
unsigned char key[BITS/8];
memset(key, 0, sizeof(key));
strncpy(key, argv[1], sizeof(key));
unsigned char ciphertext[256];
memset(ciphertext, 0, sizeof(ciphertext));
strncpy(ciphertext, argv[2], sizeof(ciphertext));
unsigned char iv[AES_BLOCK_SIZE];
memset(iv, 0, sizeof(iv));
AES_KEY aes_key;
AES_set_decrypt_key(key, BITS, &aes_key);
unsigned char plaintext[sizeof(ciphertext)];
memset(plaintext, 0, sizeof(plaintext));
AES_cbc_encrypt(ciphertext, plaintext, sizeof(ciphertext), &aes_key, iv, AES_DECRYPT);
printf("Plaintext: %s\n", plaintext);
return 0;
}
```
这两个程序使用 CBC 模式进行加密和解密,并使用 128 位的 AES 密钥。使用时,分别传入密钥和需要加密/解密的文本即可。注意,加密后的密文可能包含不可打印字符,输出时需要进行转换。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)