RSA 加密解密简单案列 Openssl 1.1.1 C语言实现

一、直接复制公钥私钥到代码里

代码

main.c

#include "crypto.h"

int main(int argc, char* argv[])
{
	char* cleartext = "123abc";
 
	if (sizeof(cleartext) > 256) {
        printf("cleartext too length!!!");
		return -1;
	}
 
	RSA_test1(cleartext);
	//RSA_test2(cleartext);
 
	printf("ok");
 
	return 0;
}

crypto.c

#include "crypto.h"

#define KEY_LENGTH  2048
int padding = RSA_PKCS1_PADDING;
int encrypt_len = 0;
#define PUB_EXP     3

int GenerateRSAKey(char* strKey[])
{
	size_t pri_len;          // Length of private key
	size_t pub_len;          // Length of public key      
 
	RSA* keypair = RSA_generate_key(KEY_LENGTH, RSA_3, NULL, NULL);
 
	BIO *pri = BIO_new(BIO_s_mem());
	BIO *pub = BIO_new(BIO_s_mem());
 
	PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
	PEM_write_bio_RSAPublicKey(pub, keypair);
 
	pri_len = BIO_pending(pri);
	pub_len = BIO_pending(pub);
 
    char pri_key[pri_len + 1];               // Private key
    char pub_key[pub_len + 1];              // Public key
 
	BIO_read(pri, pri_key, pri_len);
	BIO_read(pub, pub_key, pub_len);
 
	pri_key[pri_len] = '\0';
	pub_key[pub_len] = '\0';
 
	strKey[0] = pub_key;
	strKey[1] = pri_key;
 
	RSA_free(keypair);
	BIO_free_all(pub);
	BIO_free_all(pri);
 
	return 0;
}
 
RSA* createRSA(unsigned char* key, int flag)
{
	RSA *rsa= NULL;
	BIO *keybio ;
	keybio = BIO_new_mem_buf(key, -1);
 
	if (keybio==NULL) {
		printf( "Failed to create key BIO");
		return 0;
	}
 
	if(flag)
		rsa = PEM_read_bio_RSA_PUBKEY(keybio, &rsa, NULL, NULL);
	else
		rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);
 
	if(rsa == NULL)
		printf( "Failed to create RSA");
 
	return rsa;
}
 
int public_encrypt(unsigned char* data, int data_len, unsigned char* key, unsigned char* encrypted)
{
	RSA * rsa = createRSA(key, 1);
	int result = RSA_public_encrypt(data_len, data, encrypted, rsa, padding);
	return result;
}
 
int private_decrypt(unsigned char* enc_data, int data_len, unsigned char* key, unsigned char* decrypted)
{
	RSA * rsa = createRSA(key, 0);
	int  result = RSA_private_decrypt(data_len,enc_data,decrypted,rsa,padding);
	return result;
}
 
int private_encrypt(unsigned char* data, int data_len, unsigned char* key, unsigned char* encrypted)
{
	RSA * rsa = createRSA(key, 0);
	int result = RSA_private_encrypt(data_len, data, encrypted, rsa, padding);
	return result;
}
 
int public_decrypt(unsigned char* enc_data, int data_len, unsigned char* key, unsigned char* decrypted)
{
	RSA * rsa = createRSA(key, 1);
	int  result = RSA_public_decrypt(data_len, enc_data, decrypted, rsa, padding);
	return result;
}
 
void printLastError(char *msg)
{
	char * err = (char*)malloc(130);;
	ERR_load_crypto_strings();
	ERR_error_string(ERR_get_error(), err);
	printf("%s ERROR: %s\n", msg, err);
	free(err);
}
 
void RSA_test1(const char* cleartext)
{
	char* plainText = cleartext;
 
	//下面的公钥和私钥是通过命令行方式获取的
	char* publicKey = "-----BEGIN PUBLIC KEY-----\n" \
		"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy8Dbv8prpJ/0kKhlGeJY\n" \
		"ozo2t60EG8L0561g13R29LvMR5hyvGZlGJpmn65+A4xHXInJYiPuKzrKUnApeLZ+\n" \
		"vw1HocOAZtWK0z3r26uA8kQYOKX9Qt/DbCdvsF9wF8gRK0ptx9M6R13NvBxvVQAp\n" \
		"fc9jB9nTzphOgM4JiEYvlV8FLhg9yZovMYd6Wwf3aoXK891VQxTr/kQYoq1Yp+68\n" \
		"i6T4nNq7NWC+UNVjQHxNQMQMzU6lWCX8zyg3yH88OAQkUXIXKfQ+NkvYQ1cxaMoV\n" \
		"PpY72+eVthKzpMeyHkBn7ciumk5qgLTEJAfWZpe4f4eFZj/Rc8Y8Jj2IS5kVPjUy\n" \
		"wQIDAQAB\n" \
		"-----END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BL1igPF3DnuPoV67BpgiaAgI4h25UJzXiDKKoa706S0D\n"\
		"4XB74zOLX11MaGPMIdhlG+SgeQfNoC5lE4ZWXNyESJH1SVgRGT9nBC2vtL6bxCVV\n"\
		"WBkTeC5D6c/QXcai6yw6OYyNNdp0uznKURe1xvMCgYBVYYcEjWqMuAvyferFGV+5\n"\
		"nWqr5gM+yJMFM2bEqupD/HHSLoeiMm2O8KIKvwSeRYzNohKTdZ7FwgZYxr8fGMoG\n"\
		"PxQ1VK9DxCvZL4tRpVaU5Rmknud9hg9DQG6xIbgIDR+f79sb8QjYWmcFGc1SyWOA\n"\
		"SkjlykZ2yt4xnqi3BfiD9QKBgGqLgRYXmXp1QoVIBRaWUi55nzHg1XbkWZqPXvz1\n"\
		"I3uMLv1jLjJlHk3euKqTPmC05HoApKwSHeA0/gOBmg404xyAYJTDcCidTg6hlF96\n"\
		"ZBja3xApZuxqM62F6dV4FQqzFX0WWhWp5n301N33r0qR6FumMKJzmVJ1TA8tmzEF\n"\
		"yINRAoGBAJqioYs8rK6eXzA8ywYLjqTLu/yQSLBn/4ta36K8DyCoLNlNxSuox+A5\n"\
		"w6z2vEfRVQDq4Hm4vBzjdi3QfYLNkTiTqLcvgWZ+eX44ogXtdTDO7c+GeMKWz4XX\n"\
		"uJSUVL5+CVjKLjZEJ6Qc2WZLl94xSwL71E41H4YciVnSCQxVc4Jw\n"\
		"-----END RSA PRIVATE KEY-----\n";
 
	unsigned char  encrypted[4098] = {};
	unsigned char decrypted[4098] = {};
 
	int encrypted_length= public_encrypt((unsigned char*)plainText,sizeof(plainText), (unsigned char*)publicKey, encrypted);
	if (encrypted_length == -1) {
		printLastError("Public Encrypt failed ");
		exit(0);
	}

    char res[4098] = {0};
    for(int i = 0;i < 4098 && encrypted[i] != '\0';i++)
    {
        printf("%d",encrypted[i]);
    }

	printf("\nEncrypted length =%d\n", encrypted_length);
 
	int decrypted_length = private_decrypt(encrypted, encrypted_length, (unsigned char*)privateKey, decrypted);
	if (decrypted_length == -1) {
		printLastError("Private Decrypt failed ");
		exit(0);
	}
	printf("Decrypted Text =%s\n", decrypted);
	printf("Decrypted Length =%d\n", decrypted_length);
 
	encrypted_length= private_encrypt((unsigned char*)plainText, sizeof(plainText),(unsigned char*)privateKey, encrypted);
	if(encrypted_length == -1) {
		printLastError("Private Encrypt failed");
		exit(0);
	}
	printf("Encrypted length =%d\n", encrypted_length);
 
	decrypted_length = public_decrypt(encrypted, encrypted_length, (unsigned char*)publicKey, decrypted);
	if(decrypted_length == -1) {
		printLastError("Public Decrypt failed");
		exit(0);
	}
	printf("Decrypted Text =%s\n", decrypted);
	printf("Decrypted Length =%d\n", decrypted_length);
}

crypto.h

#ifndef _CRYPTOTEST_H_
#define _CRYPTOTEST_H_
 
#include <string.h>
#include <stdio.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
 
typedef enum {
	GENERAL = 0,
	ECB,
	CBC,
	CFB,
	OFB,
	TRIPLE_ECB,
	TRIPLE_CBC
}CRYPTO_MODE;
 
int GenerateRSAKey(char* strKey[]);

void RSA_test1(const char* cleartext);
 
#endif //_CRYPTOTEST_H_

gcc编译

gcc main.c crypto.c -o main.out -std=c99 -L /home/openssl-1.1.1l -l ssl -l crypto

执行该命令的前提是下载并解压了openssl资源包,可参考下面的教程
openssl的编译和使用

运行结果

在这里插入图片描述

二、读取pem文件后加密解密

代码

encry.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<openssl/rsa.h>
#include<openssl/pem.h>
#include<openssl/err.h>

#define PRIKEY "private_key.pem"
#define PUBKEY "public_key.pem"
#define BUFFSIZE 4096

/************************************************************************
* RSA加密解密函数
*
* file: test_rsa_encdec.c
* gcc -Wall -O2 -o test_rsa_encdec test_rsa_encdec.c -lcrypto -lssl
*
* author: tonglulin@gmail.com by www.qmailer.net
************************************************************************/

char*my_encrypt(char*str,char*pubkey_path)
{
   RSA *rsa = NULL;
   FILE*fp = NULL;
   char*en = NULL;
   int len = 0;
   int rsa_len = 0;

   if((fp = fopen(pubkey_path,"r")) == NULL) {
       return NULL;
   }

   /* 读取公钥PEM,PUBKEY格式PEM使用PEM_read_RSA_PUBKEY函数 */
   if((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) == NULL) {
       return NULL;
   }

   RSA_print_fp(stdout, rsa, 0);

   len = strlen(str);
   rsa_len = RSA_size(rsa);

   en = (char*)malloc(rsa_len + 1);
   memset(en, 0, rsa_len + 1);

   if(RSA_public_encrypt(rsa_len, (unsigned char*)str, (unsigned char*)en, rsa, RSA_NO_PADDING) < 0) {
       return NULL;
   }

   RSA_free(rsa);
   fclose(fp);

   return en;
}

char*my_decrypt(char*str,char*prikey_path)
{
   RSA *rsa = NULL;
   FILE*fp = NULL;
   char*de = NULL;
   int rsa_len = 0;

   if((fp = fopen(prikey_path,"r")) == NULL) {
       return NULL;
   }

   if((rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) {
       return NULL;
   }

   RSA_print_fp(stdout, rsa, 0);

   rsa_len = RSA_size(rsa);
   de = (char*)malloc(rsa_len + 1);
   memset(de, 0, rsa_len + 1);

   if(RSA_private_decrypt(rsa_len, (unsigned char*)str, (unsigned char*)de, rsa, RSA_NO_PADDING) < 0) {
       return NULL;
   }

   RSA_free(rsa);
   fclose(fp);

   return de;
}

int main(int argc,char*argv[])
{
   char*src = "hello, world!";
   char*en = NULL;
   char*de = NULL;

   printf("src is: %s\n", src);

   en = my_encrypt(src, PUBKEY);
   printf("enc is: %s\n", en);

   de= my_decrypt(en, PRIKEY);
   printf("dec is: %s\n", de);

   if(en != NULL) {
       free(en);
   }

   if(de != NULL) {
       free(de);
   }

   return 0;
}

编译

gcc encry.c -o encry.out -std=c99 -L /home/openssl-1.1.1l -l ssl -l crypto

执行这个命令需要两个pem文件,路径在代码中指出了,生成pem文件的命令可参考:
openssl生成pem格式公私钥文件

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值