【问题标题】:reverse engineer equation to convert ciphertext to plaintext逆向工程方程将密文转换为明文
【发布时间】:2017-07-23 21:58:58
【问题描述】:

我有以下公式:

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");

}

当我使用 random 作为关键字输入 abcdefghijklmnopqrstuvwxyz 时,我得到:

rbpgsrxhvmyxdnbsedjthykjpz as ciphertext[]

但是当我再次使用 random 作为关键字输入 rbpgsrxhvmyxdnbsedjthykjpz 时,我得到:

abcdefghijklSnUpWXYt[v]^_z  as xiphertext[]

所以它的工作原理是字母 m

【问题讨论】:

  • 请提供有关问题或问题的更多详细信息。
  • 我无法计算出数学。如何反转模函数?

标签: c algebra cs50 vigenere


【解决方案1】:

您将无法解决它,因为% 26 操作会为不同的plaintext[i]s 生成相同的值。您可以通过计算生成一个可能的大量可能性的明文

plaintext[i] = ((ciphertext[i]-'a'- k) % 26) + 'a';

Demo.

谢谢,我需要添加以下内容:

 if ((plaintext[i] - 'a' - k)%26 < 0)xiphertext[i] = ((plaintext[i] -'a' - k + 26) % 26)  + 'a';

【讨论】:

  • 我使用的是 vigenere 密码。如果我将纯文本转换为密文,是否应该有办法将密文转换回纯文本?
  • @DCR % 26 将为'a' 和'{' 生成相同的值。除非您确保所有输入都由例如字母字符组成,否则您无法恢复原始值。
  • 所以我添加了代码,它们都是 alpha,但反向不起作用
  • @DCR 看看我的演示链接,它得到了正确反转的结果。对于较大的k 值,您可能需要将26 添加到ciphertext[i]-'a'- k 的结果中,即ciphertext[i]-'a'- k+26 甚至ciphertext[i]-'a'- k+52。
  • Vigenere 密码只编码字母字符。因此,如果编码为a 和{ 生成相同的值,则将其解码为a。
猜你喜欢
  • 1970-01-01
  • 2010-11-25
  • 2011-02-16
  • 2020-07-02
  • 2011-08-09
  • 2016-09-27
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
相关资源
最近更新 更多