资源描述:
《des算法c++源代码》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
DES算法C++源代码文章来源:黑客中国更新时间:2005-12-12Des.cpp/********************************************************************//*DES(DataEncryptionStandard)*//*WrittenbyBunny*//*BanyetSoftLabs.1999*//*ALLRIGHTSRESERVED!*//*注意!版权所有!可以自由转载,但不得加以修改或删除!*//*E-mail:Assassin@ynmail.comHttp://Assassin.yeah.net*//********************************************************************//**************************************************************************//*注意:这只是标准DES算法的例子,所以速度并不是很快,不适用于大量数据加密的场*//*合.UNIX的密码也采用DES,不过它在里面加了点其它的东西.所以结果和DES的结果*//*不一样.由于使用了WINDOWS类库,所以必须在WINDOWS环境下编译.*//**************************************************************************/#include#include#include#include#include"Schedle.h"classCShift{public:DWORDLONGmask[16];intstep[16];CShift(){for(inti=0;i<16;i++){step=2;mask=0xc000000;}step[0]=step[1]=step[8]=step[15]=1;mask[0]=mask[1]=mask[8]=mask[15]=0x8000000;}};classCDES{public: CDES(){m_dwlKey=0;m_dwlData=0;ConvertTableToMask(dwlKey_PC_1,64);//PrintTable(dwlKey_PC_1,7,8);ConvertTableToMask(dwlKey_PC_2,56);ConvertTableToMask(dwlData_IP,64);ConvertTableToMask(dwlData_Expansion,32);ConvertTableToMask(dwlData_FP,64);ConvertTableToMask(dwlData_P,32);Generate_S();}voidPrintBit(DWORDLONG);voidEncryptKey(char*);unsignedchar*EncryptData(unsignedchar*);unsignedchar*DescryptData(unsignedchar*);private:voidConvertTableToMask(DWORDLONG*,int);voidGenerate_S(void);voidPrintTable(DWORDLONG*,int,int);DWORDLONGProcessByte(unsignedchar*,BOOL);DWORDLONGPermuteTable(DWORDLONG,DWORDLONG*,int);voidGenerate_K(void);voidEncryptKernel(void);DWORDLONGGenerate_B(DWORDLONG,DWORDLONG*);/*Forverifyschedulepermutationonly*/DWORDLONGUnPermuteTable(DWORDLONG,DWORDLONG*,int);/**************************************/DWORDLONGdwlData_S[9][4][16];CShiftm_shift;DWORDLONGm_dwlKey;DWORDLONGm_dwlData;DWORDLONGm_dwl_K[17];};voidCDES::EncryptKey(char*key){printf(" OriginalKey:%s",key);m_dwlKey=ProcessByte((unsignedchar*)key,TRUE);//PrintBit(m_dwlKey);m_dwlKey=PermuteTable(m_dwlKey,dwlKey_PC_1,56);//PrintBit(m_dwlKey); Generate_K();//printf(" ****************************************** ");}voidCDES::Generate_K(void){DWORDLONGC[17],D[17],tmp;C[0]=m_dwlKey>>28;D[0]=m_dwlKey&0xfffffff;for(inti=1;i<=16;i++){tmp=(C[i-1]&m_shift.mask[i-1])>>(28-m_shift.step[i-1]);C=((C[i-1]<>(28-m_shift.step[i-1]);D=((D[i-1]<>=1;i--;}returntmp;}voidCDES::PrintTable(DWORDLONG*dwlPara,intcol,introw){inti,j;for(i=0;i>1;}out=' ';strcpy(out,strrev(out));printf("%s**:%d ",out,i-space);}voidCDES::ConvertTableToMask(DWORDLONG*mask,intmax){inti=0;DWORDLONGnBit=1;while(mask!=0){nBit=1;nBit<<=max-mask;mask[i++]=nBit;}}voidCDES::Generate_S(void){inti;intj,m,n;m=n=0;j=1;for(i=0;i<512;i++){dwlData_S[j][m][n]=OS; n=(n+1)%16;if(!n){m=(m+1)%4;if(!m)j++;}}}unsignedchar*CDES::EncryptData(unsignedchar*block){unsignedchar*EncrytedData=newunsignedchar(15);printf(" OriginalData:%s ",block);m_dwlData=ProcessByte(block,0);//PrintBit(m_dwlData);m_dwlData=PermuteTable(m_dwlData,dwlData_IP,64);EncryptKernel();//PrintBit(m_dwlData);DWORDLONGbit6=m_dwlData;for(inti=0;i<11;i++){EncrytedData[7-i]=(unsignedchar)(bit6&0x3f)+46;bit6>>=6;}EncrytedData[11]=' ';printf(" AfterEncrypted:%s",EncrytedData);for(i=0;i<8;i++){EncrytedData[7-i]=(unsignedchar)(m_dwlData&0xff);m_dwlData>>=8;}EncrytedData[8]=' ';returnEncrytedData;}voidCDES::EncryptKernel(void){inti=1;DWORDLONGL[17],R[17],B[9],EK,PSB;L[0]=m_dwlData>>32;R[0]=m_dwlData&0xffffffff; for(i=1;i<=16;i++){L=R[i-1];R[i-1]=PermuteTable(R[i-1],dwlData_Expansion,48);//ExpansionREK=R[i-1]^m_dwl_K;//EPermutationPSB=Generate_B(EK,B);//PPermutationR=L[i-1]^PSB;}R[16]<<=32;m_dwlData=R[16]|L[16];m_dwlData=PermuteTable(m_dwlData,dwlData_FP,64);}unsignedchar*CDES::DescryptData(unsignedchar*desData){inti=1;unsignedchar*DescryptedData=newunsignedchar(15);DWORDLONGL[17],R[17],B[9],EK,PSB;DWORDLONGdataPara;dataPara=ProcessByte(desData,0);dataPara=PermuteTable(dataPara,dwlData_IP,64);R[16]=dataPara>>32;L[16]=dataPara&0xffffffff;for(i=16;i>=1;i--){R[i-1]=L;L=PermuteTable(L,dwlData_Expansion,48);//ExpansionLEK=L^m_dwl_K;//EPermutationPSB=Generate_B(EK,B);//PPermutationL[i-1]=R^PSB;}L[0]<<=32;dataPara=L[0]|R[0];dataPara=PermuteTable(dataPara,dwlData_FP,64);//PrintBit(dataPara);for(i=0;i<8;i++){DescryptedData[7-i]=(unsignedchar)(dataPara&0xff);dataPara>>=8; }DescryptedData[8]=' ';printf(" AfterDecrypted:%s ",DescryptedData);returnDescryptedData;}DWORDLONGCDES::Generate_B(DWORDLONGEKPara,DWORDLONG*block){inti,m,n;DWORDLONGtmp=0;for(i=8;i>0;i--){block=EKPara&0x3f;m=(int)(block&0x20)>>4;m|=block&0x01;n=(int)(block<<1)>>2;block=dwlData_S[m][n];EKPara>>=6;}for(i=1;i<=8;i++){tmp|=block;tmp<<=4;}tmp>>=4;tmp=PermuteTable(tmp,dwlData_P,32);returntmp;}voidmain(void){CDESdes;des.EncryptKey("12345678");unsignedchar*result=des.EncryptData((unsignedchar*)"DemoData");des.DescryptData(result);} DES算法源代码伊洛方清发表于2006-1-1314:26:00看到网上到处是关于DES的英文文章,有的只是简单的翻译,可就是没有源代码,可苦了那些寻找源代码的人。在vc下建立一个控制台工程,把下面的des.h des.c 和sample.c分别存为文件就行了,然后编译,sample是一个应用des算法的例子.关于des算法原理的废话就不多说了,网上那都是.代码如下://des.hvoidendes(unsignedchara[8],unsignedcharb[8],unsignedcharc[8]);voidundes(unsignedchara[8],unsignedcharb[8],unsignedcharc[8]);unsignedchar*byte2bit(unsignedchara[8],unsignedcharb[8]);unsignedchar*bit2byte(unsignedchara[8],unsignedcharb[8]);voidkeychange(unsignedcharx[8],unsignedchary[16][8]);voids_replace(unsignedchara[8]);///////////////////////////////////////des.cunsignedchar*byte2bit(unsignedcharbyte[64],unsignedcharbit[8])/*change64byteto64bit(8byte)*/{inti=0;/*byte1*/for(i=0;i<=7;i++){if(byte[0]==0x1)bit[0]=bit[0]|0x80;elsebit[0]=bit[0]&0x7f;if(byte[1]==0x1)bit[0]=bit[0]|0x40;elsebit[0]=bit[0]&0xbf;if(byte[2]==0x1)bit[0]=bit[0]|0x20;elsebit[0]=bit[0]&0xdf;if(byte[3]==0x1)bit[0]=bit[0]|0x10;elsebit[0]=bit[0]&0xef;if(byte[4]==0x1)bit[0]=bit[0]|0x08;elsebit[0]=bit[0]&0xf7;if(byte[5]==0x1)bit[0]=bit[0]|0x04;elsebit[0]=bit[0]&0xfb;if(byte[6]==0x1)bit[0]=bit[0]|0x02;elsebit[0]=bit[0]&0xfd;if(byte[7]==0x1)bit[0]=bit[0]|0x01;elsebit[0]=bit[0]&0xfe;}/*byte2*/ for(i=8;i<=15;i++){if(byte[8]==0x1)bit[1]=bit[1]|0x80;elsebit[1]=bit[1]&0x7f;if(byte[9]==0x1)bit[1]=bit[1]|0x40;elsebit[1]=bit[1]&0xbf;if(byte[10]==0x1)bit[1]=bit[1]|0x20;elsebit[1]=bit[1]&0xdf;if(byte[11]==0x1)bit[1]=bit[1]|0x10;elsebit[1]=bit[1]&0xef;if(byte[12]==0x1)bit[1]=bit[1]|0x08;elsebit[1]=bit[1]&0xf7;if(byte[13]==0x1)bit[1]=bit[1]|0x04;elsebit[1]=bit[1]&0xfb;if(byte[14]==0x1)bit[1]=bit[1]|0x02;elsebit[1]=bit[1]&0xfd;if(byte[15]==0x1)bit[1]=bit[1]|0x01;elsebit[1]=bit[1]&0xfe;}/*byte3*/for(i=16;i<=23;i++){if(byte[16]==0x1)bit[2]=bit[2]|0x80;elsebit[2]=bit[2]&0x7f;if(byte[17]==0x1)bit[2]=bit[2]|0x40;elsebit[2]=bit[2]&0xbf;if(byte[18]==0x1)bit[2]=bit[2]|0x20;elsebit[2]=bit[2]&0xdf;if(byte[19]==0x1)bit[2]=bit[2]|0x10;elsebit[2]=bit[2]&0xef;if(byte[20]==0x1)bit[2]=bit[2]|0x08;elsebit[2]=bit[2]&0xf7;if(byte[21]==0x1)bit[2]=bit[2]|0x04;elsebit[2]=bit[2]&0xfb;if(byte[22]==0x1)bit[2]=bit[2]|0x02;elsebit[2]=bit[2]&0xfd;if(byte[23]==0x1)bit[2]=bit[2]|0x01;elsebit[2]=bit[2]&0xfe;}/*byte4*/for(i=24;i<=31;i++){if(byte[24]==0x1)bit[3]=bit[3]|0x80;elsebit[3]=bit[3]&0x7f; if(byte[25]==0x1)bit[3]=bit[3]|0x40;elsebit[3]=bit[3]&0xbf;if(byte[26]==0x1)bit[3]=bit[3]|0x20;elsebit[3]=bit[3]&0xdf;if(byte[27]==0x1)bit[3]=bit[3]|0x10;elsebit[3]=bit[3]&0xef;if(byte[28]==0x1)bit[3]=bit[3]|0x08;elsebit[3]=bit[3]&0xf7;if(byte[29]==0x1)bit[3]=bit[3]|0x04;elsebit[3]=bit[3]&0xfb;if(byte[30]==0x1)bit[3]=bit[3]|0x02;elsebit[3]=bit[3]&0xfd;if(byte[31]==0x1)bit[3]=bit[3]|0x01;elsebit[3]=bit[3]&0xfe;}/*byte5*/for(i=32;i<=39;i++){if(byte[32]==0x1)bit[4]=bit[4]|0x80;elsebit[4]=bit[4]&0x7f;if(byte[33]==0x1)bit[4]=bit[4]|0x40;elsebit[4]=bit[4]&0xbf;if(byte[34]==0x1)bit[4]=bit[4]|0x20;elsebit[4]=bit[4]&0xdf;if(byte[35]==0x1)bit[4]=bit[4]|0x10;elsebit[4]=bit[4]&0xef;if(byte[36]==0x1)bit[4]=bit[4]|0x08;elsebit[4]=bit[4]&0xf7;if(byte[37]==0x1)bit[4]=bit[4]|0x04;elsebit[4]=bit[4]&0xfb;if(byte[38]==0x1)bit[4]=bit[4]|0x02;elsebit[4]=bit[4]&0xfd;if(byte[39]==0x1)bit[4]=bit[4]|0x01;elsebit[4]=bit[4]&0xfe;}/*byte6*/for(i=40;i<=47;i++){if(byte[40]==0x1)bit[5]=bit[5]|0x80;elsebit[5]=bit[5]&0x7f;if(byte[41]==0x1)bit[5]=bit[5]|0x40;elsebit[5]=bit[5]&0xbf;if(byte[42]==0x1)bit[5]=bit[5]|0x20;elsebit[5]=bit[5]&0xdf; if(byte[43]==0x1)bit[5]=bit[5]|0x10;elsebit[5]=bit[5]&0xef;if(byte[44]==0x1)bit[5]=bit[5]|0x08;elsebit[5]=bit[5]&0xf7;if(byte[45]==0x1)bit[5]=bit[5]|0x04;elsebit[5]=bit[5]&0xfb;if(byte[46]==0x1)bit[5]=bit[5]|0x02;elsebit[5]=bit[5]&0xfd;if(byte[47]==0x1)bit[5]=bit[5]|0x01;elsebit[5]=bit[5]&0xfe;}/*byte7*/for(i=48;i<=55;i++){if(byte[48]==0x1)bit[6]=bit[6]|0x80;elsebit[6]=bit[6]&0x7f;if(byte[49]==0x1)bit[6]=bit[6]|0x40;elsebit[6]=bit[6]&0xbf;if(byte[50]==0x1)bit[6]=bit[6]|0x20;elsebit[6]=bit[6]&0xdf;if(byte[51]==0x1)bit[6]=bit[6]|0x10;elsebit[6]=bit[6]&0xef;if(byte[52]==0x1)bit[6]=bit[6]|0x08;elsebit[6]=bit[6]&0xf7;if(byte[53]==0x1)bit[6]=bit[6]|0x04;elsebit[6]=bit[6]&0xfb;if(byte[54]==0x1)bit[6]=bit[6]|0x02;elsebit[6]=bit[6]&0xfd;if(byte[55]==0x1)bit[6]=bit[6]|0x01;elsebit[6]=bit[6]&0xfe;}/*byte8*/for(i=56;i<=63;i++){if(byte[56]==0x1)bit[7]=bit[7]|0x80;elsebit[7]=bit[7]&0x7f;if(byte[57]==0x1)bit[7]=bit[7]|0x40;elsebit[7]=bit[7]&0xbf;if(byte[58]==0x1)bit[7]=bit[7]|0x20;elsebit[7]=bit[7]&0xdf;if(byte[59]==0x1)bit[7]=bit[7]|0x10;elsebit[7]=bit[7]&0xef;if(byte[60]==0x1)bit[7]=bit[7]|0x08;elsebit[7]=bit[7]&0xf7; if(byte[61]==0x1)bit[7]=bit[7]|0x04;elsebit[7]=bit[7]&0xfb;if(byte[62]==0x1)bit[7]=bit[7]|0x02;elsebit[7]=bit[7]&0xfd;if(byte[63]==0x1)bit[7]=bit[7]|0x01;elsebit[7]=bit[7]&0xfe;}returnbit;}/*endofbyte2bit*//*----------------------------------------------------*//*bit2byte*//*----------------------------------------------------*/unsignedchar*bit2byte(unsignedcharbit[8],unsignedcharbyte[64])/*change64bit(8byte)to64byte*/{inti=0;for(i=0;i<=63;i++){byte[i]=0x0;}for(i=0;i<=7;i++){if((bit[i]&0x80)==0x80)byte[i*8+0]=0x01;if((bit[i]&0x40)==0x40)byte[i*8+1]=0x01;if((bit[i]&0x20)==0x20)byte[i*8+2]=0x01;if((bit[i]&0x10)==0x10)byte[i*8+3]=0x01;if((bit[i]&0x08)==0x08)byte[i*8+4]=0x01;if((bit[i]&0x04)==0x04)byte[i*8+5]=0x01;if((bit[i]&0x02)==0x02)byte[i*8+6]=0x01;if((bit[i]&0x01)==0x01)byte[i*8+7]=0x01;}returnbyte;}/*endofbit2byte*//*--------------------------------------------------*//*changethekey*//*--------------------------------------------------*/keychange(unsignedcharoldkey[8],unsignedcharnewkey[16][8]){inti=0,j=0,k=0;intpc_1[56]={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};intpc_2[48]={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};intccmovebit[16]={1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};unsignedcharoldkey_byte[64];unsignedcharoldkey_byte1[64];unsignedcharoldkey_byte2[64];unsignedcharoldkey_c[28];unsignedcharoldkey_d[28];unsignedcharcc_temp;unsignedcharnewkey_byte[16][64];bit2byte(oldkey,oldkey_byte);/*changetobyte*/for(i=0;i<=55;i++)oldkey_byte1[i]=oldkey_byte[pc_1[i]-1];/*gotoPC-1*/for(i=0;i<=27;i++)oldkey_c[i]=oldkey_byte1[i];/*move28bit->c0*/for(i=28;i<=55;i++)oldkey_d[i-28]=oldkey_byte1[i];/*moveother28bit->d0*//*cc_movebit:getc1-16,d1-16*/for(i=0;i<=15;i++){for(j=1;j<=ccmovebit[i];j++){cc_temp=oldkey_c[0];/*moveoutthefirstbit*/for(k=0;k<=26;k++){oldkey_c[k]=oldkey_c[k+1];}oldkey_c[27]=cc_temp;/*movethefirstbittothelastbit*/cc_temp=oldkey_d[0];/*moveoutthefirstbit*/for(k=0;k<=26;k++){oldkey_d[k]=oldkey_d[k+1];}oldkey_d[27]=cc_temp;/*movethefirstbittothelastbit*/}/*cc_movebit*//*gotopc-2changebit*/for(k=0;k<=27;k++)oldkey_byte2[k]=oldkey_c[k];for(k=28;k<=55;k++)oldkey_byte2[k]=oldkey_d[k-28]; /*addc(i)+d(i)->forpc-2change56bitto48bitk(i)*/for(k=0;k<=47;k++)newkey_byte[i][k]=oldkey_byte2[pc_2[k]-1];/*readytonextk(i)*/}/*endofoneofchangethe48bitkey*//*bytetobitfor48bitnewkey*/for(i=0;i<=15;i++)byte2bit(newkey_byte[i],newkey[i]);}/*endofkeychange*//*--------------------------------------------------*//*dataencryption*//*--------------------------------------------------*/endes(unsignedcharm_bit[8],unsignedchark_bit[8],unsignedchare_bit[8]){intip[64]={58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8,57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7};intip_1[64]={40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29,36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25};inte[48]={32,1,2,3,4,5,4,5,6,7,8,9,8,9,10,11,12,13,12,13,14,15,16,17,16,17,18,19,20,21,20,21,22,23,24,25,24,25,26,27,28,29,28,29,30,31,32,1};unsignedcharm_bit1[8]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0};unsignedcharm_byte[64];unsignedcharm_byte1[64];unsignedcharkey_n[16][8];unsignedcharl_bit[17][8]; unsignedcharr_bit[17][8];unsignedchare_byte[64];unsignedchare_byte1[64];unsignedcharr_byte[64];unsignedcharr_byte1[64];inti=0,j=0;/*initialize*/for(i=0;i<=15;i++){for(j=0;j<=7;j++){l_bit[i][j]=0x0;r_bit[i][j]=0x0;key_n[i][j]=0x0;}}for(i=0;i<=63;i++){m_byte[i]=0x0;m_byte1[i]=0x0;r_byte[i]=0x0;r_byte1[i]=0x0;e_byte[i]=0x0;e_byte1[i]=0x0;}keychange(k_bit,key_n);/*getthe48bitkeyx16(16rowsx6byteinkey_n)*/bit2byte(m_bit,m_byte);/*changetobyte*/for(i=0;i<=63;i++)m_byte1[i]=m_byte[ip[i]-1];/*gotoIPswapbit*/byte2bit(m_byte1,m_bit1);/*re-changetobit*/for(i=0;i<=3;i++)l_bit[0][i]=m_bit1[i];/*moveleft32bit->l0*/for(i=4;i<=7;i++)r_bit[0][i-4]=m_bit1[i];/*moveright32bit->r0*/for(i=1;i<=16;i++)/*16layer*/{for(j=0;j<=3;j++)l_bit[i][j]=r_bit[i-1][j];/*L(n)=R(n-1)*//*computf(R(n-1),k)*/bit2byte(r_bit[i-1],r_byte);for(j=0;j<=47;j++)r_byte1[j]=r_byte[e[j]-1];/*gotoEswapbit*/byte2bit(r_byte1,r_bit[i-1]);/*nowr_bitis48bit*//*xor48bitkey*/for(j=0;j<=5;j++)r_bit[i-1][j]=r_bit[i-1][j]^key_n[i-1][j];/*gotoand*/s_replace(r_bit[i-1]);/*change48bitr_bit[i-1]->32bitr_bit[i-1]*/for(j=0;j<=3;j++)/*getnextr_bit*/{ r_bit[i][j]=l_bit[i-1][j]^r_bit[i-1][j];/*f(R(n-1),k)*/}}/*endofendes*/for(i=0;i<=3;i++)e_bit[i]=r_bit[16][i];for(i=4;i<=7;i++)e_bit[i]=l_bit[16][i-4];/*r_bit+l_bit->e_bit(64bit)*/bit2byte(e_bit,e_byte);/*changetobyteforswapbitIP-1*/for(i=0;i<=63;i++)e_byte1[i]=e_byte[ip_1[i]-1];/*gotoIP-1swapbit*/byte2bit(e_byte1,e_bit);/*gote_bit*/}/*endofdataencryption*//*--------------------------------------------------*//*datauncryption*//*--------------------------------------------------*/undes(unsignedcharm_bit[8],unsignedchark_bit[8],unsignedchare_bit[8])/*NOTE:infact,m_bitisencryptiondata,e_bitisuncryption*/{intip[64]={58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8,57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7};intip_1[64]={40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29,36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25};inte[48]={32,1,2,3,4,5,4,5,6,7,8,9,8,9,10,11,12,13,12,13,14,15,16,17,16,17,18,19,20,21,20,21,22,23,24,25,24,25,26,27,28,29,28,29,30,31,32,1};unsignedcharm_bit1[8]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0}; unsignedcharm_byte[64];unsignedcharm_byte1[64];unsignedcharkey_n[16][8];unsignedcharl_bit[17][8];unsignedcharr_bit[17][8];unsignedchare_byte[64];unsignedchare_byte1[64];unsignedcharl_byte[64];unsignedcharl_byte1[64];inti=0,j=0;/*initialize*/for(i=0;i<=15;i++){for(j=0;j<=7;j++){l_bit[i][j]=0x0;r_bit[i][j]=0x0;key_n[i][j]=0x0;}}for(i=0;i<=63;i++){m_byte[i]=0x0;m_byte1[i]=0x0;l_byte[i]=0x0;l_byte1[i]=0x0;e_byte[i]=0x0;e_byte1[i]=0x0;}keychange(k_bit,key_n);/*getthe48bitkeyx16(16rowsx6byteinkey_n)*/bit2byte(m_bit,m_byte);/*changetobyte*/for(i=0;i<=63;i++)m_byte1[i]=m_byte[ip[i]-1];/*gotoIPswapbit*/byte2bit(m_byte1,m_bit1);/*re-changetobit*/for(i=0;i<=3;i++)r_bit[16][i]=m_bit1[i];/*moveleft32bit->r16*/for(i=4;i<=7;i++)l_bit[16][i-4]=m_bit1[i];/*moveright32bit->l16*/for(i=16;i>=1;i--)/*->(16)layerfrom16->1*/{for(j=0;j<=3;j++)r_bit[i-1][j]=l_bit[i][j];/*R(n-1)=L(n)*//*computf(L(n),k)*/bit2byte(l_bit[i],l_byte);for(j=0;j<=47;j++)l_byte1[j]=l_byte[e[j]-1];/*gotoEswapbit*/byte2bit(l_byte1,l_bit[i]);/*nowr_bitis48bit*//*xor48bitkey*/for(j=0;j<=5;j++)l_bit[i][j]=l_bit[i][j]^key_n[i-1][j]; /*gotoand*/s_replace(l_bit[i]);/*change48bitl_bit[i]->32bitl_bit[i]*/for(j=0;j<=3;j++)/*getPREVl_bit*/{l_bit[i-1][j]=r_bit[i][j]^l_bit[i][j];/*f(L(n),k)*/}}/*endofundes*/for(i=0;i<=3;i++)e_bit[i]=l_bit[0][i];for(i=4;i<=7;i++)e_bit[i]=r_bit[0][i-4];/*r_bit+l_bit->e_bit(64bit)*/bit2byte(e_bit,e_byte);/*changetobyteforswapbitIP-1*/for(i=0;i<=63;i++)e_byte1[i]=e_byte[ip_1[i]-1];/*gotoIP-1swapbit*/byte2bit(e_byte1,e_bit);/*gote_bit*//*now!infact,thee_bitistheuncryptiondata.*/}/*endofuncryptiondata*//*--------------------------------------------------*//*S_replace*//*--------------------------------------------------*/s_replace(unsignedchars_bit[8]){intp[32]={16,7,20,21,29,12,28,17,1,15,23,26,5,18,31,10,2,8,24,14,32,27,3,9,19,13,30,6,22,11,4,25};unsignedchars1[4][16]={14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13};unsignedchars2[4][16]={15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9};unsignedchars3[4][16]={10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12}; unsignedchars4[4][16]={7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14};unsignedchars5[4][16]={2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3,};unsignedchars6[4][16]={12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13};unsignedchars7[4][16]={4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12};unsignedchars8[4][16]={13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11};inti=0,j=0;unsignedchars_byte[64];unsignedchars_byte1[64];unsignedchars_bit_temp[8]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0};unsignedcharrow=0,col=0;unsignedchars_out_bit[8]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0};unsignedchars_out_bit1[8]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0};/*initialize*/for(i=0;i<=63;i++)s_byte[i]=0x0;for(i=0;i<=63;i++)s_byte1[i]=0x0;/*change48bit(8bitx6byte)to48bit(6bitx8byte)*/bit2byte(s_bit,s_byte);for(i=0;i<=7;i++){for(j=0;j<=63;j++)s_byte1[j]=0x0;/*cleartemp*/s_byte1[6]=s_byte[i*6];/*getbit0in6bit*/s_byte1[7]=s_byte[i*6+5];/*getbit5in6bit*/byte2bit(s_byte1,s_bit_temp);/*000000??*/row=s_bit_temp[0];/*getrow[i]*/ for(j=0;j<=63;j++)s_byte1[j]=0x0;/*cleartemp*/s_byte1[4]=s_byte[i*6+1];/*0000????*/s_byte1[5]=s_byte[i*6+2];s_byte1[6]=s_byte[i*6+3];s_byte1[7]=s_byte[i*6+4];byte2bit(s_byte1,s_bit_temp);col=s_bit_temp[0];/*getcolumninStable*//*getnumberfromStablewithrowandcol*/switch(i){case0:s_out_bit[i]=s1[row][col];break;case1:s_out_bit[i]=s2[row][col];break;case2:s_out_bit[i]=s3[row][col];break;case3:s_out_bit[i]=s4[row][col];break;case4:s_out_bit[i]=s5[row][col];break;case5:s_out_bit[i]=s6[row][col];break;case6:s_out_bit[i]=s7[row][col];break;case7:s_out_bit[i]=s8[row][col];break;};}/*s_out_bit[0-7]:0000????0000????0000????0000????...0000????*//*change64bitto32bit:clean0000(high4bit)*/s_out_bit1[0]=(s_out_bit[0]<<4)+s_out_bit[1];s_out_bit1[1]=(s_out_bit[2]<<4)+s_out_bit[3];s_out_bit1[2]=(s_out_bit[4]<<4)+s_out_bit[5];s_out_bit1[3]=(s_out_bit[6]<<4)+s_out_bit[7];/*nows_out_bit1[0-7]=????????????????????????????????0000..*/for(i=0;i<=63;i++)s_byte[i]=0x0;for(i=0;i<=63;i++)s_byte1[i]=0x0; bit2byte(s_out_bit1,s_byte);/*changebyteforPswapbit*/for(i=0;i<=31;i++)s_byte1[i]=s_byte[p[i]-1];/*gotoPswapbit*/for(i=0;i<=7;i++)s_bit[i]=0x0;byte2bit(s_byte1,s_bit);/*now!wegot32bitf(R,K)*/}/*endofS_replace*////////////////////////////////////////sample.c#include"stdio.h"#include"des.h"voidmain(){/*SampleData*/unsignedcharm_bit[8]={'a','b','b','x','y','z','m','n'};/*uncode*/unsignedchark_bit[8]={'[','Z','W','g','j','V','g','n'};/*key*/unsignedchare_bit[8]={0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0};/*encode*//*SampleData*/inti=0;printf(" ThisisasampleforDESfunctionbyAtan1998/02/28");printf(" Passwordis:[ZWgjVgn");printf(" UncryptionData:");for(i=0;i<=7;i++)printf("%c",m_bit[i]);endes(m_bit,k_bit,e_bit);printf(" EncryptionData:");for(i=0;i<=7;i++)printf("%c",e_bit[i]);/*clearm_bit*/for(i=0;i<=7;i++)m_bit[i]=0x0;undes(e_bit,k_bit,m_bit);printf(" UncryptionData:");for(i=0;i<=7;i++)printf("%c",m_bit[i]);printf(" ");}/*endofmainsample*/filename:RSA.java/**CreatedonMar3,2005**TODOTochangethetemplateforthisgeneratedfilegoto *Window-Preferences-Java-CodeStyle-CodeTemplates*/importjava.math.BigInteger;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.FileWriter;importjava.io.FileReader;importjava.io.BufferedReader;importjava.util.StringTokenizer;/***@authorSteve**TODOTochangethetemplateforthisgeneratedtypecommentgoto*Window-Preferences-Java-CodeStyle-CodeTemplates*/publicclassRSA{/***BigInteger.ZERO*/privatestaticfinalBigIntegerZERO=BigInteger.ZERO;/***BigInteger.ONE*/privatestaticfinalBigIntegerONE=BigInteger.ONE;/***PseudoBigInteger.TWO*/privatestaticfinalBigIntegerTWO=newBigInteger("2");privateBigIntegermyKey;privateBigIntegermyMod;privateintblockSize; publicRSA(BigIntegerkey,BigIntegern,intb){myKey=key;myMod=n;blockSize=b;}publicvoidencodeFile(Stringfilename){byte[]bytes=newbyte[blockSize/8+1];byte[]temp;inttempLen;InputStreamis=null;FileWriterwriter=null;try{is=newFileInputStream(filename);writer=newFileWriter(filename+".enc");}catch(FileNotFoundExceptione1){System.out.println("Filenotfound:"+filename);}catch(IOExceptione1){System.out.println("Filenotfound:"+filename+".enc");}/***Writeencodedmessageto'filename'.enc*/try{while((tempLen=is.read(bytes,1,blockSize/8))>0){for(inti=tempLen+1;ibase^powwithinthemodular*domainofmod.**@parambasethebasetoberaised*@parampowthepowertowhichthebasewillberaisded*@parammodthemodulardomainoverwhichtoperformthisoperation*@returnbase^powwithinthemodular*domainofmod.*/publicBigIntegerencodeDecode(BigIntegerbase){BigIntegera=ONE;BigIntegers=base;BigIntegern=myKey;while(!n.equals(ZERO)){if(!n.mod(TWO).equals(ZERO)) a=a.multiply(s).mod(myMod);s=s.pow(2).mod(myMod);n=n.divide(TWO);}returna;}}在这里提供两个版本的RSA算法JAVA实现的代码下载:1.来自于http://www.javafr.com/code.aspx?ID=27020的RSA算法实现源代码包:http://zeal.newmenbase.net/attachment/JavaFR_RSA_Source.rar2.来自于http://www.ferrara.linux.it/Members/lucabariani/RSA/implementazioneRsa/的实现:http://zeal.newmenbase.net/attachment/sorgentiJava.tar.gz-源代码包http://zeal.newmenbase.net/attachment/algoritmoRSA.jar-编译好的jar包另外关于RSA算法的php实现请参见文章:php下的RSA算法实现关于使用VB实现RSA算法的源代码下载(此程序采用了psc1算法来实现快速的RSA加密):http://zeal.newmenbase.net/attachment/vb_PSC1_RSA.rarRSA加密的JavaScript实现:http://www.ohdave.com/rsa/在ASP.Net中实现RSA加密作者:无从考证来源:中国软件发布时间:2005-8-2320:32:37发布人:hncj减小字体增大字体在我们实际运用中,加密是保证数据安全的重要手段。以前使用ASP时,对数据加密可以使用MD5和SHA1算法,这两种算法虽然快捷有效,但是无法对通过它们加密的密文进行反运算,即是解密。因此需要解密数据的场合,这两种方法就不太适合了。当然你也可以自己编写适用的加密和解密程序,不过这对编写者的数学水平有很高的要求,一般人是很难做到的。现在,随着ASP.Net的推出,彻底改变了以前ASP下的编程模式。我们能够利用.Net Framework中的类提供的加密服务来保证数据安全。目前应用较为广泛的加密方法是使用RSA算法进行加密。在.NetFramework中与RSA加密算法相关的类主要有两个:RSA类和RSACryptoServiceProvider类。按照MSDN的说法RSA类是“表示RSA算法的所有实现均从中继承的基类”,而RSACryptoServiceProvider类是“使用加密服务提供程序(CSP)提供的RSA算法的实现执行不对称加密和解密”。另外,“表示RSA算法的标准参数”的RSAParameters结构也是很重要的,它保存了RSA算法的参数。由于介绍RSA算法原理的文章或书籍比较多,大家可以参阅一下,在此就不复述了。下面着重介绍一下如何在ASP.Net中实现RSA加密。RSA参数的产生:RSA参数的类型就是上面提到的RSAParameters结构,查阅MSDN可知其包含了D、DP、DQ、Exponent、InverseQ、Modulus、P、Q八个字段。加密时仅需要Exponent和Modulus两个值,可看成公钥。解密时所有字段都需要,可看成私钥。下面这段程序显示了如何产生RSA两个参数:RSACryptoServiceProviderrsa=newRSACryptoServiceProvider();RSAParametersrsaParamsExcludePrivate=rsa.ExportParameters(false);RSAParametersrsaParamsIncludePrivate=rsa.ExportParameters(true);RSACryptoServiceProvider类的ExportParameters(bool)方法用于导出RSA参数,true表示导出上述八个字段的“私钥”,false表示导出“公钥”。使用RSA参数进行加密解密:这一步需要把上面两个参数导入到RSACryptoServiceProvider类对象中,再用它对数据进行加密。如下面的代码所示,我们可以写一个函数来完成加密过程:Publicbyte[]RSAEncrypt(byte[]b){RSACryptoServiceProviderrsa=newRSACryptoServiceProvider();rsa.ImportParameters(rsaParamsExcludePrivate);//导入公钥byte[]EncryptedData=rsa.Encrypt(DataToEncrypt,false);returnEncryptedData;}解密时只要把rsa.ImportParameters(rsaParamsExcludePrivate)换成rsa.ImportParameters(rsaParamsExcludePrivate),再把Encrypt换成Decrypt就行了。保存和加载RSA参数:RSA参数可以保存为XML格式,下面代码说明了如何保存和加载(只列出了关键部分)保存:RSACryptoServiceProviderrsa=newRSACryptoServiceProvider();StreamWriterwriter=newStreamWriter(@"d:PublicAndPrivateKey.xml");stringPPKeyXml=rsa.ToXmlString(true);//保存私钥writer.Write(PPKeyXml);writer.Close();writer=newStreamWriter(@"d:PublicKey.xml");stringPKeyXml=rsa.ToXmlString(false);//保存公钥writer.Write(PKeyXml);writer.Close();读取:RSACryptoServiceProviderrsa=newRSACryptoServiceProvider();StreamReaderreader=newStreamReader(@"d:PublicKey.xml"); stringPKey=reader.ReadToEnd();rsa.FromXmlString(PKey);reader.Close();StreamReaderreader=newStreamReader(@"d:PublicAndPrivateKey.xml");stringPPKey=reader.ReadToEnd();reader.Close();ToXmlString和ExportParameters方法类似,false表示保存“公钥”,true表示保存“私钥”。以上就是在ASP.Net中实现RSA加密的主要方法。最后,提供一个完整的示例供下载。下载地址我所知道的就是我一无所知———苏格拉底java非对称加密的源代码(RSA)2006-05-3010:29:34天气:晴朗心情:高兴鉴于rsa加密的重要性和相关源代码的匮乏,经过整理特此贴出。需要下载bcprov-jdk14-123.jar。 importjavax.crypto.Cipher; importjava.security.*; importjava.security.spec.RSAPublicKeySpec; importjava.security.spec.RSAPrivateKeySpec; importjava.security.spec.InvalidKeySpecException; importjava.security.interfaces.RSAPrivateKey; importjava.security.interfaces.RSAPublicKey; importjava.io.*; importjava.math.BigInteger; /** *RSA工具类。提供加密,解密,生成密钥对等方法。 *需要到http://www.bouncycastle.org/latest_releases.html下载bcprov-jdk14-123.jar。 * */ publicclassRSAUtil{ /** *生成密钥对 *@returnKeyPair *@throwsEncryptException */ publicstaticKeyPairgenerateKeyPair()throwsEncryptException{ try{ KeyPairGeneratorkeyPairGen=KeyPairGenerator.getInstance("RSA", neworg.bouncycastle.jce.provider.BouncyCastleProvider()); finalintKEY_SIZE=1024;//没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低 keyPairGen.initialize(KEY_SIZE,newSecureRandom()); KeyPairkeyPair=keyPairGen.genKeyPair(); returnkeyPair; }catch(Exceptione){ thrownewEncryptException(e.getMessage()); } } /** *生成公钥 *@parammodulus *@parampublicExponent *@returnRSAPublicKey *@throwsEncryptException */ publicstaticRSAPublicKeygenerateRSAPublicKey(byte[]modulus,byte[]publicExponent)throwsEncryptException{ KeyFactorykeyFac=null; try{ keyFac=KeyFactory.getInstance("RSA",neworg.bouncycastle.jce.provider.BouncyCastleProvider()); }catch(NoSuchAlgorithmExceptionex){ thrownewEncryptException(ex.getMessage()); } RSAPublicKeySpecpubKeySpec=newRSAPublicKeySpec(newBigInteger(modulus),newBigInteger(publicExponent)); try{ return(RSAPublicKey)keyFac.generatePublic(pubKeySpec); }catch(InvalidKeySpecExceptionex){ thrownewEncryptException(ex.getMessage()); } } /** *生成私钥 *@parammodulus *@paramprivateExponent *@returnRSAPrivateKey *@throwsEncryptException */ publicstaticRSAPrivateKeygenerateRSAPrivateKey(byte[]modulus,byte[]privateExponent)throwsEncryptException{ KeyFactorykeyFac=null; try{ keyFac=KeyFactory.getInstance("RSA",neworg.bouncycastle.jce.provider.BouncyCastleProvider()); }catch(NoSuchAlgorithmExceptionex){ thrownewEncryptException(ex.getMessage()); } RSAPrivateKeySpecpriKeySpec=newRSAPrivateKeySpec(newBigInteger(modulus),newBigInteger(privateExponent)); try{ return(RSAPrivateKey)keyFac.generatePrivate(priKeySpec); }catch(InvalidKeySpecExceptionex){ thrownewEncryptException(ex.getMessage()); } } /** *加密 *@paramkey加密的密钥 *@paramdata待加密的明文数据 *@return加密后的数据 *@throwsEncryptException */ publicstaticbyte[]encrypt(Keykey,byte[]data)throwsEncryptException{ try{ Ciphercipher=Cipher.getInstance("RSA",neworg.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE,key); intblockSize=cipher.getBlockSize();//获得加密块大小,如:加密前数据为128个byte,而key_size=1024加密块大小为127byte,加密后为128个byte;因此共有2个加密块,第一个127byte第二个为1个byte intoutputSize=cipher.getOutputSize(data.length);//获得加密块加密后块大小 intleavedSize=data.length%blockSize; intblocksSize=leavedSize!=0?data.length/blockSize1:data.length/blockSize; byte[]raw=newbyte[outputSize*blocksSize]; inti=0; while(data.length-i*blockSize>0){ if(data.length-i*blockSize>blockSize) cipher.doFinal(data,i*blockSize,blockSize,raw,i*outputSize); else cipher.doFinal(data,i*blockSize,data.length-i*blockSize,raw,i*outputSize); //这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。 i; } returnraw; }catch(Exceptione){ thrownewEncryptException(e.getMessage()); } } /** *解密 *@paramkey解密的密钥 *@paramraw已经加密的数据 *@return解密后的明文 *@throwsEncryptException */ publicstaticbyte[]decrypt(Keykey,byte[]raw)throwsEncryptException{ try{ Ciphercipher=Cipher.getInstance("RSA",neworg.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(cipher.DECRYPT_MODE,key); intblockSize=cipher.getBlockSize(); ByteArrayOutputStreambout=newByteArrayOutputStream(64); intj=0; while(raw.length-j*blockSize>0){ bout.write(cipher.doFinal(raw,j*blockSize,blockSize)); j; } returnbout.toByteArray(); }catch(Exceptione){ thrownewEncryptException(e.getMessage()); } } /** * *@paramargs *@throwsException */ publicstaticvoidmain(String[]args)throwsException{ Filefile=newFile("test.html"); FileInputStreamin=newFileInputStream(file); ByteArrayOutputStreambout=newByteArrayOutputStream(); byte[]tmpbuf=newbyte[1024]; intcount=0; while((count=in.read(tmpbuf))!=-1){ bout.write(tmpbuf,0,count); tmpbuf=newbyte[1024]; } in.close(); byte[]orgData=bout.toByteArray(); KeyPairkeyPair=RSAUtil.generateKeyPair(); RSAPublicKeypubKey=(RSAPublicKey)keyPair.getPublic(); RSAPrivateKeypriKey=(RSAPrivateKey)keyPair.getPrivate(); byte[]pubModBytes=pubKey.getModulus().toByteArray(); byte[]pubPubExpBytes=pubKey.getPublicExponent().toByteArray(); byte[]priModBytes=priKey.getModulus().toByteArray(); byte[]priPriExpBytes=priKey.getPrivateExponent().toByteArray(); RSAPublicKeyrecoveryPubKey=RSAUtil.generateRSAPublicKey(pubModBytes,pubPubExpBytes); RSAPrivateKeyrecoveryPriKey=RSAUtil.generateRSAPrivateKey(priModBytes,priPriExpBytes); byte[]raw=RSAUtil.encrypt(priKey,orgData); file=newFile("encrypt_result.dat"); OutputStreamout=newFileOutputStream(file); out.write(raw); out.close(); byte[]data=RSAUtil.decrypt(recoveryPubKey,raw); file=newFile("decrypt_result.html"); out=newFileOutputStream(file); out.write(data); out.flush(); out.close(); } } 加密可以用公钥,解密用私钥;或者加密用私钥。通常非对称加密是非常消耗资源的,因此可以对大数据用对称加密如:des(具体代码可以看我以前发的贴子),而对其对称密钥进行非对称加密,这样既保证了数据的安全,还能保证效率。