WHCSRL 技术网

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

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] = '';
	pub_key[pub_len] = '';
 
	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
", msg, err);
	free(err);
}
 
void RSA_test1(const char* cleartext)
{
	char* plainText = cleartext;
 
	//下面的公钥和私钥是通过命令行方式获取的
	char* publicKey = "-----BEGIN PUBLIC KEY-----
" 
		"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy8Dbv8prpJ/0kKhlGeJY
" 
		"ozo2t60EG8L0561g13R29LvMR5hyvGZlGJpmn65+A4xHXInJYiPuKzrKUnApeLZ+
" 
		"vw1HocOAZtWK0z3r26uA8kQYOKX9Qt/DbCdvsF9wF8gRK0ptx9M6R13NvBxvVQAp
" 
		"fc9jB9nTzphOgM4JiEYvlV8FLhg9yZovMYd6Wwf3aoXK891VQxTr/kQYoq1Yp+68
" 
		"i6T4nNq7NWC+UNVjQHxNQMQMzU6lWCX8zyg3yH88OAQkUXIXKfQ+NkvYQ1cxaMoV
" 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2wFpSfE7nNH2u4CpAXNSF9HsCgYEA2l8D
"
		"JrDE5m9Kkn+J4l+AdGfeBL1igPF3DnuPoV67BpgiaAgI4h25UJzXiDKKoa706S0D
"
		"4XB74zOLX11MaGPMIdhlG+SgeQfNoC5lE4ZWXNyESJH1SVgRGT9nBC2vtL6bxCVV
"
		"WBkTeC5D6c/QXcai6yw6OYyNNdp0uznKURe1xvMCgYBVYYcEjWqMuAvyferFGV+5
"
		"nWqr5gM+yJMFM2bEqupD/HHSLoeiMm2O8KIKvwSeRYzNohKTdZ7FwgZYxr8fGMoG
"
		"PxQ1VK9DxCvZL4tRpVaU5Rmknud9hg9DQG6xIbgIDR+f79sb8QjYWmcFGc1SyWOA
"
		"SkjlykZ2yt4xnqi3BfiD9QKBgGqLgRYXmXp1QoVIBRaWUi55nzHg1XbkWZqPXvz1
"
		"I3uMLv1jLjJlHk3euKqTPmC05HoApKwSHeA0/gOBmg404xyAYJTDcCidTg6hlF96
"
		"ZBja3xApZuxqM62F6dV4FQqzFX0WWhWp5n301N33r0qR6FumMKJzmVJ1TA8tmzEF
"
		"yINRAoGBAJqioYs8rK6eXzA8ywYLjqTLu/yQSLBn/4ta36K8DyCoLNlNxSuox+A5
"
		"w6z2vEfRVQDq4Hm4vBzjdi3QfYLNkTiTqLcvgWZ+eX44ogXtdTDO7c+GeMKWz4XX
"
		"uJSUVL5+CVjKLjZEJ6Qc2WZLl94xSwL71E41H4YciVnSCQxVc4Jw
"
		"-----END RSA PRIVATE KEY-----
";
 
	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] != '';i++)
    {
        printf("%%d",encrypted[i]);
    }

	printf("
Encrypted length =%%d
", 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
", decrypted);
	printf("Decrypted Length =%%d
", 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
", 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
", decrypted);
	printf("Decrypted Length =%%d
", decrypted_length);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184

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_
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

gcc编译

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

执行该命令的前提是下载并解压了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
", src);

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

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

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

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

   return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110

编译

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

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

推荐阅读