2017-07-23 33 views
-4

我有以下公式:逆向工程式轉換密文明文

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

我試圖解決明文[I]給出的密文[1]。

我正在使用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使用隨機爲關鍵字輸入我得到:

rbpgsrxhvmyxdnbsedjthykjpz as ciphertext[] 

但是當我rbpgsrxhvmyxdnbsedjthykjpz再次輸入使用隨機的關鍵詞,我得到:

abcdefghijklSnUpWXYt[v]^_z as xiphertext[] 

所以它可以工作到字母m

+0

請包括關於對更多細節問題或問題。 – UmarZaii

+0

我找不出數學。如何反轉模函數? – DCR

回答

3

您將無法解決它,因爲% 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'; 
+0

我正在使用vigenere密碼。如果我將純文本轉換爲密文,那麼不應該有辦法將密文轉換回純文本嗎? – DCR

+0

@DCR'%26'將爲''a''和''{''產生相同的值。除非確保所有輸入包含例如字母字符,否則無法恢復原始值。 – dasblinkenlight

+0

所以我添加了代碼,他們都是阿爾法,但反過來不起作用 – DCR