用c++实现一次性密码本
时间: 2024-05-08 15:17:07 浏览: 14
一次性密码本(One-Time Pad,OTP)是一种加密方法,它使用随机生成的密钥与明文进行异或运算,从而产生密文。这种加密方法的安全性非常高,因为每个密钥只能使用一次,而且密钥是完全随机的。
下面是用C语言实现一次性密码本的基本代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_LEN 1000
void generate_key(char *key, int len) {
int i;
for (i = 0; i < len; i++) {
key[i] = rand() % 256;
}
}
void encrypt(char *plaintext, char *key, char *ciphertext, int len) {
int i;
for (i = 0; i < len; i++) {
ciphertext[i] = plaintext[i] ^ key[i];
}
}
void decrypt(char *ciphertext, char *key, char *plaintext, int len) {
int i;
for (i = 0; i < len; i++) {
plaintext[i] = ciphertext[i] ^ key[i];
}
}
int main() {
char plaintext[MAX_LEN];
char key[MAX_LEN];
char ciphertext[MAX_LEN];
int len, i;
printf("Enter the length of the plaintext: ");
scanf("%d", &len);
printf("Enter the plaintext: ");
scanf("%s", plaintext);
srand(time(NULL));
generate_key(key, len);
encrypt(plaintext, key, ciphertext, len);
printf("The ciphertext is: ");
for (i = 0; i < len; i++) {
printf("%02x", (unsigned char) ciphertext[i]);
}
printf("\n");
decrypt(ciphertext, key, plaintext, len);
printf("The decrypted plaintext is: %s\n", plaintext);
return 0;
}
```
在这个代码中,我们首先定义了三个函数:generate_key、encrypt和decrypt,它们分别用于生成密钥、加密明文和解密密文。generate_key函数使用rand函数生成随机数填充密钥数组;encrypt和decrypt函数分别使用异或运算对明文和密文进行加密和解密。
在main函数中,我们首先输入明文的长度和内容,然后使用generate_key函数生成密钥,使用encrypt函数对明文进行加密,输出密文,最后使用decrypt函数对密文进行解密,输出解密后的明文。
需要注意的是,在这个代码中,我们使用了scanf函数来读取明文,这可能会导致一些安全问题。如果需要处理敏感信息,建议使用更安全的输入函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)