用替代密码算法简单写一个加密程序
时间: 2023-09-06 16:08:41 浏览: 119
好的,我可以给你一个简单的替代密码算法加密程序,代码如下:
```python
def encrypt(plaintext, key):
# 将明文转换为大写字母
plaintext = plaintext.upper()
ciphertext = ''
# 遍历明文的每个字符
for char in plaintext:
if char.isalpha():
# 将字母转换为数字,A-->0, B-->1, ..., Z-->25
num = ord(char) - ord('A')
# 使用替代密码算法进行加密
num = (num + key) % 26
# 将加密后的数字转换回字母
char = chr(num + ord('A'))
ciphertext += char
return ciphertext
```
这个加密程序的思路是,将明文中的每个字母转换为数字,然后使用替代密码算法进行加密,最后再将加密后的数字转换回字母。其中,替代密码算法的实现方式是,将明文中每个字母的数字加上一个密钥(key),然后对 26 取模得到加密后的数字。
相关问题
用C语言实现一个简单替代密码算法程序
以下是一个简单的替代密码算法程序,使用C语言实现:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char plaintext[100], ciphertext[100];
int key[26] = {10, 15, 3, 20, 9, 12, 25, 6, 16, 17, 1, 22, 5, 11, 8, 18, 0, 24, 14, 7, 19, 4, 21, 2, 23, 13}; // 替代表
printf("请输入明文:");
scanf("%s", plaintext);
// 加密
int len = strlen(plaintext);
for (int i = 0; i < len; i++)
{
if (plaintext[i] >= 'a' && plaintext[i] <= 'z')
{
ciphertext[i] = 'a' + key[plaintext[i] - 'a']; // 明文字符替换为对应的密文字符
}
else
{
ciphertext[i] = plaintext[i]; // 非小写字母保持不变
}
}
ciphertext[len] = '\0'; // 添加结束符
printf("加密后的密文:%s\n", ciphertext);
return 0;
}
```
程序中使用了一个长度为26的数组作为替代表,每个元素表示对应的小写字母在密文中的替代字符。输入明文后,程序遍历明文中的每个字符,如果是小写字母,则将其替换为替代表中对应的字符,否则保持不变。最后输出加密后的密文。
替代密码算法c语言
替代密码算法是一种基于置换和替换的加密算法,常见的有凯撒密码、栅栏密码、摩尔斯电码等。以下是一个简单的栅栏密码的C语言实现示例:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void encrypt(char *input, int key) {
int len = strlen(input);
char cipher[MAX_LEN] = {0};
for (int i = 0; i < key; i++) {
for (int j = i; j < len; j += key) {
cipher[strlen(cipher)] = input[j];
}
}
printf("Cipher text: %s\n", cipher);
}
void decrypt(char *input, int key) {
int len = strlen(input);
char plain[MAX_LEN] = {0};
int index = 0;
for (int i = 0; i < key; i++) {
for (int j = i; j < len; j += key) {
plain[j] = input[index++];
}
}
printf("Plain text: %s\n", plain);
}
int main() {
char input[MAX_LEN];
int key;
printf("Enter the plain text: ");
fgets(input, MAX_LEN, stdin);
input[strcspn(input, "\n")] = 0;
printf("Enter the key: ");
scanf("%d", &key);
encrypt(input, key);
decrypt(input, key);
return 0;
}
```
该程序接受用户输入的字符串和密钥,对输入的字符串进行栅栏加密和解密,并输出结果。需要注意的是,该程序只是一个简单的示例,实际使用中需要考虑更多的安全性和灵活性问题。