openssl 的RSA 非对称加密算法
使用测试2011-05-10 0:38 1 #include <openssl/rsa.h>
2 #include <openssl/pem.h>3 #include <unistd.h>
4 #include <iostream>
5
6 const char *g_pPubFile = "public.pem";
7 const char *g_pPriFile = "private.pem";
8
9 //maxCodeByte = g_nBits/8-11
10 const int g_nBits = 1024;
11
12 using namespace std;
13
14 int MakeKey()
15 {
16 if (access(g_pPubFile,0) == 0 && access(g_pPriFile,0) == 0)
17 {
18 return 0;
19 }
20 //生成key,这里设置了1024,意味着最多可以编解码1024/8-11=117个字节,
21 //RSA_F4为公钥指数,一般情况下使用RSA_F4即可,
22 //其它两个参数可以设置为NULL
23 RSA *pRsa = RSA_generate_key(g_nBits,RSA_F4,NULL,NULL);
24 if (pRsa == NULL)
25 {
26 cout << "rsa_generate_key error" << endl;
27 return -1;
28 }
29 BIO *pBio = BIO_new_file(g_pPubFile,"w");
30 if (pBio == NULL)
31 {
32 cout << "BIO_new_file " << g_pPubFile << " error" << endl;
33 return -2;
34 }
35 if(PEM_write_bio_RSAPublicKey(pBio,pRsa) == 0)
36 {
37 cout << "write public key error" << endl;
38 return -3;
39 }
40 BIO_free_all(pBio);
41 pBio = BIO_new_file(g_pPriFile,"w");
42 if (pBio == NULL)
43 {
44 cout << "BIO_new_file " << g_pPriFile << " error" << endl;
45 return -4;
46 }
47 if(PEM_write_bio_RSAPrivateKey(pBio,pRsa,NULL,NULL,0,NULL,NULL) == 0)
48 {
49 cout << "write private key error" << endl;
50 return -5;
51 }
52 BIO_free_all(pBio);
53 RSA_free(pRsa);
54 return 0;
55 }
56
57 int Enc(char *in, int inLen, char *out, int &outLen)
58 {
59 BIO *pBio = BIO_new_file(g_pPubFile,"r");
60 RSA *pRsa = PEM_read_bio_RSAPublicKey(pBio,NULL,NULL,NULL);
61 BIO_free_all(pBio);
62 outLen = RSA_public_encrypt(
63 (RSA_size(pRsa)-11)>inLen?inLen:RSA_size(pRsa)-11,
64 reinterpret_cast<unsigned char*>(in),
65 reinterpret_cast<unsigned char*>(out),
66 pRsa,
67 RSA_PKCS1_PADDING);
68 RSA_free(pRsa);
69 if(outLen >= 0)
70 return 0;
71 return -1;
72 }
73
74 int Dec(char *in, int inLen, char *out, int &outLen)
75 {
76 BIO *pBio = BIO_new_file(g_pPriFile,"r");
77 RSA *pRsa = PEM_read_bio_RSAPrivateKey(pBio,NULL,NULL,NULL);
78 BIO_free_all(pBio);
79 outLen = RSA_private_decrypt(
80 inLen,
81 reinterpret_cast<unsigned char*>(in),
82 reinterpret_cast<unsigned char*>(out),
83 pRsa,
84 RSA_PKCS1_PADDING);
85 RSA_free(pRsa);
86 if(outLen >= 0)
87 return 0;
88 return -1;
89 }
90
91 int main()
92 {
93 MakeKey();
94 char pOld[100]="for test";
95 char szEnc[1024] = {0};
96 int nEncLen = 0;
97 char szDec[1024] = {0};
98 int nDecLen = 0;
99 Enc(pOld,strlen(pOld),szEnc,nEncLen);
100 Dec(szEnc,nEncLen,szDec,nDecLen);
101 cout << "decode: " << szDec