openssl pem密钥文件rsa加密解密例子

准备工作

命令行加密解密,用与比对代码中的算法和命令行的算法是否一致

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;   
}
 





posted on 2016-10-20 19:57  阮減显  阅读(738)  评论(0编辑  收藏  举报

导航