OpenSSL成功Build出來安裝於系統後,在C:\usr\local\ssl路徑下會有bin、include、lib三個資料夾,裡面的檔案就是用來建立加密專案所需Lib與include的路徑,接下來就一步步教大家如何配置檔案至正確路徑,Build出加密App。
開啟VC6建立一新專案TestAES。
- 設定OpenSSL Lib、Include路徑 Tools -> Options -> Directories -> Show directories for: Include files
- 將C:\usr\local\ssl\bin或C:\openssl\out32dll下的libeay32.dll、ssleay32.dll複製到到C:\Windows\system32下。
- 將以下Linker加入專案擋頭。
- 編譯執行以下程式碼。
加入C:\usr\local\ssl\include
Tools -> Options -> Directories -> Show directories for: Library files
加入C:\usr\local\ssl\lib
#pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib")
#include <openssl/aes.h> #include <openssl/rand.h> #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") UCHAR CEKKey[AES_BLOCK_SIZE]; UCHAR IVKey[AES_BLOCK_SIZE]; void aes_create_key() { //CEK Key RAND_bytes(CEKKey, sizeof(CEKKey)); //IV key RAND_bytes(IVKey, sizeof(IVKey)); } BOOL aes_encrypt(char* source_string, UCHAR* des_string) { int nLen =0; AES_KEY aes; UCHAR key[AES_BLOCK_SIZE]; UCHAR iv[AES_BLOCK_SIZE]; memcpy(key, CEKKey, 16); memcpy(iv, IVKey, 16); if(NULL == source_string || NULL == des_string) return FALSE; if (AES_set_encrypt_key(key, 128, &aes) < 0) return FALSE; nLen = strlen(source_string)+1; AES_cbc_encrypt((UCHAR*)source_string, des_string, nLen, &aes, iv, AES_ENCRYPT); return TRUE; } BOOL aes_decrypt(char* source_string, UCHAR* des_string) { int nLen =0; AES_KEY aes; UCHAR key[AES_BLOCK_SIZE]; UCHAR iv[AES_BLOCK_SIZE]; memcpy(key, CEKKey, 16); memcpy(iv, IVKey, 16); if(NULL == source_string || NULL == des_string) return FALSE; if (AES_set_decrypt_key(key, 128, &aes) < 0) return FALSE; nLen = strlen(source_string)+1; AES_cbc_encrypt((UCHAR*)source_string, des_string, nLen, &aes, iv, AES_DECRYPT); return TRUE; } int main(int argc, TCHAR* argv[], TCHAR* envp[]) { CHAR cSource[] = {"Hello!AminWhite"}; UCHAR cDstStringTemp[16+1] = {0}; UCHAR ucDst[16+1] = {0}; aes_create_key(); aes_encrypt(cSource, cDstStringTemp); printf("Encrypt text : %s\n", cSource); printf("After Encrypt: %s\n", cDstStringTemp); aes_decrypt((CHAR*)cDstStringTemp, ucDst); printf("Decrypt text : %s\n", ucDst); return TRUE; }
沒有留言:
張貼留言