3DES

// 3DES.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdio.h"
#include "des3.h"
#include "Base64.h"
#define MAX_LENGTH 1024
const char DES3_Key[] = "1D;rsw@{p,cSe.?w";

int des3_ecb_encryptStr (unsigned char * keyStr, unsigned char *sIn, unsigned char * sOutCode, int inLen){
	unsigned char key[16];
	unsigned char pt[9];
    unsigned char ct[9];

	unsigned char sOut[MAX_LENGTH];

	int start, outLen;

	memset (key, '\0', 16);
	strncpy ((char*)key, (char*)keyStr, 16);
	key[7]=key[15]='\0';

	start = 0;
	outLen = 0;
	while (start <= inLen) {
		memset (pt, '\0', 8);
		memset (ct, '\0', 8);
		if (start + 8 <= inLen ) memcpy (pt, start + sIn, 8);
		else memcpy (pt, start + sIn, inLen - start+1);

		des3_ecb_encrypt(pt,ct,key,16);
		memcpy (sOut + start, ct, 8);
		outLen += 8;
		start += 8;
	}
	return Base64Encode (sOut,sOutCode, outLen);
}

int des3_ecb_decryptStr (unsigned char * keyStr, unsigned char *sInCode, unsigned char * sOut, int inCodeLen){
	unsigned char key[16];
	unsigned char pt[9];
    unsigned char ct[9];
	unsigned char sIn[MAX_LENGTH];

	int start, outLen, inLen;

	inLen = Base64Decode (sInCode, sIn, inCodeLen);

	memset (key, '\0', 16);
	strncpy ((char*)key, (char*)keyStr, 16);
	key[7]=key[15]='\0';

	start = 0;
	outLen = 0;
	while (start < inLen) {
		memset (pt, '\0', 8);
		memset (ct, '\0', 8);
		if (start + 8 <= inLen ) memcpy (pt, start + sIn, 8);
		else memcpy (pt, start + sIn, inLen - start+1);
		des3_ecb_decrypt(pt,ct,key,16);
		memcpy (sOut + start, ct, 8);

		outLen += 8;
		start += 8;
	}
	
	return outLen;
}
int PwEnCrypt (char * sIn, char * sOut){
	int len;
	unsigned char Des3key[32];

	len = strlen (sIn);
	
	memset (Des3key , 0, sizeof (Des3key));
	memcpy (Des3key, DES3_Key, 16);

	return des3_ecb_encryptStr (Des3key, (unsigned char *)sIn, (unsigned char *)sOut, len);

}
int PwDeCrypt (char * sIn, char * sOut){
	int len;
	unsigned char Des3key[32];

	len = strlen (sIn);
	
	memset (Des3key , 0, sizeof (Des3key));
	memcpy (Des3key, DES3_Key, 16);


	return des3_ecb_decryptStr ((unsigned char *) Des3key, (unsigned char *)sIn, (unsigned char *)sOut, len);
}


int _tmain(int argc, _TCHAR* argv[])
{
	char sIn[MAX_LENGTH];
	char sOut[MAX_LENGTH];
	char *str = "hello world";

	PwEnCrypt(str,sOut);

	printf("%s\n",sOut);

	PwDeCrypt(sOut,sIn);
	printf("%s\n",sIn);

	return 0;
}

源码





你可能感兴趣的:(c,des,3des)