-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathopenssl_rsa.cpp
58 lines (40 loc) · 1.4 KB
/
openssl_rsa.cpp
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
#include <iostream>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include "openssl_rsa.h"
using namespace std;
RSA * create_RSA(RSA * keypair, int pem_type, char *file_name) {
RSA *rsa = NULL;
FILE *fp = NULL;
if(pem_type == PUBLIC_KEY_PEM) {
fp = fopen(file_name, "w");
PEM_write_RSAPublicKey(fp, keypair);
fclose(fp);
fp = fopen(file_name, "rb");
PEM_read_RSAPublicKey(fp, &rsa, NULL, NULL);
fclose(fp);
}
else if(pem_type == PRIVATE_KEY_PEM) {
fp = fopen(file_name, "w");
PEM_write_RSAPrivateKey(fp, keypair, NULL, NULL, NULL, NULL, NULL);
fclose(fp);
fp = fopen(file_name, "rb");
PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL);
fclose(fp);
}
return rsa;
}
int public_encrypt(int flen, unsigned char* from, unsigned char* to, RSA* key, int padding) {
int result = RSA_public_encrypt(flen, from, to, key, padding);
return result;
}
int private_decrypt(int flen, unsigned char* from, unsigned char* to, RSA* key, int padding) {
int result = RSA_private_decrypt(flen, from, to, key, padding);
return result;
}
void create_encrypted_file(char* encrypted, RSA* key_pair) {
FILE* encrypted_file = fopen("encrypted_file.bin", "w");
fwrite(encrypted, sizeof(*encrypted), RSA_size(key_pair), encrypted_file);
fclose(encrypted_file);
}