当前位置:首页 » 操作系统 » 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

热点内容
sqlserver2016r 发布:2025-03-16 11:15:58 浏览:24
网页登录找不到该服务器什么意思 发布:2025-03-16 11:14:19 浏览:831
网站搭建服务器搭建 发布: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