當前位置:首頁 » 操作系統 » c3des源碼

c3des源碼

發布時間: 2023-07-15 23:04:07

⑴ 求C++高手幫我編寫一個能運行的3DES加解密演算法源程序,謝謝!

#if !defined(_CRYPT3DES_H)
#define _CRYPT3DES_H
#if !defined(ED_FLAG)
#define ED_FLAG
#define encrypt 0
#define decrypt 1
#endif
#ifndef _WINDOWS_
#include "windows.h"
#endif
//////////////////////////////////////////////////////////////////////////
/*
unsigned char key[8] = {"doks"};
unsigned char buff[8] = {"abcdef"};
C3DES des;
des.DoDES3(0,buff,key);
des.DoDES3(1,buff,key);
*/
/* 3DES Class. */
class C3DES
{
public:
BOOL DoDES3(int nWay,unsigned char* pSrc,int nSrcSize,unsigned char* pDes,unsigned char pKey[8]);
private:
BOOL DoDES3(
unsigned char EDFlag, //EDFlag是加\脫密標志,0表示加密,1表示脫密
unsigned char databuf[8], //DataBuf將被處理的明文或密文的緩沖區,並兼作輸出緩沖區
unsigned char keybuf[8] //8byte的密鑰緩沖區
);
inline void pro_key(void);
代碼太長http://www.360doc.com/content/14/0502/18/17111906_374002596.shtml

⑵ 有關於DES演算法的C語言源代碼嘛急需,能直接運行的

//////////////////////////////////////////////////////////////////////////
/*
Provided by 王俊川, Northeastern University (www.neu.e.cn)
Email: [email protected]
This proct is free for use.
*/
//////////////////////////////////////////////////////////////////////////

#include "memory.h"
enum {ENCRYPT,DECRYPT};

//////////////////////////////////////////////////////////////////////////

// initial permutation IP
const static char IP_Table[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
};
// final permutation IP^-1
const static char IPR_Table[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
};
// expansion operation matrix
static const char E_Table[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
};
// 32-bit permutation function P used on the output of the S-boxes
const static char P_Table[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
};
// permuted choice table (key)
const static char PC1_Table[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
};
// permuted choice key (table)
const static char PC2_Table[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
};
// number left rotations of pc1
const static char LOOP_Table[16] = {
1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1
};
// The (in)famous S-boxes
const static char S_Box[8][4][16] = {
// S1
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,
// S2
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,
// S3
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,
// S4
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,
// S5
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,
// S6
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,
// S7
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,
// S8
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
};

//////////////////////////////////////////////////////////////////////////

typedef bool (*PSubKey)[16][48];

//////////////////////////////////////////////////////////////////////////

static void DES(char Out[8], char In[8], const PSubKey pSubKey, bool Type);//標准DES加/解密
static void SetKey(const char* Key, int len);// 設置密鑰
static void SetSubKey(PSubKey pSubKey, const char Key[8]);// 設置子密鑰
static void F_func(bool In[32], const bool Ki[48]);// f 函數
static void S_func(bool Out[32], const bool In[48]);// S 盒代替
static void Transform(bool *Out, bool *In, const char *Table, int len);// 變換
static void Xor(bool *InA, const bool *InB, int len);// 異或
static void RotateL(bool *In, int len, int loop);// 循環左移
static void ByteToBit(bool *Out, const char *In, int bits);// 位元組組轉換成位組
static void BitToByte(char *Out, const bool *In, int bits);// 位組轉換成位元組組

//////////////////////////////////////////////////////////////////////////

static bool SubKey[2][16][48];// 16圈子密鑰
static bool Is3DES;// 3次DES標志
static char Tmp[256], deskey[16];

//////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
// Code starts from Line 130
//////////////////////////////////////////////////////////////////////////
bool Des_Go(char *Out, char *In, long datalen, const char *Key, int keylen, bool Type)
{
if( !( Out && In && Key && (datalen=(datalen+7)&0xfffffff8) ) )
return false;
SetKey(Key, keylen);
if( !Is3DES ) { // 1次DES
for(long i=0,j=datalen>>3; i<j; ++i,Out+=8,In+=8)
DES(Out, In, &SubKey[0], Type);
} else{ // 3次DES 加密:加(key0)-解(key1)-加(key0) 解密::解(key0)-加(key1)-解(key0)
for(long i=0,j=datalen>>3; i<j; ++i,Out+=8,In+=8) {
DES(Out, In, &SubKey[0], Type);
DES(Out, Out, &SubKey[1], !Type);
DES(Out, Out, &SubKey[0], Type);
}
}
return true;
}
void SetKey(const char* Key, int len)
{
memset(deskey, 0, 16);
memcpy(deskey, Key, len>16?16:len);
SetSubKey(&SubKey[0], &deskey[0]);
Is3DES = len>8 ? (SetSubKey(&SubKey[1], &deskey[8]), true) : false;
}
void DES(char Out[8], char In[8], const PSubKey pSubKey, bool Type)
{
static bool M[64], tmp[32], *Li=&M[0], *Ri=&M[32];
ByteToBit(M, In, 64);
Transform(M, M, IP_Table, 64);
if( Type == ENCRYPT ){
for(int i=0; i<16; ++i) {
memcpy(tmp, Ri, 32);
F_func(Ri, (*pSubKey)[i]);
Xor(Ri, Li, 32);
memcpy(Li, tmp, 32);
}
}else{
for(int i=15; i>=0; --i) {
memcpy(tmp, Li, 32);
F_func(Li, (*pSubKey)[i]);
Xor(Li, Ri, 32);
memcpy(Ri, tmp, 32);
}
}
Transform(M, M, IPR_Table, 64);
BitToByte(Out, M, 64);
}
void SetSubKey(PSubKey pSubKey, const char Key[8])
{
static bool K[64], *KL=&K[0], *KR=&K[28];
ByteToBit(K, Key, 64);
Transform(K, K, PC1_Table, 56);
for(int i=0; i<16; ++i) {
RotateL(KL, 28, LOOP_Table[i]);
RotateL(KR, 28, LOOP_Table[i]);
Transform((*pSubKey)[i], K, PC2_Table, 48);
}
}
void F_func(bool In[32], const bool Ki[48])
{
static bool MR[48];
Transform(MR, In, E_Table, 48);
Xor(MR, Ki, 48);
S_func(In, MR);
Transform(In, In, P_Table, 32);
}
void S_func(bool Out[32], const bool In[48])
{
for(char i=0,j,k; i<8; ++i,In+=6,Out+=4) {
j = (In[0]<<1) + In[5];
k = (In[1]<<3) + (In[2]<<2) + (In[3]<<1) + In[4];
ByteToBit(Out, &S_Box[i][j][k], 4);
}
}
void Transform(bool *Out, bool *In, const char *Table, int len)
{
for(int i=0; i<len; ++i)
Tmp[i] = In[ Table[i]-1 ];
memcpy(Out, Tmp, len);
}
void Xor(bool *InA, const bool *InB, int len)
{
for(int i=0; i<len; ++i)
InA[i] ^= InB[i];
}
void RotateL(bool *In, int len, int loop)
{
memcpy(Tmp, In, loop);
memcpy(In, In+loop, len-loop);
memcpy(In+len-loop, Tmp, loop);
}
void ByteToBit(bool *Out, const char *In, int bits)
{
for(int i=0; i<bits; ++i)
Out[i] = (In[i>>3]>>(i&7)) & 1;
}
void BitToByte(char *Out, const bool *In, int bits)
{
memset(Out, 0, bits>>3);
for(int i=0; i<bits; ++i)
Out[i>>3] |= In[i]<<(i&7);
}
//////////////////////////////////////////////////////////////////////////
// Code ends at Line 231
//////////////////////////////////////////////////////////////////////////

⑶ IDEA加密演算法的C語言實現

1、數據加密的基本過程就是對原來為明文的文件或數據按某種演算法進行處理,使其成為不可讀的一段代碼,通常稱為「密文」,使其只能在輸入相應的密鑰之後才能顯示出本來內容,通過這樣的途徑來達到保護數據不被非法人竊取、閱讀的目的。

2、常見加密演算法
DES(Data Encryption Standard):數據加密標准,速度較快,適用於加密大量數據的場合;
3DES(Triple DES):是基於DES,對一塊數據用三個不同的密鑰進行三次加密,強度更高;
RC2和 RC4:用變長密鑰對大量數據進行加密,比 DES 快;
IDEA(International Data Encryption Algorithm)國際數據加密演算法:使用 128 位密鑰提供非常強的安全性;
RSA:由 RSA 公司發明,是一個支持變長密鑰的公共密鑰演算法,需要加密的文件塊的長度也是可變的;
DSA(Digital Signature Algorithm):數字簽名演算法,是一種標準的 DSS(數字簽名標准);
AES(Advanced Encryption Standard):高級加密標准,是下一代的加密演算法標准,速度快,安全級別高,目前 AES 標準的一個實現是 Rijndael 演算法;
BLOWFISH,它使用變長的密鑰,長度可達448位,運行速度很快;
其它演算法,如ElGamal、Deffie-Hellman、新型橢圓曲線演算法ECC等。
比如說,MD5,你在一些比較正式而嚴格的網站下的東西一般都會有MD5值給出,如安全焦點的軟體工具,每個都有MD5。

3、常式:

#include<stdio.h>
#include<process.h>
#include<conio.h>
#include<stdlib.h>
#definemaxim65537
#definefuyi65536
#defineone65536
#defineround8
unsignedintinv(unsignedintxin);
unsignedintmul(unsignedinta,unsignedintb);
voidcip(unsignedintIN[4],unsignedintOUT[4],unsignedintZ[7][10]);
voidkey(unsignedintuskey[9],unsignedintZ[7][10]);
voidde_key(unsignedintZ[7][10],unsignedintDK[7][10]);
voidmain()
{
inti,j,k,x;
unsignedintZ[7][10],DK[7][10],XX[5],TT[5],YY[5];
unsignedintuskey[9];
FILE*fpout,*fpin;
printf(" InputKey");
for(i=1;i<=8;i++)
scanf("%6u",&uskey[i]);
for(i=0;i<9;i++)
uskey[i]=100+i*3;
key(uskey,Z);/*產生加密子密鑰*/
de_key(Z,DK);/*計算解密子密鑰*/
if((fpin=fopen("ekey.txt","w"))==NULL)
{
printf("cannotopenfile!");
exit(EXIT_FAILURE);
}
for(i=0;i<7;i++)
{
for(j=0;j<10;j++)
fprintf(fpin,"%6u",Z[i][j]);
fprintf(fpin," ");
}
fclose(fpin);

/*XX[1..5]中為明文*/
for(i=0;i<4;i++)XX[i]=2*i+101;
clrscr();
printf("Mingwen%6u%6u%6u%6u ",XX[0],XX[1],XX[2],XX[3]);
if((fpin=(fopen("ideaming.txt","w")))==NULL)
{printf("cannotopenfile!");
exit(EXIT_FAILURE);
}
fprintf(fpin,"%6u,%6u,%6u,%6u ",XX[0],XX[1],XX[2],XX[3]);
fclose(fpin);
for(i=1;i<=30000;i++)
cip(XX,YY,Z);/*用密鑰Z加密XX中的明文並存在YY中*/
printf(" Mingwen%6u%6u%6u%6u ",YY[0],YY[1],YY[2],YY[3]);
if((fpin=fopen("ideamiwn.txt","w"))==NULL)
{
printf("cannotopenfile!");
exit(EXIT_FAILURE);
}
fprintf(fpout,"%6u%6u%6u%6u ",YY[0],YY[1],YY[2],YY[3]);
{
printf("cannotopenfile!");
exit(EXIT_FAILURE);
}
fprintf(fpout,"%6u%6u%6u%6u ",YY[0],YY[1],YY[2],YY[3]);
fclose(fpout);
for(i=1;i<=30000;i++)
cip(YY,TT,DK);/*encipherYYtoTTwithKeyDK*/
printf(" JieMi%6u%6u%6u%6u ",TT[0],TT[1],TT[2],TT[3]);
if((fpout=fopen("dideaout.txt","w"))==NULL)
{
printf("cannotopenfile!");
exit(EXIT_FAILURE);
}
fprintf(fpout,"%6u%6u%6u%6u ",TT[0],TT[1],TT[2],TT[3]);
fclose(fpout);
}
/*此函數執行IDEA演算法中的加密過程*/

voidcip(unsignedintIN[4],unsignedintOUT[4],unsignedintZ[7][10])
{
unsignedintr,x1,x2,x3,x4,kk,t1,t2,a;
x1=IN[0];x2=IN[1];x3=IN[2];x4=IN[3];
for(r=1;r<=8;r++)
{
/*對64位的塊進行分組運算*/
x1=mul(x1,Z[1][r]);x4=mul(x4,Z[4][r]);
x2=x2+Z[2][r]&one;x3=(x3+Z[3][r])&one;
/*MA結構的函數*/
kk=mul(Z[5][r],(x1^x3));
t1=mul(Z[6][r],(kk+(x2^x4))&one;
/*隨機變換PI*/
x1=x1^t1;x4=x4^t2;a=x2^t2;x2=x3^t1;x3=a;
}
/*輸出轉換*/
OUT[0]=mul(x1,Z[1][round+1]);
OUT[3]=mul(x4,Z[1][round+1]);
OUT[1]=(x3+Z[2][round+1])&one;
OUT[2]=(x2+Z[3][round+1])&one;
}

/*用高低演算法上實現乘法運算*/
unsignedintmul(unsignedinta,unsignedintb)
{
longintp;
longunsignedq;
if(a==0)p=maxim-b;
elseif(b==0)p=maxim-a;
else
{
q=(unsignedlong)a*(unsignedlong)b;
p=(q&one)-(q>>16);
if(p<=0)p=p+maxim;
{
return(unsigned)(p&one);
}

/*通過Euclideangcd演算法計算xin的倒數*/
unsignedintinv(unsignedintxin)
{
longn1,n2,q,r,b1,b2,t;
if(xin==0)
b2=0;
else
{n1=maxim;n2=xin;b2=1;b1=0;
do{
r=(n1%n2);q=(n1-r)/n2;
if(r==0)
if(b2<0)b2=maxim+b2;
else
{n1=n2;n2=r;
t=b2;
b2=b1-q*b2;b1=t;
}
}while(r!=0);
}
return(unsignedlongint)b2;
}
/*產生加密子密鑰Z*/
voidkey(unsignedintuskey[9],unsignedintZ[7][10])
{
unsignedintS[54];
inti,j,r;
for(i=1;i<9;i++)
S[i-1]=uskey[i];
/*shifts*/
for(i=8;i<54;i++)
{
if(i+2)%8==0)/*對於S[14],S[22],...進行計算*/
S[i]=((S[i-7]<<0)^(S[i-14]>>7)&one;
elseif((i+1)%8==0)/*對於S[15],S[23],...進行計算*/
S[i]=((S[i-15]<<9)^(S[i-14]>>7)&one;
else
S[i]=((S[i-7]<<9)^(S[i-6]>>7)&one;
}
/*取得子密鑰*/
for(r=1;r<=round+1;r++)
for(j=1;j<7;j++)
Z[j][r]=S[6*(r-1)+j-1];
}

/*計算解子密鑰DK*/
voidde_key(unsignedintZ[7][10],unsignedintDK[7][10])
{
intj;
for(j=1;j<=round+1;j++)
{DK[1][round-j+2]=inv(Z[1][j]);
DK[4][round-j+2]=inv(Z[4][j]);
if(i==1|j==round+1)
{
DK[2][round-j+2]=(fuyi-Z[2][j])&one;
DK[3][round-j+2]=(fuyi-Z[3][j])&one;
}
else
{
DK[2][round-j+2]=inv(Z[3][j]);
DK[3][round-j+2]=inv(Z[2][j]);
}
}
for(j=1;j<=round+1;j++)
{
DK[5][round-j+2]=inv(Z[5][j]);
DK[6][round-j+2]=inv(Z[6][j]);
}

}

⑷ [高分]求關於java的3des加密的bug解決辦法,要求能用16位key並且不讓加密後長度多8個位元組;

在java中調用sun公司提供的3DES加密解密演算法時,需要使用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
jce.jar
security/US_export_policy.jar
security/local_policy.jar
ext/sunjce_provider.jar
Java運行時會自動載入這些包,因此對於帶main函數的應用程序不需要設置到CLASSPATH環境變數中。對於WEB應用,不需要把這些包加到WEB-INF/lib目錄下。
以下是java中調用sun公司提供的3DES加密解密演算法的樣本代碼:
加密解密代碼
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/*字元串 DESede(3DES) 加密*/
public class ThreeDes {
/**
* @param args在java中調用sun公司提供的3DES加密解密演算法時,需要使
* 用到$JAVA_HOME/jre/lib/目錄下如下的4個jar包:
*jce.jar
*security/US_export_policy.jar
*security/local_policy.jar
*ext/sunjce_provider.jar
*/
private static final String Algorithm ="DESede"; //定義加密演算法,可用 DES,DESede,Blowfish
//keybyte為加密密鑰,長度為24位元組
//src為被加密的數據緩沖區(源)
public static byte[] encryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(src);//在單一方面的加密或解密
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//keybyte為加密密鑰,長度為24位元組
//src為加密後的緩沖區
public static byte[] decryptMode(byte[] keybyte,byte[] src){
try {
//生成密鑰
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
//解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
// TODO: handle exception
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingException e2){
e2.printStackTrace();
}catch(java.lang.Exception e3){
e3.printStackTrace();
}
return null;
}
//轉換成十六進制字元串
public static String byte2Hex(byte[] b){
String hs="";
String stmp="";
for(int n=0; n<b.length; n++){
stmp = (java.lang.Integer.toHexString(b[n]& 0XFF));
if(stmp.length()==1){
hs = hs + "0" + stmp;
}else{
hs = hs + stmp;
}
if(n<b.length-1)hs=hs+":";
}
return hs.toUpperCase();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加新安全演算法,如果用JCE就要把它添加進去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58,
(byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79,0x51,
(byte)0xCB,
(byte)0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
(byte)0x98, 0x30, 0x40, 0x36,
(byte)0xE2
}; //24位元組的密鑰
String szSrc = "This is a 3DES test. 測試";
System.out.println("加密前的字元串:" + szSrc);
byte[] encoded = encryptMode(keyBytes,szSrc.getBytes());
System.out.println("加密後的字元串:" + new String(encoded));
byte[] srcBytes = decryptMode(keyBytes,encoded);
System.out.println("解密後的字元串:" + (new String(srcBytes)));
}
}

⑸ 什麼是3DES對稱加密演算法

DES加密經過下面的步驟
1、提供明文和密鑰,將明文按照64bit分塊(對應8個位元組),不足8個位元組的可以進行填充(填充方式多種),密鑰必須為8個位元組共64bit
填充方式:

當明文長度不為分組長度的整數倍時,需要在最後一個分組中填充一些數據使其湊滿一個分組長度。
* NoPadding
API或演算法本身不對數據進行處理,加密數據由加密雙方約定填補演算法。例如若對字元串數據進行加解密,可以補充\0或者空格,然後trim

* PKCS5Padding
加密前:數據位元組長度對8取余,余數為m,若m>0,則補足8-m個位元組,位元組數值為8-m,即差幾個位元組就補幾個位元組,位元組數值即為補充的位元組數,若為0則補充8個位元組的8
解密後:取最後一個位元組,值為m,則從數據尾部刪除m個位元組,剩餘數據即為加密前的原文。
例如:加密字元串為為AAA,則補位為AAA55555;加密字元串為BBBBBB,則補位為BBBBBB22;加密字元串為CCCCCCCC,則補位為CCCCCCCC88888888。

* PKCS7Padding
PKCS7Padding 的填充方式和PKCS5Padding 填充方式一樣。只是加密塊的位元組數不同。PKCS5Padding明確定義了加密塊是8位元組,PKCS7Padding加密快可以是1-255之間。
2、選擇加密模式

**ECB模式** 全稱Electronic Codebook模式,譯為電子密碼本模式
**CBC模式** 全稱Cipher Block Chaining模式,譯為密文分組鏈接模式
**CFB模式** 全稱Cipher FeedBack模式,譯為密文反饋模式
**OFB模式** 全稱Output Feedback模式,譯為輸出反饋模式。
**CTR模式** 全稱Counter模式,譯為計數器模式。
3、開始加密明文(內部原理--加密步驟,加密演算法實現不做講解)

image
1、將分塊的64bit一組組加密,示列其中一組:將此組進行初始置換(IP置換),目的是將輸入的64位數據塊按位重新組合,並把輸出分為L0、R0兩部分,每部分各長32位。
2、開始Feistel結構的16次轉換,第一次轉換為:右側數據R0和子密鑰經過輪函數f生成用於加密左側數據的比特序列,與左側數據L0異或運算,
運算結果輸出為加密後的左側L0,右側數據則直接輸出為右側R0。由於一次Feistel輪並不會加密右側,因此需要將上一輪輸出後的左右兩側對調後才正式完成一次Feistel加密,
3、DES演算法共計進行16次Feistel輪,最後一輪輸出後左右兩側無需對調,每次加密的子密鑰不相同,子密鑰是通過秘鑰計算得到的。
4、末置換是初始置換的逆過程,DES最後一輪後,左、右兩半部分並未進行交換,而是兩部分合並形成一個分組做為末置換的輸入
DES解密經過下面的步驟
1、拿到密文和加密的密鑰
2、解密:DES加密和解密的過程一致,均使用Feistel網路實現,區別僅在於解密時,密文作為輸入,並逆序使用子密鑰。
3、講解密後的明文去填充 (padding)得到的即為明文
Golang實現DES加密解密
package main

import (
"fmt"
"crypto/des"
"bytes"
"crypto/cipher"
)

func main() {
var miwen,_= DESEncode([]byte("hello world"),[]byte("12345678"))
fmt.Println(miwen) // [11 42 146 232 31 180 156 225 164 50 102 170 202 234 123 129],密文:最後5位是補碼
var txt,_ = DESDecode(miwen,[]byte("12345678"))
fmt.Println(txt) // [104 101 108 108 111 32 119 111 114 108 100]明碼
fmt.Printf("%s",txt) // hello world
}
// 加密函數
func DESEncode(orignData, key []byte)([]byte,error){

// 建立密碼塊
block ,err:=des.NewCipher(key)
if err!=nil{ return nil,err}

// 明文分組,不足的部分加padding
txt := PKCS5Padding(orignData,block.BlockSize())

// 設定加密模式,為了方便,初始向量直接使用key充當了(實際項目中,最好別這么做)
blockMode := cipher.NewCBCEncrypter(block,key)

// 創建密文長度的切片,用來存放密文位元組
crypted :=make([]byte,len(txt))

// 開始加密,將txt作為源,crypted作為目的切片輸入
blockMode.CryptBlocks(crypted,txt)

// 將加密後的切片返回
return crypted,nil
}
// 加密所需padding
func PKCS5Padding(ciphertext []byte,size int)[]byte{
padding := size - len(ciphertext)%size
padTex := bytes.Repeat([]byte{byte(padding)},padding)
return append(ciphertext,padTex...)
}
// 解密函數
func DESDecode(cripter, key []byte) ([]byte,error) {
// 建立密碼塊
block ,err:=des.NewCipher(key)
if err!=nil{ return nil,err}

// 設置解密模式,加密模式和解密模式要一樣
blockMode := cipher.NewCBCDecrypter(block,key)

// 設置切片長度,用來存放明文位元組
originData := make([]byte,len(cripter))

// 使用解密模式解密,將解密後的明文位元組放入originData 切片中
blockMode.CryptBlocks(originData,cripter)

// 去除加密的padding部分
strByt := UnPKCS5Padding(origenData)

return strByt,nil
}
// 解密所需要的Unpadding
func UnPKCS5Padding(origin []byte) []byte{
// 獲取最後一位轉為整型,然後根據這個整型截取掉整型數量的長度
// 若此數為5,則減掉轉換明文後的最後5位,即為我們輸入的明文
var last = int(origin[len(origin)-1])
return origin[:len(origin)-last]
}
注意:在設置加密模式為CBC的時候,我們需要設置一個初始化向量,這個量的意思 在對稱加密演算法中,如果只有一個密鑰來加密數據的話,明文中的相同文字就會也會被加密成相同的密文,這樣密文和明文就有完全相同的結構,容易破解,如果給一個初始化向量,第一個明文使用初始化向量混合並加密,第二個明文用第一個明文的加密後的密文與第二個明文混合加密,這樣加密出來的密文的結構則完全與明文不同,更加安全可靠。CBC模式圖如下

CBC
3DES
DES 的常見變體是三重 DES,使用 168 位的密鑰對資料進行三次加密的一種機制;它通常(但非始終)提供極其強大的安全性。如果三個 56 位的子元素都相同,則三重 DES 向後兼容 DES。
對比DES,發現只是換了NewTripleDESCipher。不過,需要注意的是,密鑰長度必須24byte,否則直接返回錯誤。關於這一點,PHP中卻不是這樣的,只要是8byte以上就行;而Java中,要求必須是24byte以上,內部會取前24byte(相當於就是24byte)。另外,初始化向量長度是8byte(目前各個語言都是如此,不是8byte會有問題)

⑹ 3DES的演算法介紹

3DES又稱Triple DES,是DES加密演算法的一種模式,它使用3條56位的密鑰對數據進行三次加密。數據加密標准(DES)是美國的一種由來已久的加密標准,它使用對稱密鑰加密法,並於1981年被ANSI組織規范為ANSI X.3.92。DES使用56位密鑰和密碼塊的方法,而在密碼塊的方法中,文本被分成64位大小的文本塊然後再進行加密。比起最初的DES,3DES更為安全。
3DES(即Triple DES)是DES向AES過渡的加密演算法(1999年,NIST將3-DES指定為過渡的加密標准),加密演算法,其具體實現如下:設Ek()和Dk()代表DES演算法的加密和解密過程,K代表DES演算法使用的密鑰,P代表明文,C代表密文,這樣:
3DES加密過程為:C=Ek3(Dk2(Ek1(P)))
3DES解密過程為:P=Dk1(EK2(Dk3(C)))

⑺ VS中用C#編寫一個DES(或3DES)加解密的Windows應用程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ZU14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

//ZU14.DES des = new ZU14.DES();
ZU14.DES des = null;

private void btn_jiami_Click(object sender, EventArgs e)
{
textBox2.Text = des.Encrypt(textBox1.Text);
// MessageBox.Show("加密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

private void btn_jiemi_Click(object sender, EventArgs e)
{
textBox3.Text = des.Decrypt(textBox2.Text);
//MessageBox.Show("解密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

private void btn_wjjiami_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = @"d:\";
open.Filter = "文本文件(*.txt,*.doc,*.xls)|*.txt;*.doc;*.xls";
if (open.ShowDialog()== DialogResult.OK)
{
des.EncryptFile(open.FileName, open.FileName);
MessageBox.Show("加密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

}

private void btn_wjjiemi_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = @"d:\";
open.Filter = "文本文件(*.txt,*.doc,*.xls)|*.txt;*.doc;*.xls";
if (open.ShowDialog() == DialogResult.OK)
{
des.DecryptFile(open.FileName);
MessageBox.Show("解密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

}

private void button1_Click(object sender, EventArgs e)
{
zifu.setmisi1 = textBox4.Text.Trim();
zifu.setmisi2 = textBox5.Text.Trim();
des = new ZU14.DES();
}
}
}
上面的代碼是窗體的
下面是調用的兩個類的
using System;
using System.Collections.Generic;
using System.Text;

namespace ZU14
{
class zifu
{
private static string misi1;
private static string misi2;
public static string getmisi1
{
get
{
return misi1;
}
}
public static string setmisi1
{
set
{
misi1 = value;
}
}
public static string getmisi2
{
get
{
return misi2;
}
}
public static string setmisi2
{
set
{
misi2 = value;
}
}
}
}

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Collections;
using System.Data;
using System.Windows.Forms;

namespace ZU14
{
class DES
{

string iv =zifu.getmisi1; //"1234的yza";
string key = zifu.getmisi2;//"123在yzb";

/// <summary>
/// DES加密偏移量,必須是>=8位長的字元串
/// </summary>
public string IV
{
get { return iv; }
set { iv = value; }
}

/// <summary>
/// DES加密的私鑰,必須是8位長的字元串
/// </summary>
public string Key
{
get { return key; }
set { key = value; }
}

/// <summary>
/// 對字元串進行DES加密
/// </summary>
/// <param name="sourceString">待加密的字元串</param>
/// <returns>加密後的BASE64編碼的字元串</returns>
public string Encrypt(string sourceString)
{
byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Encoding.Default.GetBytes(sourceString);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}

return Convert.ToBase64String(ms.ToArray());
}
catch
{
throw;
}
}
}

/// <summary>
/// 對DES加密後的字元串進行解密
/// </summary>
/// <param name="encryptedString">待解密的字元串</param>
/// <returns>解密後的字元串</returns>
public string Decrypt(string encryptedString)
{
byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Convert.FromBase64String(encryptedString);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}

return Encoding.Default.GetString(ms.ToArray());
}
catch
{
throw;
}
}
}

/// <summary>
/// 對文件內容進行DES加密
/// </summary>
/// <param name="sourceFile">待加密的文件絕對路徑</param>
/// <param name="destFile">加密後的文件保存的絕對路徑</param>
public void EncryptFile(string sourceFile, string destFile)
{
if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路徑不存在!", sourceFile);

byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] btFile = File.ReadAllBytes(sourceFile);

using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
{
try
{
using (CryptoStream cs = new CryptoStream(fs, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(btFile, 0, btFile.Length);
cs.FlushFinalBlock();
}
}
catch
{
// throw;
}
finally
{
fs.Close();
}
}
}

/// <summary>
/// 對文件內容進行DES加密,加密後覆蓋掉原來的文件
/// </summary>
/// <param name="sourceFile">待加密的文件的絕對路徑</param>
public void EncryptFile(string sourceFile)
{
EncryptFile(sourceFile, sourceFile);
}

/// <summary>
/// 對文件內容進行DES解密
/// </summary>
/// <param name="sourceFile">待解密的文件絕對路徑</param>
/// <param name="destFile">解密後的文件保存的絕對路徑</param>
public void DecryptFile(string sourceFile, string destFile)
{
if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路徑不存在!", sourceFile);

byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] btFile = File.ReadAllBytes(sourceFile);

using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
{
try
{
using (CryptoStream cs = new CryptoStream(fs, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(btFile, 0, btFile.Length);
cs.FlushFinalBlock();
}
}
catch
{
// MessageBox.Show(ex.Message);
//throw;
}
finally
{
fs.Close();
}
}
}

/// <summary>
/// 對文件內容進行DES解密,加密後覆蓋掉原來的文件
/// </summary>
/// <param name="sourceFile">待解密的文件的絕對路徑</param>
public void DecryptFile(string sourceFile)
{
DecryptFile(sourceFile, sourceFile);
}

}
}
有什麼看不明白的,再聯系我,我的賬號就是我的QQ

⑻ 如何用C實現3DES演算法..

3DES演算法C語言實現,有注釋! http://tech.cuit.e.cn/forum/thread-2448-1-1.html

熱點內容
網站搭建伺服器搭建 發布:2025-03-16 10:33:27 瀏覽:795
游戲目錄在哪裡安卓 發布:2025-03-16 10:33:19 瀏覽:467
婉兒腳本 發布:2025-03-16 10:19:33 瀏覽:580
c語言ftp下載文件 發布:2025-03-16 10:05:02 瀏覽:307
手機帳戶密碼怎麼找回密碼 發布:2025-03-16 10:02:10 瀏覽:706
c語言位段的使用 發布:2025-03-16 10:00:38 瀏覽:572
象山編程 發布:2025-03-16 09:38:41 瀏覽:927
綠點掌知識薪資密碼是多少 發布:2025-03-16 09:37:05 瀏覽:597
osu安卓版怎麼 發布:2025-03-16 09:37:05 瀏覽:153
python編程編程第三版 發布:2025-03-16 09:29:56 瀏覽:968