用c++语言实现一套简单的古典口令加密算法
时间: 2023-05-30 07:02:01 浏览: 101
古典口令加密算法是一种简单的替换密码,其中每个字母都被替换为一个固定的字符。以下是用C语言实现的古典口令加密算法:
```c
#include <stdio.h>
#include <string.h>
char* encrypt(char* message, char* password) {
int len = strlen(message);
char* result = (char*)malloc(len + 1);
int i, j;
for (i = 0; i < len; i++) {
j = i % strlen(password);
result[i] = (message[i] + password[j] - 2 * 'A') % 26 + 'A';
}
result[len] = '\0';
return result;
}
char* decrypt(char* message, char* password) {
int len = strlen(message);
char* result = (char*)malloc(len + 1);
int i, j;
for (i = 0; i < len; i++) {
j = i % strlen(password);
result[i] = (message[i] - password[j] + 26) % 26 + 'A';
}
result[len] = '\0';
return result;
}
int main() {
char message[] = "HELLO WORLD";
char password[] = "SECRET";
char* encrypted = encrypt(message, password);
printf("Encrypted message: %s\n", encrypted);
char* decrypted = decrypt(encrypted, password);
printf("Decrypted message: %s\n", decrypted);
free(encrypted);
free(decrypted);
return 0;
}
```
在该代码中,encrypt函数将明文字符串和密码字符串作为输入,并返回加密后的字符串。decrypt函数将加密后的字符串和密码字符串作为输入,并返回解密后的字符串。
加密和解密的过程都是通过循环遍历明文或密文字符串,并使用当前位置上的密码字符进行加密或解密操作。加密和解密操作都是通过将当前字符映射到0到25的数字范围内,然后进行加或减的操作,最后再将结果映射回字符形式完成的。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)