最近学密码学,有时需要算DES算法生成的16轮子密钥,觉得有点麻烦,就写了个小程序来算,具体代码如下:
#include
int subSecretKey[17][48];//16轮的子密钥1-16
int leftSecretKey[27]=
{
0,0,0,0,1,1,1,1,0,0,1,1,0,0,1,1,0,1,0,1,0,1,0,1,1,1,1,1
};//进行第一轮置换后的左边秘密钥
int rightSecretKey[27]=
{
0,1,0,1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1
};//进行第一轮置换后的右边秘密钥
int subLeftSecretKey[24];
int subRightSecretKey[24];
int s,i,m;
//为了数组表示方便,将置换选择2中的位置全部减小1
int LP[24] =
{
13,16,10,23,0,4,2,27,14,5,20,9,
22,18,11,3,25,7,15,6,26,19,12,1
};
//主函数
int RP[24] =
{
40,51,30,36,46,54,29,39,50,44,32,47,
43,48,38,55,33,52,45,41,49,35,28,31
};
int main()
{
int i,j,t;
//16轮的子密钥生成
for(i=1; i<=16;i++)
{
if(i==1|| i==2 ||i==9 ||i==16)
//循环左移一位
{
int tempLeft = leftSecretKey[0];
int tempRight = rightSecretKey[0];
for(j=0; j<27; j++)
{
leftSecretKey[j] = leftSecretKey[j+1];
rightSecretKey[j]= rightSecretKey[j+1];
}
leftSecretKey[27] = tempLeft;
rightSecretKey[27] = tempRight;
}
else //循环左移两位
{
int tempLeft1 = leftSecretKey[0],
tempLeft2 = leftSecretKey[1];
int tempRight1 = rightSecretKey[0],
tempRight2 = rightSecretKey[1];
for(j=0; j<26; j++)
{
leftSecretKey[j] = leftSecretKey[j+2];
rightSecretKey[j]= rightSecretKey[j+2];
}
leftSecretKey[26]= tempLeft1;
leftSecretKey[27]= tempLeft2;
rightSecretKey[26]= tempRight1;
rightSecretKey[27]= tempRight2;
}
//置换,形成subLeftSecretKey[24],subRightSecretKey[24];
for(j=0; j<24; j++)
{
t=LP[j];
subLeftSecretKey[j] = leftSecretKey[t];
}
printf("\n");
for(j=0; j<24; j++)
{
t=RP[j];
//注意,由于开始分了两个数组输入,所以这里要减去前面的28位,才是正确的赋值
subRightSecretKey[j] = rightSecretKey[t-28];
}
//输出第i轮的子密钥
printf("第%d轮密钥为:",i);
for(s=0; s<48; s++)
{
if(s%4==0)
printf(" ");
if(s<24)
{
subSecretKey[i][s] = subLeftSecretKey[s];
printf("%d",subSecretKey[i][s]);
}
else
{
subSecretKey[i][s] = subRightSecretKey[s-24];
printf("%d",subSecretKey[i][s]);
}
}
}
return 0;
}