close

簡易版LFSR程式撰寫

線性反饋移位暫存器(Linear feedback shift registerLFSR)是指給定前一狀態的輸出,將該輸出的線性函數再用作輸入的移位暫存器

 

範例:

建立一個具備四個記憶單元的線性回饋位移暫存器,其中b4 = b1 ⊕ b0。假設種子是(0001)二進制,在 20 次位移之後的輸出值如下圖表格所表示。

未命名.png

 

以上述流程簡單解釋先   b4 = b1 ⊕   b0 ,再往右移一個位元,讓   b0 成為   key 之後一直重複上述步驟即可。

 

未命名1.png

 

//簡易LFSR程式碼部分(建議以cpp檔儲存)

/*LFSR*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <iostream>
using namespace std;

int main(void) {                        
    char *p;                     //明文    
    char *c=new char(40);        //密文 
    int b[10];                   //種子 
    int x[9];                    //暫存器 
    FILE *fPtr;
    unsigned long leng, count;
      
    //xor
    for(int i=0;i<9;i++){
    x[i]=0;
    }

    //暫存器選擇
    cout<<"請選擇暫存器(1~8)(如要結束請按88)"<<endl;
    int i=0;
    cin>>x[i];
    i++;
    while(x[i-1]!=88){
        cin>>x[i];
        i++;
    }
    
    //seed(八位數)
    cout<<"input seed: ";
    for(int k=8;k>0;k--){
        cin>>b[k];
    }

    i=0;
    b[9]=0;
    while(x[i]!=88){
        b[9]=b[9]^b[x[i]];
        i++;
    }
      
    //讀入檔案(須先建立source.txt)
    fPtr = fopen("source.txt", "r");
    fseek(fPtr, 0, SEEK_END);
    leng = ftell(fPtr);
    fseek(fPtr, 0, SEEK_SET);
    p    = (char *) malloc((leng + 1) * sizeof(char));
    fread(p, 1, leng, fPtr);  
    fclose(fPtr);
    p[leng] = '\0';
  
    count = 0;
    for (int i=0; i<leng; i++)
    p[count++] = p[i];
    p[count] = '\0';
    printf("\n明文: %s\n\n", p);
  
    // 將字串編碼
    for(int m=0;m<leng;m++){
        for(int j=0;j<9;j++){
            b[j]=b[j+1];
        }
        
        c[m]=b[0]^p[m];

        i=0;
        b[9]=0;
        while(x[i]!=88){
            b[9]=b[9]^b[x[i]];
            i++;
        }    
    }
    
    cout<<"LFSR 密文: ";
    for(int b=0;b<leng;b++){
        cout<<c[b];
    }
      
    //輸出檔案 
    fPtr = fopen("result.txt", "w");
    fwrite(c, 1, count, fPtr);
    fclose(fPtr);
      
    return 0;
}

 

程式執行結果:

未命名3.png

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

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