我有以下公式:
ciphertext[i] = ((plaintext[i] -'a' + k) % 26) + 'a';
我正试图解决明文[i]给出的密文[i]。
我正在使用vigenere密码。如果我将纯文本转换为密文,是否应该有一种方法将密文转换回纯文本?
以下是整个代码:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[]){
if (argc !=2){
printf("FATAL ERROR: All hail Caesar!");
return 1;
}
for(int i = 0, n=strlen(argv[1]);i < n;i++){
if(!isupper(argv[1][i]) && !islower(argv[1][i])){
printf("FATAL ERROR: All hail Mark Anthony!");
return 1;
}
}
int cipherlength = strlen(argv[1]),ciphercount=0;
char cipherkey[strlen(argv[1])];
for(int i = 0, n=strlen(argv[1]);i < n;i++){
cipherkey[i] = argv[1][i];
}
string plaintext = NULL;
int k;
do{
printf("plaintext: ");
plaintext = get_string();
printf("ciphertext: ");
}while(plaintext == NULL);
char ciphertext[strlen(plaintext)];
char xiphertext[strlen(plaintext)];
k = atoi(argv[1]);
for (int i = 0,n=strlen(plaintext);i < n; i++){
int index = ciphercount % cipherlength;
if(isupper(cipherkey[index])) k = cipherkey[index] - 'A';
else if(islower(cipherkey[index])) k = cipherkey[index] - 'a';
if ((int)plaintext[i] >= 65 && (int)plaintext[i] <= 90){
ciphertext[i] = ((plaintext[i] -'A' + k) % 26) + 'A';
xiphertext[i] = ((plaintext[i] -'A' - k) % 26) + 'A';
ciphercount++;
}else if ((int)plaintext[i] >= 97 && (int)plaintext[i] <= 122){
ciphertext[i] = ((plaintext[i] -'a' + k) % 26) + 'a';
xiphertext[i] = ((plaintext[i] -'a' - k) % 26) + 'a';
ciphercount++;
}else {
ciphertext[i] = plaintext[i];
xiphertext[i] = plaintext[i];
}
printf("%c %c %c /n",plaintext[i],ciphertext[i],xiphertext[i]);
}
printf("\n");
}
当我输入abcdefghijklmnopqrstuvwxyz使用random作为关键词时,我得到:
rbpgsrxhvmyxdnbsedjthykjpz as ciphertext[]
但是当我再次输入rbpgsrxhvmyxdnbsedjthykjpz使用随机词作为关键词时,我得到了:
abcdefghijklSnUpWXYt[v]^_z as xiphertext[]
所以它适用于字母m
答案 0 :(得分:3)
你无法解决它,因为% 26
操作会为不同的plaintext[i]
生成相同的值。您可以通过计算
plaintext[i] = ((ciphertext[i]-'a'- k) % 26) + 'a';
谢谢,我需要添加以下内容:
if ((plaintext[i] - 'a' - k)%26 < 0)xiphertext[i] = ((plaintext[i] -'a' - k + 26) % 26) + 'a';