⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 subkeyproduce.cpp

📁 DES算法的加解密实现,Visual C++实现
💻 CPP
字号:
#include <string.h>
#include <iostream.h>

#include "SubKeyProduce.h"
#ifndef SubKey
#include "GlobalData.h"
#endif

void circularLS1(int *ch)          //循环左移1位,ch为长28的int数组
{
	int temp=ch[0];
	for(int i=1;i<28;i++)ch[i-1]=ch[i];
	ch[27]=temp;
}

void circularLS2(int *ch)         //循环左移2位,ch为长28的int数组
{
	int temp1=ch[0];
	int temp2=ch[1];

	for(int i=2;i<28;i=i+2){
		ch[i-2]=ch[i];
		ch[i-1]=ch[i+1];
	}
	ch[26]=temp1;
	ch[27]=temp2;
}

void compresspermu(int *chl,int *chr,int turn)       //密钥作相应移位后,选择56位中的48位
{
	int CPTable[]={13,16,10,23,0,4,2,27,14,5,20,9,
                   22,18,11,3,25,7,15,6,26,19,12,1,
				   40,51,30,36,46,54,29,39,50,44,32,47,
				   43,48,38,55,33,52,45,41,49,35,28,31};

	for(int i=0;i<48;i++){               //生成第turn轮的48位子密钥                      
		if(CPTable[i]<28)
			SubKey[turn-1][i]=chl[CPTable[i]];          //chl和chr只用于赋值,不会改变
		else
			SubKey[turn-1][i]=chr[(CPTable[i]-28)];
	}
}
/***************************************************************************************************/

void SKeyProduce(char *KEY)
{
	char key[7];
	strcpy(key,KEY);

	/****把密钥转换成56位的整数****/
	int k[56];
	int index=55;
	for(int i=0;i<7;i++){
		for(int j=0;j<8;j++){
			k[index--]=(int)key[i]%2;
			key[i]>>1;
		}
	}

	/****将56位密钥分为两半****/
	int kl[28];
	int kr[28];
	memcpy(kl,k,56);
	memcpy(kr,k+56,56);

	/****循环左移、压缩置换生成48位子密码****/
	int j=1;
	while(j<17){
		switch(j){
		case 1:
		case 2:
		case 9:
		case 16:
			circularLS1(kl);
			circularLS1(kr);
			break;
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
		case 8:
		case 10:
		case 11:
		case 12:
		case 13:
		case 14:
		case 15:
			circularLS2(kl);
			circularLS2(kr);
			break;
		default:
			cout<<"生成子密钥过程出错"<<endl;
		}

		compresspermu(kl,kr,j);
		j++;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -