des3在線加密解密
1. 【急】【求助】.des加密文件怎樣打開
想實現用方法1加密文件 後再方法2 解密文件 可成功正常運行"C:/j2sdk1.4.2_08/bin/aa.class"文件
//方法1 這是加密文件, 把"C:/aa.class" 加密為 "C:/j2sdk1.4.2_08/bin/aaEncode.class"
//方法2 這是解密文件,把"C:/j2sdk1.4.2_08/bin/aaEncode.class" 解密為 "C:/j2sdk1.4.2_08/bin/aa.class"
//方法3 這是先加密再解密的代碼,這是加密文件, 把"C:/aa.class" 加密到一個內存後把這內存解密到 "C:/j2sdk1.4.2_08/bin/aa.class"
其中直接運行方法3 可正常運行"C:/j2sdk1.4.2_08/bin/aa.class"文件,成功!
如果先運行 方法1 再運行方法2 不可正常運行"C:/j2sdk1.4.2_08/bin/aa.class"文件,失敗!
請高手解決一下。
//方法1 這是加密文件, 把"C:/aa.class" 加密為 "C:/j2sdk1.4.2_08/bin/aaEncode.class"
void CTestDllDlg::OnBnClickedjiami()
{
CString spath ;
int ilen = 800;
char *pBufferRead = new char[ilen];
ZeroMemory(pBufferRead,ilen);
spath ="C:/aa.class";
CFile fFileRead(spath,CFile::modeReadWrite | CFile::modeNoTruncate );
ilen = fFileRead.GetLength();
fFileRead.Read(pBufferRead,fFileRead.GetLength());
fFileRead.Close();
char *key =new char[10];
strcpy(key,"1234567");
char *bufferEncode =new char[ilen];
Des_EncodeFile( bufferEncode, pBufferRead, key,ilen);
spath ="C:/j2sdk1.4.2_08/bin/aaEncode.class";
CFile fFileWrite(spath,CFile::modeReadWrite | CFile::modeNoTruncate | CFile::modeCreate);
fFileWrite.SeekToBegin();
fFileWrite.Write(bufferEncode,ilen);
fFileWrite.Close();
CString ss;
//ss.Format("新文件大小原 %s 新%s",bufferEncode,pBufferRead);
// AfxMessageBox(ss);
delete [] pBufferRead ;
delete [] key ;
delete [] bufferEncode ;
}
//方法2 這是解密文件,把"C:/j2sdk1.4.2_08/bin/aaEncode.class" 解密為 "C:/j2sdk1.4.2_08/bin/aa.class"
void CTestDllDlg::OnBnClickedjiemi()
{
CString spath ;
int ilen = 800;
char *pBufferRead = new char[ilen];
ZeroMemory(pBufferRead,ilen);
spath ="C:/j2sdk1.4.2_08/bin/aaEncode.class";
CFile fFileRead(spath,CFile::modeReadWrite | CFile::modeNoTruncate );
ilen = fFileRead.GetLength();
fFileRead.Read(pBufferRead,fFileRead.GetLength());
fFileRead.Close();
char *key =new char[10];
strcpy(key,"1234567");
char *bufferDecode =new char[ilen ];
Des_DecodeFile( bufferDecode, pBufferRead, key,ilen);
spath ="C:/j2sdk1.4.2_08/bin/aa.class";
CFile fFileWrite(spath,CFile::modeReadWrite | CFile::modeNoTruncate | CFile::modeCreate);
fFileWrite.SeekToBegin();
fFileWrite.Write(bufferDecode,ilen);
fFileWrite.Close();
CString ss;
//ss.Format("新文件大小原 %s 新%s",bufferDecode,pBufferRead);
// AfxMessageBox(ss);
delete [] pBufferRead ;
delete [] key ;
delete [] bufferDecode ;
}
//方法3 這是先加密再解密的代碼,這是加密文件, 把"C:/aa.class" 加密到一個內存後把這內存解密到 "C:/j2sdk1.4.2_08/bin/aa.class"
void CTestDllDlg::OnBnClickedjiajiemi()
{
CString spath ;
int ilen = 800;
char *pBufferRead = new char[ilen];
ZeroMemory(pBufferRead,ilen);
spath ="C:/aa.class";
CFile fFileRead(spath,CFile::modeReadWrite | CFile::modeNoTruncate );
ilen = fFileRead.GetLength();
fFileRead.Read(pBufferRead,fFileRead.GetLength());
fFileRead.Close();
char *key =new char[10];
strcpy(key,"1234567");
char *bufferEncode =new char[ilen];
Des_EncodeFile( bufferEncode, pBufferRead, key,ilen);
char *bufferDecode =new char[ilen ];
Des_DecodeFile( bufferDecode, bufferEncode, key,ilen);
spath ="C:/j2sdk1.4.2_08/bin/aa.class";
CFile fFileWrite(spath,CFile::modeReadWrite | CFile::modeNoTruncate | CFile::modeCreate);
fFileWrite.SeekToBegin();
fFileWrite.Write(bufferDecode,ilen);
fFileWrite.Close();
CString ss;
//ss.Format("新文件大小原 %s 新%s",bufferEncode,pBufferRead);
// AfxMessageBox(ss);
delete [] pBufferRead ;
delete [] key ;
delete [] bufferEncode ;
delete [] bufferDecode ;
}
//
int CTestDllDlg::Des_EncodeFile( char *buf, char *input, char *key,int lenp)
{
Des_Go(buf, input, lenp, key, sizeof(key), ENCRYPT);
return 0;
}
//
int CTestDllDlg::Des_DecodeFile(char *output, char *input, char *key,int lenp)
{
Des_Go(output,input, lenp, key, sizeof(key), DECRYPT);
return 0;
}
或是看看下面這個網址
http://hi..com/sammy17084/blog/item/369fa202a6263d054afb5167.html
希望對你有幫助
2. 請教DES演算法的解密
DES演算法處理的數據對象是一組64比特的明文串。設該明文串為m=m1m2…m64 (mi=0或1)。明文串經過64比特的密鑰K來加密,最後生成長度為64比特的密文E。其加密過程圖示如下:
DES演算法加密過程
對DES演算法加密過程圖示的說明如下:待加密的64比特明文串m,經過IP置換後,得到的比特串的下標列表如下:
IP 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
該比特串被分為32位的L0和32位的R0兩部分。R0子密鑰K1(子密鑰的生成將在後面講)經過變換f(R0,K1)(f變換將在下面講)輸出32位的比特串f1,f1與L0做不進位的二進制加法運算。運算規則為:
f1與L0做不進位的二進制加法運算後的結果賦給R1,R0則原封不動的賦給L1。L1與R0又做與以上完全相同的運算,生成L2,R2…… 一共經過16次運算。最後生成R16和L16。其中R16為L15與f(R15,K16)做不進位二進制加法運算的結果,L16是R15的直接賦值。
R16與L16合並成64位的比特串。值得注意的是R16一定要排在L16前面。R16與L16合並後成的比特串,經過置換IP-1後所得比特串的下標列表如下:
IP-1 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
經過置換IP-1後生成的比特串就是密文e.。
下面再講一下變換f(Ri-1,Ki)。
它的功能是將32比特的輸入再轉化為32比特的輸出。其過程如圖所示:
對f變換說明如下:輸入Ri-1(32比特)經過變換E後,膨脹為48比特。膨脹後的比特串的下標列表如下:
E: 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 31
膨脹後的比特串分為8組,每組6比特。各組經過各自的S盒後,又變為4比特(具體過程見後),合並後又成為32比特。該32比特經過P變換後,其下標列表如下:
P: 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
經過P變換後輸出的比特串才是32比特的f (Ri-1,Ki)。
3. 使用des對文件加密後怎麼解密
您好,一般來說在線加密工具都是網頁版的,des加密需要加密前明文和加密密鑰,在網頁的控制項上填寫好對應信息之後,點擊加密按鈕一般就可以看到加密後的加密結果。
4. java的des3解密方法。轉成c#
byte[] iv = utf8.GetBytes("25439768");改成byte[] iv = Convert.FromBase64String("25439768")
5. 使用des對文件加密後怎麼解密
des加密解密都比較復雜
推薦使用加密軟體進行加密解密
文件夾加密超級大師解密也很方便。雙擊加密的數據在彈出的密碼框輸入正確的密碼,點擊【解密】即可
6. DES加密演算法C語言實現
/*********************************************************************/
/*-文件名:des.h */
/*- */
/*-功能: 實現DES加密演算法的加密解密功能 */
/*********************************************************************/
typedef int INT32;
typedef char INT8;
typedef unsigned char ULONG8;
typedef unsigned short ULONG16;
typedef unsigned long ULONG32;
/*如果採用c++編譯器的話採用如下宏定義
#define DllExport extern "C" __declspec(dllexport)
*/
#define DllExport __declspec(dllexport)
/*加密介面函數*/
DllExport INT32 DdesN(ULONG8 *data, ULONG8 **key, ULONG32 n_key,ULONG32 readlen);
DllExport INT32 desN(ULONG8 *data, ULONG8 **key, ULONG32 n_key,ULONG32 readlen);
DllExport INT32 des3(ULONG8 *data, ULONG8 *key,ULONG32 n ,ULONG32 readlen);
DllExport INT32 Ddes3(ULONG8 *data,ULONG8 *key,ULONG32 n ,ULONG32 readlen);
DllExport INT32 des(ULONG8 *data, ULONG8 *key,INT32 readlen);
DllExport INT32 Ddes(ULONG8 *data,ULONG8 *key,INT32 readlen);
*********************************************************************/
/*-文件名:des.c */
/*- */
/*-功能: 實現DES加密演算法的加密解密功能 */
//*********************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>
#include "des.h"
#define SUCCESS 0
#define FAIL -1
#define READFILESIZE 512
#define WZ_COMMEND_NUM 4
#define WZUSEHELPNUM 19
#define DESONE 1
#define DESTHREE 2
#define DESMULTI 3
INT8 *WZ_Commend_Help[] =
{
"基於DES的加密解密工具v1.0 ",/*0*/
"追求卓越,勇於創新 ",
"----著者 : 吳真--- ",
" "
};
INT8 *WZ_USE_HELP[]={
"輸入5+n個參數:",
"\t1.可執行文件名 *.exe",
"\t2.操作類型 1:一層加密;2:一層解密;",
"\t\t13:N層單密鑰加密;23:N層單密鑰解密;",
"\t\t39:N層多密鑰加密;49:N層多密鑰解密",
"\t3.讀出數據的文件名*.txt",
"\t4.寫入數據的文件名*.txt",
"\t5.密鑰(8位元組例如:wuzhen12)",
"\t[6].N層單密鑰的層數或者...二層加密|解密密鑰",
"\t[7].三層加密|解密密鑰",
"\t[8]. ...",
"\t[N].N層加密|解密密鑰",
"\t 例1: des 1 1.txt 2.txt 12345678",
"\t : des 2 2.txt 3.txt 12345678",
"\t 例2: des 13 1.txt 2.txt tiantian 5",
"\t : des 23 2.txt 3.txt tiantian 5",
"\t 例3: des 39 1.txt 2.txt 12345678 tiantian gaoxinma",
"\t : des 49 2.txt 3.txt 12345678 tiantian gaoxinma",
"******************************"
};
INT32 hextofile( ULONG8 *buf ,FILE *writefile, ULONG32 length);/*以16進制寫入文件*/
INT32 encodehex(ULONG8 *tobuf,ULONG8 *frombuf,ULONG32 len);/*16進制解碼*/
INT32 file_enc(FILE *readfile,FILE *writefile,
ULONG8 *key,ULONG32 keynum,
ULONG8 **superkey,ULONG32 n_superkey,
ULONG8 flag);
INT32 file_dec(FILE *readfile,FILE *writefile,
ULONG8 *key,ULONG32 keynum,
ULONG8 **superkey,ULONG32 n_superkey,
ULONG8 flag);
void wz_print_help();
INT32 main(INT32 argc,INT8 *argv[])
{
INT8 *FILENAME1,*FILENAME2;
FILE *fp, *fp2;
ULONG8 *key ;
ULONG8 **superkey ;/*n層加密解密密鑰*/
ULONG8 n_superkey ;
ULONG32 num;
if ( argc >= 5 && (atoi(argv[1]) == 39 || atoi(argv[1]) == 49 ) )
{
n_superkey = argc - 4 ;
superkey = ( INT8 **)calloc(1, n_superkey*sizeof( void *) ) ;
for ( num = 0 ; num < n_superkey ; num++)
{
superkey[num] = argv[4+num] ;
}
}
else if ( argc == 6 && (atoi(argv[1]) == 13 || atoi(argv[1]) == 23 ) && (atoi(argv[5])) > 0)
{
}
else if ( argc == 5 && ( atoi(argv[1]) == 1 || atoi(argv[1]) == 2 ))
{
}
else
{
wz_print_help();
return FAIL;
}
FILENAME1 = argv[2];
FILENAME2 = argv[3];
if ((fp= fopen(FILENAME1,"rb")) == NULL || (fp2 = fopen(FILENAME2,"wb"))==NULL)
{
printf("Can't open file\n");
return FAIL;
}
key = argv[4] ;
switch( atoi(argv[1] ))
{
case 1: /*加密*/
file_enc(fp,fp2,key,0, NULL,0, DESONE);
printf("\n \tDES 一層加密完畢,密文存於%s文件\n",FILENAME2);
break;
case 2:
file_dec(fp,fp2,key,0, NULL, 0,DESONE);
printf("\n \tDES 一層解密完畢,密文存於%s文件\n",FILENAME2);
break;
case 13:
file_enc(fp,fp2,key,atoi(argv[5]),NULL,0,DESTHREE);
printf("\n \tDES %u層單密鑰加密完畢,密文存於%s文件\n",atoi(argv[5]),FILENAME2);
break;
case 23:
file_dec(fp,fp2,key,atoi(argv[5]),NULL,0,DESTHREE);
printf("\n \tDES %u層單密鑰解密完畢,密文存於%s文件\n",atoi(argv[5]),FILENAME2);
break;
case 39:
file_enc(fp,fp2,NULL,0,superkey,n_superkey,DESMULTI);
printf("\n \tDES 多密鑰加密完畢,密文存於%s文件\n",FILENAME2);
free(superkey);
superkey = NULL;
break;
case 49:
file_dec(fp,fp2,NULL,0,superkey,n_superkey,DESMULTI);
printf("\n \tDES 多密鑰加密完畢,密文存於%s文件\n",FILENAME2);
free(superkey);
superkey = NULL;
break;
default:
printf("請選擇是加密|解密 plese choose encrypt|deencrypt\n");
break;
}
fclose(fp);
fclose(fp2);
return SUCCESS;
}
void wz_print_help()
{
INT32 i ;
printf("\t");
for ( i = 0 ; i < 22 ; i++)
{
printf("%c ",5);
}
printf("\n");
for( i = 0 ; i < WZ_COMMEND_NUM ; i++)
{
printf("\t%c\t%s %c\n",5,WZ_Commend_Help[i],5);
}
printf("\t");
for ( i = 0 ; i < 22 ; i++)
{
printf("%c ",5);
}
printf("\n");
for( i = 0 ; i < WZUSEHELPNUM ; i++)
{
printf("\t%s\n",WZ_USE_HELP[i]);
}
return ;
}
INT32 file_enc(FILE *readfile,FILE *writefile,
ULONG8 *key,ULONG32 keynum,
ULONG8 **superkey,ULONG32 n_superkey,
ULONG8 flag)
{
INT32 filelen = 0,readlen = 0,writelen = 0;
ULONG32 totalfilelen = 0 ;/*統計實際的文件的長度*/
ULONG8 readbuf[READFILESIZE] = { 0 };
filelen = fread( readbuf, sizeof( INT8 ), READFILESIZE, readfile );
while( filelen == READFILESIZE )
{
totalfilelen += READFILESIZE;
switch(flag)
{
case DESONE:
des( readbuf,key,READFILESIZE);
break;
case DESTHREE:
des3( readbuf, key ,keynum,READFILESIZE);
break;
case DESMULTI:
desN( readbuf, superkey ,n_superkey,READFILESIZE);
break;
}
hextofile( readbuf, writefile, READFILESIZE );/*以16進制形式寫入文件*/
memset(readbuf,0,READFILESIZE);
filelen = fread( readbuf, sizeof( INT8 ), READFILESIZE, readfile );
}
/*這是從文件中讀出的最後一批數據,長度可能會等於0,所以要先判斷*/
if ( filelen > 0 )
{
/*如果從文件中讀出的長度不等於0,那麼肯定有8個位元組以上的空間
文件長度存在最後8個位元組中*/
totalfilelen += filelen;
memcpy( &readbuf[READFILESIZE-8], (ULONG8*)&totalfilelen,4);
switch(flag)
{
case DESONE:
des( readbuf,key,READFILESIZE);
break;
case DESTHREE:
des3( readbuf, key ,keynum,READFILESIZE);
break;
case DESMULTI:
desN( readbuf, superkey ,n_superkey,READFILESIZE);
break;
}
hextofile( readbuf, writefile,READFILESIZE );/*以16進制形式寫入文件*/
memset(readbuf,0 ,READFILESIZE);
}
else /*filelen == 0*/
{
memcpy( &readbuf[0], (ULONG8*)&totalfilelen,4);
switch(flag)
{
case DESONE:
des( readbuf,key,8);
break;
case DESTHREE:
des3( readbuf, key ,keynum,8);
break;
case DESMULTI:
desN( readbuf, superkey ,n_superkey,8);
break;
}
hextofile( readbuf, writefile, 8);/*以16進制形式寫入文件*/
}
return SUCCESS;
}
INT32 file_dec(FILE *readfile,FILE *writefile,
ULONG8 *key,ULONG32 keynum,
ULONG8 **superkey,ULONG32 n_superkey,
ULONG8 flag)
{
INT32 filelen = 0,readlen = 0,writelen = 0;
ULONG32 totalfilelen = 0 ;/*統計實際的文件的長度*/
INT32 num = 0;
ULONG8 readbuf[READFILESIZE] = { 0 };
ULONG8 sendbuf[READFILESIZE*2] = { 0 };
fseek(readfile,-16,SEEK_END);/*最後16個位元組的表示文件長度的空間*/
filelen = fread( sendbuf, sizeof( INT8 ), 16, readfile );
encodehex( readbuf,sendbuf,8);
switch(flag)
{
case DESONE:
Ddes( readbuf,key,8);
break;
case DESTHREE:
Ddes3( readbuf, key ,keynum,8);
break;
case DESMULTI:
DdesN( readbuf, superkey ,n_superkey,8);
break;
}
/*解密*/
memcpy((ULONG8*)&totalfilelen, &readbuf[0],4);/*得到文件總長*/
memset(readbuf,0 ,8);
memset(sendbuf,0 ,16);
num = totalfilelen/READFILESIZE;/*有幾個READFILESIZE組*/
totalfilelen %= READFILESIZE;
fseek(readfile,0,SEEK_SET);/*跳到文件頭*/
while(num--)
{
filelen = fread( sendbuf, sizeof( INT8 ), READFILESIZE*2, readfile );
encodehex( readbuf,sendbuf,READFILESIZE);
switch(flag)
{
case DESONE:
Ddes( readbuf,key,READFILESIZE);
break;
case DESTHREE:
Ddes3( readbuf, key ,keynum,READFILESIZE);
break;
case DESMULTI:
DdesN( readbuf, superkey ,n_superkey,READFILESIZE);
break;
}
writelen = fwrite(readbuf, sizeof( INT8 ), READFILESIZE, writefile);
memset(readbuf,0 ,READFILESIZE);
memset(sendbuf,0 ,READFILESIZE*2);
}
if ( totalfilelen > 0 )/*最後一塊有多餘的元素*/
{
filelen = fread( sendbuf, sizeof( INT8 ), READFILESIZE*2, readfile );
encodehex( readbuf,sendbuf,READFILESIZE);
switch(flag)
{
case DESONE:
Ddes( readbuf,key,READFILESIZE);
break;
case DESTHREE:
Ddes3( readbuf, key ,keynum,READFILESIZE);
break;
case DESMULTI:
DdesN( readbuf, superkey ,n_superkey,READFILESIZE);
break;
}
writelen = fwrite(readbuf, sizeof( INT8 ), totalfilelen, writefile);
memset(readbuf,0 ,READFILESIZE);
memset(sendbuf,0 ,READFILESIZE*2);
}
return SUCCESS;
}
INT32 hextofile( ULONG8 *buf ,FILE *writefile, ULONG32 length)
{
ULONG32 writelen = 0 ;
/*以16進制形式寫入文件*/
while( writelen < length)
{
if(buf[writelen] == 0)
{
fprintf( writefile, "%x", 0 );
fprintf( writefile, "%x", 0 );
}
else if (buf[writelen] < 0x10)
{
fprintf( writefile, "%x", 0 );
fprintf( writefile, "%x", buf[writelen] );
}
else
{
fprintf( writefile, "%x", buf[writelen] );
}
writelen++;
}
return SUCCESS;
}
INT32 encodehex(ULONG8 *tobuf,ULONG8 *frombuf,ULONG32 len)
{
ULONG8 *readfirst = frombuf ;
ULONG8 *readend = &frombuf[1] ;
INT8 *s;
ULONG8 y[2] ;
ULONG32 i;
for ( i = 0 ; i < len ; i++)
{
y[0] = *readfirst ;
y[1] = *readend ;
readfirst += 2 ;
readend += 2 ;
tobuf[i] = (ULONG8)strtol((INT8*)y, &s, 16);
}
return SUCCESS;
}
7. C#加密Java解密
DES加密 java與 C# 可以相互加密解密
這里的KEY採用Base64編碼,便用分發,因為Java的Byte范圍為-128至127,c#的Byte范圍是0-255
核心是確定Mode和Padding,關於這兩個的意思可以搜索3DES演算法相關文章
一個是C#採用CBC Mode,PKCS7 Padding,Java採用CBC Mode,PKCS5Padding Padding,
另一個是C#採用ECB Mode,PKCS7 Padding,Java採用ECB Mode,PKCS5Padding Padding,
Java的ECB模式不需要IV
對字元加密時,雙方採用的都是UTF-8編碼
C# 代碼
/// <summary>
/// DES3加密解密
/// </summary>
public class Des3
{
#region CBC模式**
/// <summary>
/// DES3 CBC模式加密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV</param>
/// <param name="data">明文的byte數組</param>
/// <returns>密文的byte數組</returns>
public static byte[] Des3EncodeCBC( byte[] key, byte[] iv, byte[] data )
{
//復制於MSDN
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
tdsp = new ();
tdsp.Mode = CipherMode.CBC; //默認值
tdsp.Padding = PaddingMode.PKCS7; //默認值
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, 0, data.Length );
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 CBC模式解密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV</param>
/// <param name="data">密文的byte數組</param>
/// <returns>明文的byte數組</returns>
public static byte[] Des3DecodeCBC( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
tdsp = new ();
tdsp.Mode = CipherMode.CBC;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
#region ECB模式
/// <summary>
/// DES3 ECB模式加密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV(當模式為ECB時,IV無用)</param>
/// <param name="str">明文的byte數組</param>
/// <returns>密文的byte數組</returns>
public static byte[] Des3EncodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
tdsp = new ();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, 0, data.Length );
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 ECB模式解密
/// </summary>
/// <param name="key">密鑰</param>
/// <param name="iv">IV(當模式為ECB時,IV無用)</param>
/// <param name="str">密文的byte數組</param>
/// <returns>明文的byte數組</returns>
public static byte[] Des3DecodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
tdsp = new ();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, 0, fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
/// <summary>
/// 類測試
/// </summary>
public static void Test()
{
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
//key為abcdefghijklmnopqrstuvwx的Base64編碼
byte[] key = Convert.FromBase64String( "" );
byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; //當模式為ECB時,IV無用
byte[] data = utf8.GetBytes( "中國ABCabc123" );
System.Console.WriteLine( "ECB模式:" );
byte[] str1 = Des3.Des3EncodeECB( key, iv, data );
byte[] str2 = Des3.Des3DecodeECB( key, iv, str1 );
System.Console.WriteLine( Convert.ToBase64String( str1 ) );
System.Console.WriteLine( System.Text.Encoding.UTF8.GetString( str2 ) );
System.Console.WriteLine();
System.Console.WriteLine( "CBC模式:" );
byte[] str3 = Des3.Des3EncodeCBC( key, iv, data );
byte[] str4 = Des3.Des3DecodeCBC( key, iv, str3 );
System.Console.WriteLine( Convert.ToBase64String( str3 ) );
System.Console.WriteLine( utf8.GetString( str4 ) );
System.Console.WriteLine();
}
}
java 代碼:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Des3 {
public static void main(String[] args) throws Exception {
byte[] key=new BASE64Decoder().decodeBuffer("");
byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] data="中國ABCabc123".getBytes("UTF-8");
System.out.println("ECB加密解密");
byte[] str3 = des3EncodeECB(key,data );
byte[] str4 = ees3DecodeECB(key, str3);
System.out.println(new BASE64Encoder().encode(str3));
System.out.println(new String(str4, "UTF-8"));
System.out.println();
System.out.println("CBC加密解密");
byte[] str5 = des3EncodeCBC(key, keyiv, data);
byte[] str6 = des3DecodeCBC(key, keyiv, str5);
System.out.println(new BASE64Encoder().encode(str5));
System.out.println(new String(str6, "UTF-8"));
}
/**
* ECB加密,不要IV
* @param key 密鑰
* @param data 明文
* @return Base64編碼的密文
* @throws Exception
*/
public static byte[] des3EncodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* ECB解密,不要IV
* @param key 密鑰
* @param data Base64編碼的密文
* @return 明文
* @throws Exception
*/
public static byte[] ees3DecodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC加密
* @param key 密鑰
* @param keyiv IV
* @param data 明文
* @return Base64編碼的密文
* @throws Exception
*/
public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC解密
* @param key 密鑰
* @param keyiv IV
* @param data Base64編碼的密文
* @return 明文
* @throws Exception
*/
public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
}
8. linux怎麼獲取使用md5處理前的密碼
這里以字元串123456為例子,它的md5密文值為:
這里以1.txt為需要被加密的文件。
一、 用oppnssl md5 加密字元串和文件的方法。
1. oppnssl md5 加密字元串的方法
a.手動輸入命令及過程如下:
#openssl //在終端中輸入openssl後回車。
OpenSSL> md5 //輸入md5後回車
123456 //接著輸入123456,不要輸入回車。然後按3次ctrl+d。
123456 //123456後面的就是密文了
解釋:為何在輸入123456後不回車呢?
是因為openssl默認會把回車符當做要加密的字元串中的一個字元,所以得到的結果不同。如果你輸入123456後回車,在按2次ctrl+d。得到的結果是:
OpenSSL> md5
123456
//因為openssl不忽略回車符導致的
b.或者直接用管道命令
# echo -n 123456 | openssl md5 //必須要有-n參數,否則就不是這個結果了。
解釋:為何要加-n這個參數?
-n就表示不輸入回車符,這樣才能得到正確的結果。如果你不加-n,那麼結果和前面說的一樣為:
//因為openssl不忽略回車符導致的
2.用openssl加密文件。
#openssl md 5 -in 1.txt
##################################################3
Openssl其他相關加密的命令參數:引自:實用命令:利用openssl進行BASE64編碼解碼、md5/sha1摘要、AES/DES3加密解密 收藏
一. 利用openssl命令進行BASE64編碼解碼(base64 encode/decode)
1. BASE64編碼命令
對字元串『abc』進行base64編碼:
# echo abc | openssl base64
YWJjCg== (編碼結果)
如果對一個文件進行base64編碼(文件名t.txt):
# openssl base64 -in t.txt
2. BASE64解碼命令
求base64後的字元串『YWJjCg==』的原文:
# echo YWJjCg== | openssl base64 -d
abc (解碼結果)
如果對一個文件進行base64解碼(文件名t.base64):
# openssl base64 -d -in t.base64
二. 利用openssl命令進行md5/sha1摘要(digest)
1. 對字元串『abc』進行md5摘要計算:echo abc | openssl md5
若對某文件進行md5摘要計算:openssl md5 -in t.txt
2. 對字元串『abc』進行sha1摘要計算:echo abc | openssl sha1
若對某文件進行sha1摘要計算:openssl sha1 -in t.txt
三. 利用openssl命令進行AES/DES3加密解密(AES/DES3 encrypt/decrypt)
對字元串『abc』進行aes加密,使用密鑰123,輸出結果以base64編碼格式給出:
# echo abc | openssl aes-128-cbc -k 123 -base64
U2FsdGVkX18ynIbzARm15nG/JA2dhN4mtiotwD7jt4g= (結果)
對以上結果進行解密處理:
# echo U2FsdGVkX18ynIbzARm15nG/JA2dhN4mtiotwD7jt4g= | openssl aes-128-cbc -d -k 123 -base64
abc (結果)
若要從文件里取原文(密文)進行加密(解密),只要指定 -in 參數指向文件名就可以了。
進行des3加解密,只要把命令中的aes-128-cbc換成des3就可以了。
註:只要利用openssl help就可以看到更多的安全演算法了。
###############################################
二、 利用php的md5函數加密字元串
#touch a.php //創建a.php文件
#vi a.php //用vi 編輯a.php文件
將<?php echo md5(123456); ?>輸入進去後保存
#php a.php //運行a.php文件
顯示:
三、 利用md5sum命令
A.在linux或Unix上,md5sum是用來計算和校驗文件報文摘要的工具程序。一般來說,安裝了Linux後,就會有md5sum這個工具,直接在命令行終端直接運行。可以用下面的命令來獲取md5sum命令幫助 man md5sum
#md5sum –help
有個提示:「With no FILE, or when FILE is -, read standard input.」翻譯過來就是「如果沒有輸入文件選項或者文件選項為 - ,則從標磚讀取輸入內容」,即可以直接從鍵盤讀取字元串來加密。
利用md5sum加密字元串的方法
# md5sum //然後回車
123456 //輸入123456.然後按兩次ctrl+d.
顯示:
123456 紅色代表加密後的值
還可以用管道命令:
#echo -n '123123' | md5sum
或者寫成md5加密腳本,名字叫md5.sh,
將以下內容復制進腳本里:
#!/bin/bash
echo -n $1 | md5sum | awk '{print $1}'
保存後,給腳本執行許可權。
#sh md5.sh 123456
顯示:
B.其實也可以將文本放入文本文件,然後用md5sum 加密改文本,也可以得到字元串加密的值。過程如下:
#touch a.txt
#echo -n 123456 > a.txt //將123456寫進文本文件,不能丟了 –n參數,避免回車符干擾
#md5sum a.txt
顯示: a.txt
ctrl+d有兩個含義:
一是向程序發送文件輸入結束符EOF。
二是向程序發送exit退出指令。程序收到信號後具體動作是結束輸入、然後等待,還是直接退出,那就要看該程序捕獲信號後是如何操作的了。
md5sum屬於第一個含義。兩次strl+d了,第一次讀取EOF指令,再次捕獲就會當成exit指令。而shell一類的程序,會直接把ctrl+d解析為退出指令。
9. 我想做一個加密解密文件的VB程序!用des加密解密方法!!! 希望高手解答!
vb.net code注意隨機密碼按鈕在沒用,調試時你自己輸入密碼,一定為8位,我是將文件存在D盤,你自己在修改一下,那個就很簡單
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sSecretKey As String = Me.TextBox2.Text
EncryptFile(Me.TextBox1.Text, "D:\JMtest.txt", sSecretKey)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim sSecretKey As String = Me.TextBox2.Text
DecryptFile("D:\JMtest.txt", "D:\Decrypted.txt", sSecretKey)
End Sub
Sub EncryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
Dim DES As New DESCryptoServiceProvider
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
Dim byteArrayInput(fsInput.Length - 1) As Byte
fsInput.Read(byteArrayInput, 0, byteArrayInput.Length)
cryptostream.Write(byteArrayInput, 0, byteArrayInput.Length)
cryptostream.Close()
End Sub
Sub DecryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
Dim DES As New DESCryptoServiceProvider
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim fsread As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor
Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
Dim fsDecrypted As New StreamWriter(sOutputFilename)
fsDecrypted.Write(New StreamReader(cryptostreamDecr, System.Text.ASCIIEncoding.Default).ReadToEnd)
fsDecrypted.Flush()
fsDecrypted.Close()
End Sub
Private Sub BtnChoose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnChoose.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName <> "" Then
Me.TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub
End Class
10. openssl提供 DES_ecb3_encrypt方法
一. 利用openssl命令進行BASE64編碼解碼(base64 encode/decode)
1. BASE64編碼命令
對字元串『abc』進行base64編碼:
# echo abc | openssl base64
YWJjCg== (編碼結果)
如果對一個文件進行base64編碼(文件名t.txt):
# openssl base64 -in t.txt
2. BASE64解碼命令
求base64後的字元串『YWJjCg==』的原文:
# echo YWJjCg== | openssl base64 -d
abc (解碼結果)
如果對一個文件進行base64解碼(文件名t.base64):
# openssl base64 -d -in t.base64
二. 利用openssl命令進行md5/sha1摘要(digest)
1. 對字元串『abc』進行md5摘要計算:echo abc | openssl md5
若對某文件進行md5摘要計算:openssl md5 -in t.txt
2. 對字元串『abc』進行sha1摘要計算:echo abc | openssl sha1
若對某文件進行sha1摘要計算:openssl sha1 -in t.txt
三. 利用openssl命令進行AES/DES3加密解密(AES/DES3 encrypt/decrypt)
對字元串『abc』進行aes加密,使用密鑰123,輸出結果以base64編碼格式給出:
# echo abc | openssl aes-128-cbc -k 123 -base64
U2FsdGVkX18ynIbzARm15nG/JA2dhN4mtiotwD7jt4g= (結果)
對以上結果進行解密處理:
# echo U2FsdGVkX18ynIbzARm15nG/JA2dhN4mtiotwD7jt4g= | openssl aes-128-cbc -d -k 123 -base64
abc (結果)
若要從文件里取原文(密文)進行加密(解密),只要指定 -in 參數指向文件名就可以了。
進行des3加解密,只要把命令中的aes-128-cbc換成des3就可以了。
另外,站長團上有產品團購,便宜有保證