繼上次只寫了 CryptoAPI 加密之後,這回把 OpenSSL 那一半補上。
動機:先前用 CryptoAPI 做出 Windows 上 IE、Firefox 與 Chrome 的加密控件,這次得加上與 Android 端的加密資訊往來。OpenSSL 移植到 Android 的過程之前提過,這裡不再重複;而當初提到的兩種「OpenSSL 與 CryptoAPI 相容」做法實測都不太好使,所以再提出一種 AES 的實作方式。
寫這篇最主要的原因在于:用過 CryptoAPI 的人都知道,它把太多細節都封裝好了,一旦要與其他加密組件對接,就得用另一套組件去「重現」CryptoAPI 的思維。
環境:Windows + Visual Studio 2010,OpenSSL for Windows(x86)動態庫。
CryptoAPI 做 AES 常見的做法,是先用 CryptCreateHash + CryptHashData 對傳入的金鑰做摘要,再由 CryptDeriveKey 導出最終金鑰。也就是說,OpenSSL 端必須照著走一遍同樣的兩步,密文才會一致。
CryptoAPI 加密(簡化版):
void cryptoAPI_encrypt(string text, unsigned char* pwd, unsigned char** encryptText, int& out_len)
{
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
if (!CryptAcquireContext(&hCryptProv, NULL, CSP_NAME, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
DWORD dwLastErr = GetLastError();
if (NTE_BAD_KEYSET == dwLastErr)
{
if (!CryptAcquireContext(&hCryptProv, NULL, CSP_NAME, PROV_RSA_AES, CRYPT_NEWKEYSET))
return;
}
else return;
}
if (!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) return;
BYTE *pPwd = pwd;
if (!CryptHashData(hHash, pPwd, 16, 0)) return; /* 先對金鑰做 MD5 */
if (!CryptDeriveKey(hCryptProv, CALG_AES_128, hHash, CRYPT_EXPORTABLE, &hKey)) return;
int len = text.length();
BYTE *pData = (BYTE*)malloc(len*4);
memcpy(pData, text.c_str(), len);
DWORD dwLen = len;
if (!CryptEncrypt(hKey, NULL, true, 0, pData, &dwLen, len*4)) return;
*encryptText = pData;
out_len = dwLen;
CryptDestroyHash(hHash);
CryptDestroyKey(hKey);
CryptReleaseContext(hCryptProv, 0);
}
unsigned char* openssl_md5(unsigned char* sessionKey, size_t n)
{
unsigned char *ret = (unsigned char*)malloc(MD5_DIGEST_LENGTH);
MD5(sessionKey, n, ret);
return ret;
}
真正的麻煩在 CryptDeriveKey。翻 MSDN 的 remarks 可以撿到它的完整步驟:以 0x36 填滿 64 位元組並與雜湊值前 k 位元組做 XOR;同樣方式用 0x5C 造第二個緩衝區;各自再雜湊一次;串接兩個結果;取前 n 位元組即為導出金鑰。照著實作:
/* 參見 MSDN CryptDeriveKey 的 remarks 步驟 */
unsigned char* derivedKey(unsigned char* sessionKey /* hash 後的值 */, size_t n /* 金鑰長度 */)
{
/* step 1 */
unsigned char* buffer = (unsigned char*)malloc(64);
for (int i = 0; i < 64; i++) buffer[i] = 0x36;
int k = n;
for (int i = 0; i < k; i++) buffer[i] = buffer[i] ^ sessionKey[i];
/* step 2 */
unsigned char* buffer2 = (unsigned char*)malloc(64);
for (int i = 0; i < 64; i++) buffer2[i] = 0x5C;
for (int i = 0; i < k; i++) buffer2[i] = buffer2[i] ^ sessionKey[i];
/* step 3、4 */
unsigned char* ret1 = openssl_md5(buffer, 64);
unsigned char* ret2 = openssl_md5(buffer2, 64);
/* step 5:串接 */
unsigned char* ret = (unsigned char*)malloc(128);
for (int i = 0; i < 128; i++)
ret[i] = (i < 64) ? ret1[i] : ret2[i-64];
/* step 6:取前 n 位元組即為 derived key */
return ret;
}
void openssl_aes_encrypt(string text, unsigned char** SessionKey_out,
unsigned char* sEncryptMsg, int& len)
{
OpenSSL_add_all_algorithms();
/* 產生會話金鑰,輸出後可交給其他模組使用 */
*SessionKey_out = (unsigned char*)malloc(MD5_SIZE);
RAND_bytes(*SessionKey_out, MD5_SIZE);
unsigned char* SessionKey = openssl_md5(*SessionKey_out, MD5_SIZE);
SessionKey = derivedKey(SessionKey, MD5_SIZE);
const unsigned char* sMsg = (const unsigned char*)text.c_str();
int cbMsg = text.length();
int cbEncryptMsg;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
if (EVP_EncryptInit_ex(&ctx, EVP_get_cipherbynid(NID_aes_128_cbc), NULL, SessionKey, NULL))
{
int offseti = 0; /* in */
int offseto = 0; /* out */
int offsett = 0; /* temp */
for (;;)
{
if (cbMsg - offseti <= MAX_ENCRYPT_LEN)
{
EVP_EncryptUpdate(&ctx, sEncryptMsg+offseto, &offsett, sMsg+offseti, cbMsg-offseti);
offseto += offsett;
break;
}
else
{
EVP_EncryptUpdate(&ctx, sEncryptMsg+offseto, &offsett, sMsg+offseti, MAX_ENCRYPT_LEN);
offseti += MAX_ENCRYPT_LEN;
offseto += offsett;
}
}
EVP_EncryptFinal_ex(&ctx, sEncryptMsg+offseto, &offsett);
offseto += offsett;
cbEncryptMsg = offseto;
}
EVP_CIPHER_CTX_cleanup(&ctx);
len = cbEncryptMsg;
}
這裡刻意用 EVP_get_cipherbynid(NID_aes_128_cbc) 搭配 NULL 的 IV,與 CryptoAPI 的預設行為對齊。若 IV 不一致,即使金鑰相同,密文也會完全不同。
CryptoAPI 解密與加密幾乎是鏡像,把 CryptEncrypt 換成 CryptDecrypt 即可:
void cryptAPI_decrypt(unsigned char* text, int len, unsigned char* pwd)
{
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
if (!CryptAcquireContext(&hCryptProv, NULL, CSP_NAME, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
if (NTE_BAD_KEYSET == GetLastError())
{
if (!CryptAcquireContext(&hCryptProv, NULL, CSP_NAME, PROV_RSA_AES, CRYPT_NEWKEYSET))
return;
}
else return;
}
if (!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) return;
BYTE *pPwd = pwd;
if (!CryptHashData(hHash, pPwd, 16, 0)) return;
if (!CryptDeriveKey(hCryptProv, CALG_AES_128, hHash, CRYPT_EXPORTABLE, &hKey)) return;
BYTE *pData = text;
DWORD dwLen = len;
if (!CryptDecrypt(hKey, NULL, true, 0, pData, &dwLen)) return;
char* plainText = (char*)malloc(dwLen + 1);
memcpy(plainText, pData, dwLen);
plainText[dwLen] = '\0';
cout << plainText << endl;
CryptDestroyHash(hHash);
CryptDestroyKey(hKey);
CryptReleaseContext(hCryptProv, 0);
}
OpenSSL 解密則是把加密流程中的 Init/Update/Final 換成 Decrypt 版本,金鑰推導邏輯完全不變:
void openssl_aes_decrypt(unsigned char* text, int len, unsigned char* SessionKeyP)
{
unsigned char* decryptMsg = (unsigned char*)malloc(len);
OpenSSL_add_all_algorithms();
unsigned char* SessionKey = openssl_md5(SessionKeyP, MD5_SIZE);
SessionKey = derivedKey(SessionKey, MD5_SIZE);
const unsigned char* sMsg = text;
int cbMsg = len;
int cbEncryptMsg;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
if (EVP_DecryptInit_ex(&ctx, EVP_get_cipherbynid(NID_aes_128_cbc), NULL, SessionKey, NULL))
{
int offseti = 0, offseto = 0, offsett = 0;
for (;;)
{
if (cbMsg - offseti <= MAX_ENCRYPT_LEN)
{
EVP_DecryptUpdate(&ctx, decryptMsg+offseto, &offsett, sMsg+offseti, cbMsg-offseti);
offseto += offsett;
break;
}
else
{
EVP_DecryptUpdate(&ctx, decryptMsg+offseto, &offsett, sMsg+offseti, MAX_ENCRYPT_LEN);
offseti += MAX_ENCRYPT_LEN;
offseto += offsett;
}
}
EVP_DecryptFinal_ex(&ctx, decryptMsg+offseto, &offsett);
offseto += offsett;
cbEncryptMsg = offseto;
}
EVP_CIPHER_CTX_cleanup(&ctx);
char* ret = (char*)malloc(cbEncryptMsg + 1);
memcpy(ret, decryptMsg, cbEncryptMsg);
ret[cbEncryptMsg] = '\0';
std::cout << ret << endl;
}
用同一組明文與金鑰分別跑 CryptoAPI 加密與 OpenSSL 加密,兩邊輸出的密文應該完全相同;再把密文丟給對方的解密函式,都能還原出原始明文,就代表互通成功。測試主程式大致如下:
int _tmain(int argc, _TCHAR* argv[])
{
string text = "texttexttexttexttext";
unsigned char* key;
unsigned char* sEncryptMsg = (unsigned char*)malloc(text.size() + MD5_SIZE);
int len;
openssl_aes_encrypt(text, &key, sEncryptMsg, len);
unsigned char** sEncryptMsg_crypto = (unsigned char**)malloc(sizeof(unsigned char*));
int len_crypto;
cryptoAPI_encrypt(text, key, sEncryptMsg_crypto, len_crypto);
/* cryptAPI_decrypt(sEncryptMsg, len, key); CryptoAPI 解 OpenSSL */
/* cryptAPI_decrypt(*sEncryptMsg_crypto, len_crypto, key); CryptoAPI 解 CryptoAPI */
/* openssl_aes_decrypt(sEncryptMsg, len, key); OpenSSL 解 OpenSSL */
/* openssl_aes_decrypt(*sEncryptMsg_crypto, len_crypto, key); OpenSSL 解 CryptoAPI */
return 0;
}
把四個解密呼叫逐一註解切換,四種組合都印出明文,就完成了跨平台的加密互通。剩下的例行工作(釋放 malloc 出來的記憶體、錯誤處理)就留給自己補上。