des.h
const BYTE IV[] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
DWORD DESEncrypt(CString data, CString password, BYTE * buffer, DWORD bufferLength);
DWORD DESDecrypt(BYTE* buffer, DWORD bufferLength, CString password);
***************************************************************
des.cpp
DWORD DESEncrypt(CString data, CString password, BYTE* buffer, DWORD bufferLength)
CT2CA passwd(password, CP_UTF8);
CT2CA secret(data, CP_UTF8);
DWORD dataLength = strlen(secret);
if (buffer == NULL || bufferLength < dataLength + 8 - (dataLength % 8) || password.GetLength() < 8) return 0;
memcpy(buffer, secret, dataLength);
HCRYPTKEY hSessionKey = NULL;
blob.header.bType = PLAINTEXTKEYBLOB;
blob.header.bVersion = CUR_BLOB_VERSION;
blob.header.reserved = 0;
blob.header.aiKeyAlg = CALG_DES;
memcpy(blob.rgbKeyData, passwd, 8);
bResult &= CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, 0);
bResult &= CryptImportKey(hProv, (BYTE*)&blob, sizeof(blob), 0, 0, &hSessionKey);
bResult &= CryptSetKeyParam(hSessionKey, KP_IV, (BYTE*)IV, 0);
bResult &= CryptEncrypt(hSessionKey, NULL, TRUE, 0, (BYTE*)buffer, &dataLength, bufferLength);
bResult &= CryptDestroyKey(hSessionKey);
bResult &= CryptReleaseContext(hProv, 0);
return bResult ? dataLength : 0;
DWORD DESDecrypt(BYTE* buffer, DWORD bufferLength, CString password)
CT2CA passwd(password, CP_UTF8);
DWORD dataLength = bufferLength;
if (buffer == NULL || password.GetLength() < 8) return 0;
HCRYPTKEY hSessionKey = NULL;
blob.header.bType = PLAINTEXTKEYBLOB;
blob.header.bVersion = CUR_BLOB_VERSION;
blob.header.reserved = 0;
blob.header.aiKeyAlg = CALG_DES;
memcpy(blob.rgbKeyData, passwd, 8);
bResult &= CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, 0);
bResult &= CryptImportKey(hProv, (BYTE*)&blob, sizeof(blob), 0, 0, &hSessionKey);
bResult &= CryptSetKeyParam(hSessionKey, KP_IV, (BYTE*)IV, 0);
bResult &= CryptDecrypt(hSessionKey, NULL, TRUE, 0, buffer, &dataLength);
bResult &= CryptDestroyKey(hSessionKey);
bResult &= CryptReleaseContext(hProv, 0);
return bResult ? dataLength : 0;
int dataLength = DESEncrypt("testt", "123456", buffer, sizeof(buffer));
int bufferLength = sizeof(buffer);
int _dataLength = DESDecrypt(buffer, bufferLength, "123456");
char *dest = (char *)malloc((_dataLength + 1) * sizeof(char));
memcpy(dest, buffer, _dataLength);
dest[_dataLength] = '\0';//必须加结束符
printf("result:%s", dest);
本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/5801611.html,如需转载请自行联系原作者