DES密码算法中进行16轮迭代运算时需要16轮子密钥,密钥初始材料为64位比特字节,本程序采用64个整形1、0代替二进制,模拟DES中16轮子密钥生成过程,这样可以形象观察其整个密钥生成过程。实际应用时只需要将int行改为byte行就行。

public class Key{

private final int SIZE=56;

private final int KEY_SIZE=48;

private int[] C=new int[28];

private int[] D=new int[28];

private int[] key=new int[SIZE];

private int[][] PRIVATE_KEY=new int[16][48];

private  int[] IP_1=new int[]{

57,49,41,33,25,17,9,1,

58,50,42,34,26,18,10,2,

59,51,43,35,27,19,11,3,

60,52,44,36,63,55,47,39,

31,23,15,7,62,54,46,38,

30,22,14,6,61,53,45,37,

29,21,13,5,28,20,12,4

};

private int[] IP_2=new int[]{

  14,17,11,24,1,5,

  3,28,15,6,21,10,

  23,19,12,4,26,8,

  16,7,27,20,13,2,

  41,52,31,37,47,55,

  30,40,51,45,33,48,

  44,49,39,56,34,53,

  46,42,50,36,29,32

};

public Key(int[] k){

for(int i=0;i<SIZE;i++)

key[i]=k[IP_1[i]];

for(int i=0;i<28;i++){

                        C[i]=key[i];

                        D[i]=key[i+28];

                }

}

public int[][] initKey(){

MoveKey();

return PRIVATE_KEY;

}

public void MoveKey(){

for(int i=0;i<16;i++){

int m=C[0],n=D[0],p=C[1],q=D[1];

int num=i;

for(int j=0;j<28;j++){

if(i==0||i==1||i==8||i==15){

if(j==27){

C[j]=m;

D[j]=n;

}

else{

C[j]=C[j+1];

D[j]=D[j+1];

}

}

else{

if(j==26){

C[j]=m;

D[j]=n;

}

else if(j==27){

C[j]=p;

D[j]=q;

}

else{

C[j]=C[j+2];

D[j]=D[j+2];

}

}

}

for(int l=0;l<KEY_SIZE;l++){

int temp=IP_2[l]-1;

if(temp<28)

PRIVATE_KEY[num][l]=C[temp];

else

PRIVATE_KEY[num][l]=D[temp-28];

}

}

}

public static void main(String[] str){

int[] test=new int[]{0,0,1,1,0,0,0,1,0,0,1,1,0,0,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,1,0,0,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,1,0,0,0};

Key k=new Key(test);

int[][] key=k.initKey();

for(int i=0;i<key.length;i++){

System.out.println("第"+(i+1)+"轮密钥: ");

for(int j=0;j<key[i].length;j++){

System.out.print(key[i][j]+"  ");

}

System.out.println("");

}

}

}