陈博的空间

对称加密算法

      对称加密算法是一个比较传统的加密算法,其加解密都是基于一个密钥进行操作的。也称之为单钥加密算法。

单钥密码系统的安全性依赖于以下两个因素:
第一、加密算法必须是足够强的,仅仅基于密文本身去解密信息在实践上是不可能的。
第二、加密方法的安全性依赖于密钥的秘密性,而不是算法的秘密性,因此,我们没有必要确保算法的秘密性(事实上,现实中使用的很多单钥密码系统的算法都是公开的),但是我们一定要保证密钥的秘密性。
其典型的有rc2加密算法,rc4加密算法,DES加密算法,triple DES加密算法。
图是一个比较典型的加解密流程,摘自http://blog.csdn.net/songkexin/archive/2007/12/16/1941391.aspx。下面以rc2算法为例,讲一下利用windows AP I进行简单的加解密流程
typedef struct tagENCRYPBYTE{
     int size;
     BYTE* pByte;
  }ENCRYPBYTE, *PENCRYPBYTE;

  

  BOOL Encrypt(LPCTSTR strSrc,LPCTSTR strKey,PENCRYPBYTE pEncryptByte)
  {
     int ret;
     HCRYPTPROV hCryptProv = NULL;
 
     // Handle to the cryptography key.
     HCRYPTKEY hKey = NULL;

     // Handle to the hash object.
     HCRYPTHASH hHash = NULL;

     pEncryptByte->size = 0;
     pEncryptByte->pByte = NULL;

     if(!::CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {

         return FALSE  ;
     }
 
     // Create an empty hash object.
     if(!::CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) {
        ::CryptDestroyHash(hHash);
        ::CryptReleaseContext(hCryptProv,0);
        return FALSE ;
     }

     if(!CryptHashData(hHash, (const BYTE*)strKey, _tcslen(strKey) * sizeof(TCHAR), 0))
     {
        ::CryptDestroyHash(hHash);
        ::CryptReleaseContext(hCryptProv,0);

        return FALSE;
     }
     // Create a session key based on the hash of the password.
     if(!CryptDeriveKey(hCryptProv, CALG_RC2, hHash, CRYPT_EXPORTABLE, &hKey)){
        ::CryptDestroyHash(hHash);
        ::CryptReleaseContext(hCryptProv,0);
        return FALSE;
     }
 
     BYTE* pData;
     DWORD dwDataLength;
     dwDataLength = (_tcslen(strSrc)+1)*sizeof(TCHAR);
     ULONGLONG uCapacity = dwDataLength*2;
     pData = (BYTE*)malloc(uCapacity);

     if(pData == NULL){

           ::CryptDestroyHash(hHash);
           ::CryptReleaseContext(hCryptProv,0);
        return FALSE;

     }  
     memcpy(pData,strSrc,dwDataLength);
     if(!::CryptEncrypt(hKey, NULL, TRUE, 0, pData, &dwDataLength, uCapacity)){
        ret = GetLastError();
     }
     else{
        ret = 0;
     }
     if(hHash)
        ::CryptDestroyHash(hHash);

     if(hKey)
        ::CryptDestroyKey(hKey);

     if(hCryptProv)
        :ryptReleaseContext(hCryptProv, 0);
     if(ret != 0){
        free(pData);
        return FALSE;
     }
     pEncryptByte->size   = dwDataLength;
     pEncryptByte->pByte = (BYTE*)pData;
     return TRUE;
}

解密算法与此流程一样,就不写了

 

posted on 2010-12-31 12:18  bob.chan  阅读(408)  评论(0编辑  收藏  举报

导航