1 //网上找的程序,可以运行!
2
3
4
5 //加密:
6
7 #include <openssl/rsa.h>
8 #include <openssl/err.h>
9 #include <string>
10 #include <iostream>
11 using namespace std;
12
13 #define MODULUS "C8FBCF21"
14 #define PUBLIC_EXPONENT RSA_F4
15 #define PRIVATE_EXPONENT "97B55D7D"
16
17 int main()
18 {
19 int ret, flen;
20 BIGNUM *bnn, *bne, *bnd;
21 unsigned char *in = (unsigned char*)"abc";
22 unsigned char *out;
23
24 bnn = BN_new();
25 bne = BN_new();
26 bnd = BN_new();
27 BN_hex2bn(&bnn, MODULUS);
28 BN_set_word(bne, PUBLIC_EXPONENT);
29 BN_hex2bn(&bnd, PRIVATE_EXPONENT);
30
31 RSA *r = RSA_new();
32 r->n = bnn;
33 r->e = bne;
34 r->d = bnd;
35 //ret = RSA_print_fp(stdout, r, 5);
36
37 flen = RSA_size(r);// - 11;
38
39 out = ( unsigned char *)malloc(flen);
40 //bzero(out, flen);
41 memset(out, 0, flen);
42
43
44 printf("Begin encrypt...\n");
45 ret = RSA_public_encrypt(flen,in,out,r,RSA_NO_PADDING);
46 if (ret < 0)
47 {
48 printf("Encrypt failed!\n");
49 return 1;
50 }
51
52 printf("Size:%d\n", ret);
53 printf("ClearText:%s\n", in);
54 printf("CipherText(Hex):\n");
55 int i;
56 for (i=0; i<ret; i++)
57 {
58 printf("0xx, ", *out);
59 out++;
60 }
61 printf("\n");
62
63 //free(out);
64
65 RSA_free(r);
66
67 cin.get();
68 return 0;
69 }
70
71
72
73 //解密:
74
75 #include <openssl/rsa.h>
76 #include <string>
77 #include <iostream>
78
79
80 using namespace std;
81
82
83 #define MODULUS "C8FBCF21"
84 #define PUBLIC_EXPONENT RSA_F4
85 #define PRIVATE_EXPONENT "97B55D7D"
86
87 int main()
88 {
89 int ret, flen;
90 BIGNUM *bnn, *bne;
91 unsigned char in[] = {0x98, 0x79, 0xb2, 0x76};
92 unsigned char *out;
93
94 bnn = BN_new();
95 bne = BN_new();
96 BN_hex2bn(&bnn, MODULUS);
97 BN_set_word(bne, PUBLIC_EXPONENT);
98
99 RSA *r = RSA_new();
100 r->n = bnn;
101 r->e = bne;
102 //RSA_print_fp(stdout, r, 5);
103
104 flen = RSA_size(r);
105 out = (unsigned char *)malloc(flen);
106 //bzero(out, flen);
107 memset(out, 0, flen);
108
109 printf("Begin decrypt...\n");
110 ret = RSA_public_decrypt(sizeof(in), in, out, r, RSA_NO_PADDING);
111 if (ret < 0)
112 {
113 printf("Decrypt failed!\n");
114 return 1;
115 }
116 printf("Size:%d\n", ret);
117 printf("ClearText:%s\n ", out);
118
119 free(out);
120 RSA_free(r);
121 cin.get();
122 return 0;
123 }