⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 des.cpp

📁 DES加密
💻 CPP
字号:
#include "DES.H"
//         [IN]   lpszKey 加密密钥
//         [IN]   lpszIv 初始化向量
DesSecurity::DesSecurity(LPTSTR lpszKey, LPTSTR lpszIv)
{
    if (lpszKey == NULL || lpszIv == NULL) {
       throw "Parameter is null!"; 
    }
    m_hKey = NULL;
    init(lpszKey, lpszIv);
}
 
DesSecurity::~DesSecurity(void)
{
    // Destroy the session key.
    if(m_hKey != 0) CryptDestroyKey(m_hKey);
 
}
 
 
void DesSecurity::init(LPTSTR lpszKey, LPTSTR lpszIv) {
    HCRYPTPROV hProv;
    HCRYPTHASH hHash;
    TCHAR szDebug[256];
    DWORD dwLength;
    try {
       // 获得密钥容器
       if(!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0)) {
           sprintf(szDebug, "Error %x during CryptAcquireContext!\n", GetLastError());
           throw szDebug;
       }
       // 创建MD5散列对象
       if(!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) {
            sprintf(szDebug, "Error %x during CryptCreateHash!\n", GetLastError());
            throw szDebug;
       }
       // 散列密钥
       dwLength = strlen(lpszKey);
       if(!CryptHashData(hHash, (LPBYTE)lpszKey, dwLength, 0)) {
            sprintf(szDebug, "Error %x during CryptHashData!\n", GetLastError());
            throw szDebug;
       }
       // 创建会话密钥
       if(!CryptDeriveKey(hProv, CALG_DES, hHash, 0, &m_hKey)) {
            sprintf(szDebug, "Error %x during CryptDeriveKey!\n", GetLastError());
            throw szDebug;
       }
       // 设置初始化向量.
       if(!CryptSetKeyParam(m_hKey, KP_IV, (LPBYTE)lpszIv, 0)) {
            sprintf(szDebug, "Error %x during CryptSetKeyParam!\n", GetLastError());
            throw szDebug;
       }
    } catch(LPTSTR lpszDebug) {
       // Destroy the hash object.
       if(hHash != 0) CryptDestroyHash(hHash);
       // Release the provider handle.
       if(hProv != 0) CryptReleaseContext(hProv, 0);
       throw lpszDebug;
    }
 
}
// 
// 功能: 解密数据
// 参数: 
//     [IN]   lpszSrc   待解密数据(BASE64编码)
//     [IN/OUT] lpszDst 存放解密后数据的缓冲区
//     [IN/OUT] pnLen       输入时指缓冲区的长度,输出时指解密后数据的长度
// 返回值:
//     TRUE   解密成功
//     FALSE 解密失败
//
BOOL DesSecurity::Decode(LPTSTR lpszSrc, LPBYTE lpszDst, PINT pnLen) {
    if (lpszSrc == NULL || lpszDst == NULL || pnLen == NULL) {
       SetLastErrorEx(ERROR_INVALID_PARAMETER ,SLE_ERROR);
       return false;
    }
    if (!Base64Decode(lpszSrc, _tcslen(lpszSrc), lpszDst, pnLen))
       return false;
    if (!CryptDecrypt(m_hKey, 0, true, 0, lpszDst, (DWORD*)pnLen))
       return false;
    return true;
}

void main()
{

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -