代码改变世界

20165321 实验三 敏捷开发与XP实践-4

2018-04-27 20:24  Ze6Pui3Loeng4  阅读(121)  评论(0编辑  收藏  举报

Java密码学程序

import java.util.*;
public class Lfsr {
    public static void main(String[] args) {
        System.out.println("请输入移位寄存器的级数n:");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println("请设置初态:");
        int[] a = new int[n];//状态数
        int  sum=1;
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            sum=2*sum;
        }
        System.out.println("请输入结构常数:");//形如[c1,c2,c3,c4,c5]
        int[] c = new int[n];//存储的为反馈函数,与反馈函数的对应规律为:若结构常数为[0,1,0,1],则反馈函数为
        for (int i = n-1; i >= 0; i--) {
            c[i] = sc.nextInt();
        }
        System.out.println("线性移位寄存器输出序列为:");
        for (int i = 0; i <sum-1; i++) {
            System.out.printf("%d", a[0]);
            operate1(a, c, n);
        }
        System.out.println(" ");
        System.out.println("对偶移位寄存器输出序列为:");
        for(int i=0;i<sum-1;i++) {
            System.out.printf("%d",a[0]);
            operate2(a,c,n);
        }
    }
    private static int[] operate2(int[] a, int[] c, int n) {
        int temp=a[0];
        for(int i=0;i<n-1;i++) {
            a[i]=a[i+1];
        }
        a[n-1]=0;
        if(temp==1) {
            for(int j=0;j<n;j++) {
                a[j]=(a[j]+c[n-j-1])%2;
            }
        }
        return a;
    }
    private static int[] operate1(int[] a, int[] c, int n) {
        int temp=0;
        for (int i = 0; i < n; i++) {
            if (a[i] * c[i] == 1) {
                temp += 1;
            }
        }
        a[n - 1] %= 2;
        for (int j = 0; j < n - 1; j++) {
            a[j] = a[j + 1];
        }
        a[n-1]=temp;
        return a;
    }
}

截图