注:下面的代码中用了Map,Base64,log,Result等都为自定义类型,太长就不一一贴出.
/*
*
*
* 文件名称:EncryptAES.cpp
* 摘 要:
* AES对称加密与AES对称解密,生成会话密钥
* 当前版本:1.0
* 作 者:周绍禹
* 创建日期:2012年3月4日
*/
#include "StdAfx.h"
#include "EncryptAES.h"
#include "base64.h"
#include <comdef.h>
#include "generic.h"
#include "Map.h"
/**
*
*初始化CSP
*
*/
CEncryptAES::CEncryptAES():CSP_NAME(MS_ENH_RSA_AES_PROV)
{
log = new Log("CEncryptAES");
}
CEncryptAES::~CEncryptAES()
{
if(log) delete log;
}
//-----------------------------------------------------------
// 函数名称:
// encrypt
// 参数:
// - string text 待加密明文
// - string pwd_base64 对称密钥base64码
// 返回:
// Result*
// 说明:
// AES对称加密
//-----------------------------------------------------------
Result* CEncryptAES::encrypt(string text, string pwd_base64)
{
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
int dwLength = 0;
if(!CryptAcquireContext(&hCryptProv,
NULL,
this->CSP_NAME,//CSP_NAME
PROV_RSA_AES,
CRYPT_VERIFYCONTEXT))
{
DWORD dwLastErr = GetLastError();
if(NTE_BAD_KEYSET == dwLastErr)
{
Result* result = new Result("EncryptAES.cpp",54,"密钥库不存在,或者访问被拒绝!","{}");
return result;
}
else{
if(!CryptAcquireContext(&hCryptProv,
NULL,
this->CSP_NAME,
PROV_RSA_AES,
CRYPT_NEWKEYSET))
{
Map* map = new Map(1);
map->put("errcode",dwLastErr);
string errcode = map->toString();
delete map;
Result* result = new Result("EncryptAES.cpp",68,"密钥库已存在,创建密钥库失败!",errcode);
return result;
}
}
}
HCRYPTPROV_Holder holder(hCryptProv);
if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash))
{
string errorcode = getErrorCode();
Result* result = new Result("EncryptAES.cpp",87,"创建hash对象失败!",errorcode.length()==0?"{}":errorcode);
if(hKey) CryptDestroyKey(hKey);
if(hCryptProv) CryptReleaseContext(hCryptProv, 0);
return result;
}
//hash密钥字符串
BYTE *pPwd = Base64::base64_decode(pwd_base64,dwLength);
if(!CryptHashData(hHash, pPwd, dwLength, 0))
{
string errorcode = getErrorCode();
Result* result = new Result("EncryptAES.cpp",103,"对密钥做hash运算失败!",errorcode.length()==0?"{}":errorcode);
if(pPwd) delete []pPwd;
if(hHash) CryptDestroyHash(hHash);
if(hCryptProv) CryptReleaseContext(hCryptProv, 0);
return result;
}
// 基于hash的密钥获取会话密钥
if(!CryptDeriveKey(hCryptProv, CALG_AES_128, hHash, CRYPT_EXPORTABLE, &hKey))
{
string errorcode = getErrorCode();
Result* result = new Result("EncryptAES.cpp",111,"获取会话密钥失败!",errorcode.length()==0?"{}":errorcode);
if(pPwd) delete []pPwd;
if(hHash) CryptDestroyHash(hHash);
if(hCryptProv) CryptReleaseContext(hCryptProv, 0);
return result;
}
int len = text.length();
BYTE *pD