openssl pem金鑰檔案rsa加密解密例子
阿新 • • 發佈:2019-02-18
準備工作
命令列加密解密,用與比對程式碼中的演算法和命令列的演算法是否一致
C:\openssl_test>openssl rsautl -encrypt -in data.txt -inkey public.pem -pubin -out data.en
C:\openssl_test>openssl rsautl -decrypt -in data.en -inkey private.pem -out data.de
-pubin表示使用純公鑰加密
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/applink.c> #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") int main() { RSA *rsaKey; char fData[]="j23ur2jfsf-=20r034ujf"; char tData[128]; FILE *fp; fp = fopen("C:\\openssl_test\\public.pem", "r"); int strLen = strlen(fData); rsaKey = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL); int ret = RSA_public_encrypt(strLen, (unsigned char *)fData, (unsigned char*)tData, rsaKey, RSA_PKCS1_PADDING); //每次加密出來的tData都不一樣,因為填充了隨機數 RSA_free(rsaKey); fclose(fp); //此段程式碼使用者比對,校驗命令列的加密 //將結果寫入檔案,生成的檔案用命令列解密 //openssl rsautl -decrypt -in pdata.en -inkey private.pem -out pdata.de fp = fopen("C:\\openssl_test\\pdata.en", "wb"); fwrite(tData , ret, 1 , fp ); fclose(fp); fp = fopen("C:\\openssl_test\\private.pem", "r"); rsaKey = PEM_read_RSAPrivateKey(fp,NULL,NULL,NULL); ret = RSA_private_decrypt(128, (unsigned char *)tData, (unsigned char *)fData, rsaKey, RSA_PKCS1_PADDING); fclose(fp); //此段程式碼用於比對,校驗命令列的解密 //將命令列生成的加密檔案讀入記憶體,然後解密 //openssl rsautl -encrypt -in data.txt -inkey public.pem -pubin -out data.en fp = fopen("C:\\openssl_test\\data.en", "rb"); fread(tData , 128, 1 , fp ); ret = RSA_private_decrypt(128, (unsigned char *)tData, (unsigned char *)fData, rsaKey, RSA_PKCS1_PADDING); fclose(fp); RSA_free(rsaKey); return 0; }