歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> OpenSSL與CryptoAPI交互AES加密解密

OpenSSL與CryptoAPI交互AES加密解密

日期:2017/3/1 10:12:02   编辑:Linux編程

繼上次只有CryptoAPI的加密後,這次要實現openssl的了。

動機:利用CryptoAPI制作windows的IE,火狐和chrome加密控件後,這次得加上與Android的加密信息交互。

先前有說openssl移植到android的過程,這裡就不再提android如何調用openssl了,而那一篇第9條提到的openssl與cryptoAPI兼容的兩種方式感覺實現都不太好用,這裡再次提出一種AES加密的實現方式。

寫這邊文章的最主要的原因,用過CryptoAPI的都知道,很多東西都封裝了,如果要與其他加密組件交互,得用其他組件來實現CryptoAPI的思路。

環境:windows visual studio 2010,openssl windows(x86)動態庫。

在CryptoAPI中進行AES加密解密,有一種實現方式是調用CryptDeriveKey通過提供的字節數組的hash值獲取key。

先來看下CryptoAPI實現AES,來個簡單點的版本。

  1. void cryptoAPI_encrypt(string text,unsigned char* pwd,unsigned char** encryptText,int &out_len)
  2. {
  3. HCRYPTPROV hCryptProv = NULL;
  4. HCRYPTKEY hKey = 0;
  5. HCRYPTHASH hHash = 0;
  6. int dwLength = 0;
  7. if(!CryptAcquireContext(&hCryptProv,
  8. NULL,
  9. CSP_NAME,//CSP_NAME
  10. PROV_RSA_AES,
  11. CRYPT_VERIFYCONTEXT))
  12. {
  13. DWORD dwLastErr = GetLastError();
  14. if(NTE_BAD_KEYSET == dwLastErr)
  15. {
  16. return;
  17. }
  18. else{
  19. if(!CryptAcquireContext(&hCryptProv,
  20. NULL,
  21. CSP_NAME,
  22. PROV_RSA_AES,
  23. CRYPT_NEWKEYSET))
  24. {
  25. return;
  26. }
  27. }
  28. }
  29. if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash))
  30. {
  31. return;
  32. }
  33. BYTE *pPwd = pwd;
  34. if(!CryptHashData(hHash, pPwd, 16, 0))
  35. {
  36. return;
  37. }
  38. if(!CryptDeriveKey(hCryptProv, CALG_AES_128, hHash, CRYPT_EXPORTABLE, &hKey))
  39. {
  40. return;
  41. }
  42. int len = text.length();
  43. BYTE *pData ;
  44. pData = (BYTE*)malloc(len*4);
  45. memcpy(pData,text.c_str(),len);
  46. DWORD dwLen = len;
  47. if(!CryptEncrypt(hKey, NULL, true, 0, pData, &dwLen, len*4))
  48. {
  49. return;
  50. }
  51. cout <<"--------------------------" << endl << "cryptoAPI encrypt"<<endl;
  52. printBytes(pData,dwLen);
  53. *encryptText = pData;
  54. out_len = dwLen;
  55. CryptDestroyHash(hHash);
  56. CryptDestroyKey(hKey);
  57. CryptReleaseContext(hCryptProv,0);
  58. }
這裡將傳進來的字節數組密鑰先進行MD5摘要後,再通過CryptoDeriveKey來得到最後用來加密的密鑰

openssl要以同樣的方式做一次這個步驟,首先是MD5摘要,相對比較簡單

  1. unsigned char* openssl_md5(unsigned char*sessionKey,size_t n)
  2. {
  3. unsigned char *ret = (unsigned char*)malloc(MD5_DIGEST_LENGTH);
  4. MD5(sessionKey,n,ret);
  5. return ret;
  6. }
然後再來實現CryptoDeriveKey,先來看下MSDN上對於這個函數的說明

主要看remarks裡面的實現步驟:

  1. Let n be the required derived key length, in bytes. The derived key is the first n bytes of the hash value after the hash computation has been completed by CryptDeriveKey. If the hash is not a member of the SHA-2 family and the required key is for either 3DES or AES, the key is derived as follows:
  2. 1.Form a 64-byte buffer by repeating the constant 0x36 64 times. Let k be the length of the hash value that is represented by the input parameter hBaseData. Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData.
  3. 2.Form a 64-byte buffer by repeating the constant 0x5C 64 times. Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData.
  4. 3.Hash the result of step 1 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter.
  5. 4.Hash the result of step 2 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter.
  6. 5.Concatenate the result of step 3 with the result of step 4.
  7. 6.Use the first n bytes of the result of step 5 as the derived key.

非常簡單的英文,不做翻譯了...

直接上openssl代碼實現

  1. //參見 http://msdn.microsoft.com/en-us/library/aa379916(v=vs.85).aspx remarks步驟
  2. unsigned char* derivedKey(unsigned char*sessionKey/*hash後的值*/,size_t n/*密鑰長度*/)
  3. {
  4. /**step 1*/
  5. unsigned char* buffer = (unsigned char*)malloc(64);
  6. for(int i = 0 ; i < 64;i++)
  7. {
  8. buffer[i] = 0x36;
  9. }
  10. int k = n;
  11. for(int i = 0 ; i < k ; i++)
  12. {
  13. buffer[i] = buffer[i] ^ sessionKey[i];
  14. }
  15. /*step 2*/
  16. unsigned char* buffer2 = (unsigned char*)malloc(64);
  17. for(int i = 0 ; i < 64;i++)
  18. {
  19. buffer2[i] = 0x5C;
  20. }
  21. for(int i = 0 ; i < k ; i++)
  22. {
  23. buffer2[i] = buffer2[i] ^ sessionKey[i];
  24. }
  25. /*step 3*/
  26. unsigned char* ret1 = openssl_md5(buffer,64);
  27. /*step 4*/
  28. unsigned char* ret2 = openssl_md5(buffer2,64);
  29. unsigned char* ret = (unsigned char*)malloc(128);
  30. for(int i = 0 ; i < 128;i++)
  31. {
  32. if(i<64)
  33. ret[i] = ret1[i];
  34. else
  35. ret[i] = ret2[i-64];
  36. }
  37. return ret;
  38. }
最麻煩的地方解決了...剩下再按照CryptoAPI的實現順序實現吧
  1. void openssl_aes_encrypt(string text,unsigned char** SessionKey_out/*這裡主要用作將產生的對稱密鑰輸出*/,unsigned char* sEncryptMsg,int &len)
  2. {
  3. OpenSSL_add_all_algorithms();
  4. //產生會話密鑰
  5. *SessionKey_out = (unsigned char*)malloc(MD5_SIZE);
  6. RAND_bytes(*SessionKey_out,MD5_SIZE);//產生隨機密鑰,輸出之後可以給其他方法是用了
  7. unsigned char* SessionKey = openssl_md5(*SessionKey_out,MD5_SIZE);
  8. SessionKey = derivedKey(SessionKey,MD5_SIZE);
  9. const unsigned char* sMsg = (const unsigned char*)text.c_str();
  10. int cbMsg = text.length();
  11. int cbEncryptMsg;
  12. //加密
  13. EVP_CIPHER_CTX ctx;
  14. EVP_CIPHER_CTX_init(&ctx);
  15. if(EVP_EncryptInit_ex(&ctx,EVP_get_cipherbynid(NID_aes_128_cbc),NULL,SessionKey,NULL))
  16. {
  17. int offseti=0;//in
  18. int offseto=0;//out
  19. int offsett=0;//temp
  20. for(;;)
  21. {
  22. if(cbMsg-offseti<=MAX_ENCRYPT_LEN)
  23. {
  24. EVP_EncryptUpdate(&ctx, sEncryptMsg+offseto, &offsett, sMsg+offseti, cbMsg-offseti);
  25. offseto+=offsett;
  26. break;
  27. }
  28. else
  29. {
  30. EVP_EncryptUpdate(&ctx, sEncryptMsg+offseto, &offsett, sMsg+offseti, MAX_ENCRYPT_LEN);
  31. offseti+=MAX_ENCRYPT_LEN;
  32. offseto+=offsett;
  33. }
  34. }
  35. EVP_EncryptFinal_ex(&ctx, sEncryptMsg+offseto, &offsett);
  36. offseto+=offsett;
  37. cbEncryptMsg=offseto;
  38. }
  39. EVP_CIPHER_CTX_cleanup(&ctx);
  40. std::cout << "openssl encrypt:" << std::endl;
  41. printBytes(sEncryptMsg,cbEncryptMsg);
  42. len = cbEncryptMsg;
  43. }
加密的搞定了,可以嘗試下了,同樣的密鑰和同樣的明文,密文輸出結果是一樣的就對了

下面是CrytpoAPI的解密:

  1. void cryptAPI_decrypt(unsigned char* text,int len,unsigned char* pwd)
  2. {
  3. HCRYPTPROV hCryptProv = NULL;
  4. HCRYPTKEY hKey = 0;
  5. HCRYPTHASH hHash = 0;
  6. int dwLength = 0;
  7. if(!CryptAcquireContext(&hCryptProv,
  8. NULL,
  9. CSP_NAME,//CSP_NAME
  10. PROV_RSA_AES,
  11. CRYPT_VERIFYCONTEXT))
  12. {
  13. DWORD dwLastErr = GetLastError();
  14. if(NTE_BAD_KEYSET == dwLastErr)
  15. {
  16. return;
  17. }
  18. else{
  19. if(!CryptAcquireContext(&hCryptProv,
  20. NULL,
  21. CSP_NAME,
  22. PROV_RSA_AES,
  23. CRYPT_NEWKEYSET))
  24. {
  25. return;
  26. }
  27. }
  28. }
  29. if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash))
  30. {
  31. return;
  32. }
  33. BYTE *pPwd = pwd;
  34. if(!CryptHashData(hHash, pPwd, 16, 0))
  35. {
  36. return;
  37. }
  38. if(!CryptDeriveKey(hCryptProv, CALG_AES_128, hHash, CRYPT_EXPORTABLE, &hKey))
  39. {
  40. return;
  41. }
  42. BYTE *pData = text;
  43. DWORD dwLen = len;
  44. if(!CryptDecrypt(hKey, NULL, true, 0, pData, &dwLen))
  45. {
  46. return;
  47. }
  48. cout <<"--------------------------" << endl << "cryptoAPI decrypt"<<endl;
  49. char* plainText = (char*)malloc(dwLen + 1);
  50. memcpy(plainText,pData,dwLen);
  51. plainText[dwLen] = '\0';
  52. cout << plainText << endl;
  53. CryptDestroyHash(hHash);
  54. CryptDestroyKey(hKey);
  55. CryptReleaseContext(hCryptProv,0);
  56. }
嘗試用這個方法解密CryptoAPI的加密和openssl的加密吧,都能輸出明文的

再來最後一個,openssl的解密

  1. void openssl_aes_decrypt(unsigned char* text,int len,unsigned char* SessionKeyP)
  2. {
  3. unsigned char* decryptMsg = (unsigned char*)malloc(len);
  4. OpenSSL_add_all_algorithms();
  5. unsigned char* SessionKey = openssl_md5(SessionKeyP,MD5_SIZE);
  6. SessionKey = derivedKey(SessionKey,MD5_SIZE);
  7. const unsigned char* sMsg = text;
  8. int cbMsg = len;
  9. int cbEncryptMsg;
  10. //解密
  11. EVP_CIPHER_CTX ctx;
  12. EVP_CIPHER_CTX_init(&ctx);
  13. if(EVP_DecryptInit_ex(&ctx,EVP_get_cipherbynid(NID_aes_128_cbc),NULL,SessionKey,NULL))
  14. {
  15. int offseti=0;//in
  16. int offseto=0;//out
  17. int offsett=0;//temp
  18. for(;;)
  19. {
  20. if(cbMsg-offseti<=MAX_ENCRYPT_LEN)
  21. {
  22. EVP_DecryptUpdate(&ctx, decryptMsg+offseto, &offsett, sMsg+offseti, cbMsg-offseti);
  23. offseto+=offsett;
  24. break;
  25. }
  26. else
  27. {
  28. EVP_DecryptUpdate(&ctx, decryptMsg+offseto, &offsett, sMsg+offseti, MAX_ENCRYPT_LEN);
  29. offseti+=MAX_ENCRYPT_LEN;
  30. offseto+=offsett;
  31. }
  32. }
  33. EVP_DecryptFinal_ex(&ctx, decryptMsg+offseto, &offsett);
  34. offseto+=offsett;
  35. cbEncryptMsg=offseto;
  36. }
  37. EVP_CIPHER_CTX_cleanup(&ctx);
  38. std::cout << "openssl decrypt:" << std::endl;
  39. char* ret = (char*)malloc(cbEncryptMsg + 1);
  40. memcpy(ret,decryptMsg,cbEncryptMsg);
  41. ret[cbEncryptMsg] = '\0';
  42. std::cout << ret << endl;
  43. }

測試下:

  1. int _tmain(int argc, _TCHAR* argv[])
  2. {
  3. string text = "texttexttexttexttext";
  4. unsigned char* key;
  5. unsigned char* sEncryptMsg = (unsigned char*)malloc(text.size() + MD5_SIZE);
  6. int len;
  7. openssl_aes_encrypt(text,&key,sEncryptMsg,len);
  8. unsigned char** sEncryptMsg_crypto = (unsigned char**)malloc(sizeof(unsigned char*));
  9. int len_crypto;
  10. cryptoAPI_encrypt(text,key,sEncryptMsg_crypto,len_crypto);
  11. cout << "-----------------------------" << endl<<"cryptoAPI decrypt openssl"<<endl;
  12. //cryptAPI_decrypt(sEncryptMsg,len,key);
  13. cout << "-----------------------------" << endl<<"cryptoAPI decrypt cryptoAPI"<<endl;
  14. //cryptAPI_decrypt(*sEncryptMsg_crypto,len_crypto,key);
  15. cout << "-----------------------------" << endl<<"oepnssl decrypt openssl"<<endl;
  16. //openssl_aes_decrypt(sEncryptMsg,len,key);
  17. cout << "-----------------------------" << endl<<"oepnssl decrypt cryptoAPI"<<endl;
  18. //openssl_aes_decrypt(*sEncryptMsg_crypto,len_crypto,key);
  19. return 0;
  20. }
Copyright © Linux教程網 All Rights Reserved