close

簡易XOR cipher程式撰寫

XOR cipher在密碼學中是一種簡單的加密演算法,它按照如下原則進行運算:

         A  B = C

         C B = A

 

其中⊕為邏輯異或(XOR)運算的符號。按照這種邏輯,字串中的每個字元可以通過與給定的金鑰進行XOR運算來加密。如果要解密,只需要將加密後的結果與金鑰再次進行XOR運算即可。

 

例如加密字串「Play」先將字串拆解成8位元的ASCII(01010000 01101100 01100001 01111001)再跟金鑰00100000(0x20)進行XOR加密之後比對8位元的ASCII表可得出密文pLAY」加密過程如下:

 

          01010000     01101100       01100001        01111001

00100000     00100000      00100000        00100000

------------------------------------------------------------------------

    01110000     01001100        01000001        01011001

 

此加密方法為對稱式加密,故解密方式為密文pLAY跟上述金鑰00100000(0x20)XOR即可:

 

   01110000     01001100         01000001        01011001

00100000     00100000        00100000        00100000

------------------------------------------------------------------------

01010000    01101100          01100001        01111001

 

此種加密法如果一直使用重複的金鑰,只要利用頻率分析就可以破解這種簡單的XOR密碼。當同時取得密文和明文時,金鑰就會泄露,因為明文 密文 = 金鑰」,此加密法其實非常脆弱。不過XOR加密法廣泛使用的原因主要為容易撰寫。簡單或重複的XOR加密有時用於不需要在特別安全的情況下來隱藏資訊。

 

如果金鑰為隨機的(不重複),且與訊息長度相同,XOR密碼就會更為安全。

(不過以下版本為金鑰重複版本)

 

以下為程式碼:

/*XOR cipher*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(){
    char *data;                                      //輸入    
    char *target=malloc(100 * sizeof(char));         //輸出 
    int key;                                         //金鑰 
    FILE *fPtr;
    unsigned long leng, count, i;
    int ch;
    
    //讀檔(須先建立source.txt) 
    fPtr = fopen("source.txt", "r");
    fseek(fPtr, 0, SEEK_END);
    leng = ftell(fPtr);
    fseek(fPtr, 0, SEEK_SET);
    data = (char *) malloc((leng + 1) * sizeof(char));
    fread(data, 1, leng, fPtr);  
    fclose(fPtr);
    data[leng] = '\0';
      
    printf("\n讀入檔案: %s\n\n", data);
    printf("請選擇加密或解密 1.解密 2.加密 : ");
    scanf("%d",&ch);
    printf("請輸入金鑰(範圍為 0x20 ~ 0x7E ) : ");
    scanf("%x",&key);
    
    count = 0;
    for (i=0; i<leng; i++) data[count++] = data[i];
    data[count] = '\0';
    
    switch(ch){
        case 1:         
            i = 0; 
            while (data[i] != '\0') {
                target[i] = data[i] ^ key;
                i++; 
            }
            target[i] = '\0';
            printf("\n密文 : %s\n\n", target); 
            break;
        case 2: 
            i = 0; 
            while (data[i] != '\0') {
                target[i] = data[i] ^ key;
                i++; 
            }
            target[i] = '\0';
            printf("\n明文 : %s\n\n", target); 
            break;              
        default:
            printf("\n錯誤\n");
            break;    
    }
    
    //輸出檔案 
    fPtr = fopen("result.txt", "w");
    fwrite(target, 1, count, fPtr);
    fclose(fPtr);
    
    system("pause");
    return 0;
}

 

輸出結果:

加密:

解密:

arrow
arrow
    文章標籤
    密碼學 程式 XOR
    全站熱搜

    ATing 發表在 痞客邦 留言(0) 人氣()