加密步驟如下:
1)首先將資料按照8個位元組一組進行分組得到D1D2......Dn(若資料不是8的整數倍,用指定的PADDING資料補位)
2)第一組資料D1與初始化向量I異或後的結果進行DES加密得到第一組密文C1(初始化向量I為全零)
3)第二組資料D2與第一組的加密結果C1異或以後的結果進行DES加密,得到第二組密文C2
4)之後的資料以此類推,得到Cn
5)按順序連為C1C2C3......Cn即為加密結果。
3Des.h檔案
#ifndef _3DES#define _3DES#include <strings.h>#ifdef __cplusplusextern "C"{#endif /* __cplusplus */ unsigned char* GetKey(unsigned char *RandomData); void DesEncrypt_ECB(unsigned char *key, unsigned char *data); unsigned char* DesEncrypt_CBC(unsigned char *key, unsigned char *data,int len);#ifdef __cplusplus};#endif /* __cplusplus */#endif /* defined(_3DES) */
3Des.cpp檔案
#include "3DES.h"#include "DES.h"#include <iostream>unsigned char* GetKey(unsigned char *RandomData){ unsigned char* key=(unsigned char*)malloc(16); for (int i=0; i<16; i++) { key[i]=0xFF; } unsigned char RevertData[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; for (int i=0; i<sizeof(RevertData); i++) { RevertData[i]=~RandomData[i]; } DesEncrypt_ECB(key, RandomData); DesEncrypt_ECB(key, RevertData); for (int i=0; i<16; i++) { if(i<8) key[i]=RandomData[i]; else key[i]=RevertData[i-8]; } return key;}void DesEncrypt_ECB(unsigned char *key, unsigned char *data){ DesEncrypt(key,data);DesDecrypt(key,data);DesEncrypt(key,data);}unsigned char* DesEncrypt_CBC(unsigned char *key, unsigned char *data, int len){ unsigned char* data2=(unsigned char*)malloc(8);unsigned char data3[8]; int sum=len/8+1; int yushu=len%8; for (int i=0;i<sum;i++) { for (int j=0; j<8; j++) { if(i<sum-1){ data2[j]=data[i*8+j]; if(j==7&&i==0){ DesEncrypt(key, data2); for (int k=0; k<8; k++) { data3[k]=data2[k]; } }else if(j==7&&i>0){ for (int k=0; k<8; k++) { data2[k]^=data3[k]; } DesEncrypt(key, data2); for (int k=0; k<8; k++) { data3[k]=data2[k]; } } }else if(yushu==0&&i==sum-1&&j==7){data2[0]=0x80;for(int k=1;k<8;k++){data2[k]=0x00;} for (int k=0; k<8; k++) { data2[k]^=data3[k]; } DesEncrypt(key, data2); }else if(yushu>0){ if(j<yushu){ data2[j]=data[i*8+j]; }else if(j==yushu){ data2[j]=0x80; }else if(j>yushu&&j!=7){ data2[j]=0x00; }else if(j==7){ data2[j]=0x00; for (int k=0; k<8; k++) { data2[k]^=data3[k]; } DesEncrypt(key, data2); } } } } return data2;}
main函數
unsigned char RandomData[16]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char* key=GetKey(RandomData); unsigned char data[17]={0x14,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};unsigned char* macdata=DesEncrypt_CBC(key,data,sizeof(data)); for (int i=0; i<8; i++) { printf("%x\n",macdata[i]); } free(macdata); free(key);