OpenSSL RSA加解密算法

在网上找了很多RSA算法的代码都是不完整或有问题的,只好自己写了。
其实很简单,PEM_read_bio_RSA_PUBKEY和PEM_read_bio_RSAPrivateKey这两个函数分别从内存中读取公钥和私钥,可以事先用openssl工具或在线工具生成。但要注意不能写错任何一个字符且每64个字符要加换行,否则会报错。
C代码如下:

#include "stdafx.h"
#include 
#include 
#include 

#pragma comment(lib,"libssl.lib")
#pragma comment(lib,"libcrypto.lib")

int main(void)
{
	char *in = "hello world";
	//BIO* bio = NULL;
	const char *pubKey = "-----BEGIN PUBLIC KEY-----\n\
		MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDpHxVLdv9g8PqGCYTe6Y6bv5tc\n\
		Lwwd5pBSZUWT9/iPArSYlOkQoYuhaYp2YkCIDfs6IQV2A4h2bMwrbRjF8Md7nbwx\n\
		Oy7w4xIsoC8XdyzOkjm78AhdcvFQQVevT+BBnMtvPrrkMTAfpJzt/zWNv1ufOpiy\n\
		v4AqyU6H24xFvyPfRQIDAQAB\
		\n----- END PUBLIC KEY-----\n";
	//此处大坑,END PUBLIC KEY前面的\n不能写在前一行的结尾,否则报错,不知道什么原因
	const char *priKey = "-----BEGIN RSA PRIVATE KEY-----\n\
		MIICXQIBAAKBgQDpHxVLdv9g8PqGCYTe6Y6bv5tcLwwd5pBSZUWT9/iPArSYlOkQ\n\
		oYuhaYp2YkCIDfs6IQV2A4h2bMwrbRjF8Md7nbwxOy7w4xIsoC8XdyzOkjm78Ahd\n\
		cvFQQVevT+BBnMtvPrrkMTAfpJzt/zWNv1ufOpiyv4AqyU6H24xFvyPfRQIDAQAB\n\
		AoGBAIeSVQ8DEDdvTTJgHM6KIy4+evpcPf6xlGLmlFUeE4YPu7k0eGn8mLhxKV35\n\
		e6/j+aNvir58BYNheEcU9iA/C7Ki/5rWX+ayrDUmHfV9hm0Lb3+2JLyTd6v4fwo4\n\
		pA/VEkED3OCgqFwlVeXa+VZ2Az/OnBrjm08HBrimq2h54DLhAkEA9Iea83K9XIca\n\
		fRSkLPmetoM+qgQT7VXYOpZznyytqeaf0Z3v7yDKeECBYo2H4B5Juw39dkKnvR1m\n\
		o1GKoF4RXQJBAPQOe7w7+cwENfS8biXvptd/arC5gOM+2NXh//xz0Xe7kyeswk0V\n\
		FWs3meJuC/Y9dnqec8/fMjN+dpaidWP3HwkCQQDzh539ONd4MCFkUstS82Nql3kw\n\
		L5F8+9K2PqJ18zQdkk62n5mWSMz8SBnTgerBfMinXz5/qdCOWpqeqpXqMuUNAkAG\n\
		53n8oz231c6o88Ox8wunQQWFplnNE/QSaOhS/fvJBVduYebFQ3ltpQ8HZtGTz71Q\n\
		Trc8BDZpWoSEUmg7wbvxAkAZRhiPNN1nV/Aja4D+/g5egtKzB6krSxhtREjp8pfL\n\
		m+h5JQKR79oj6OBX/ntdKV/RNxgCFyvnrQOCAlO7Q2vF\
		\n-----END RSA PRIVATE KEY-----\n";

	BIO* pubBio = BIO_new_mem_buf(pubKey, -1);
	RSA* pubRsa = PEM_read_bio_RSA_PUBKEY(pubBio, NULL, NULL, NULL);
	char *en[512] = { 0 };
	RSA_public_encrypt(strlen(in), (unsigned char*)in, (unsigned char*)en, pubRsa, RSA_PKCS1_PADDING);
	printf("加密:%s\n", en);

	BIO* priBIO = BIO_new_mem_buf(priKey, -1);
	RSA* priRsa = PEM_read_bio_RSAPrivateKey(priBIO, NULL, NULL, NULL);
	char de[512] = { 0 };
	RSA_private_decrypt(RSA_size(priRsa), (unsigned char*)en, (unsigned char*)de, priRsa, RSA_PKCS1_PADDING);
	printf("解密:%s", de);

	RSA_free(pubRsa);
	RSA_free(priRsa);

	getchar();
	return 0;
}

你可能感兴趣的:(OpenSSL RSA加解密算法)