软件加密-RSA(openSSL)的应用

RSA算法,在1977年由Ron Rivest、Adi Shamirh和LenAdleman,在美国的麻省理工学院开发完成。这个算法的名字,来源于三位开发者的名字。RSA已经成为公钥数据加密标准。

RSA属于公开密钥密码体制。公开密钥体制就是产生两把密钥,一把用于加密,一把用于解密,而且不能根据算法和其中的一把密钥,而去推出另外的一把密钥。在使用的时候,将公钥公开,对方用公开的公钥加密数据后,将密文发回,然后用另一把私钥进行解密,从而还原出明文。

RSA算法的数学基础是数论中的素数相关性质。RSA的算法如下:

(1)、找出两个数p和q,其中p与q都是比较大的素数,其中p不等于q,为了保证安全性,RSA中使用的素数都比较大,且对这两个数要进行严格的保密;

(2)、计算乘积n = p *q;

(3)、计算乘积f(p,q) =(p - 1) * (q - 1);

(4)、找到一个素数e,使1 < e< f(p,q),并且e与f(p,q)互素;

(5)、将(e, n)做公钥,对明文按公式C=p^e mod n进行加密;

(6)、计算私钥d=e^-1mod f(p,q);对密文按P = C^d mod n进行解密。

其中,e,n作为公钥公开,任何人都可以知道。而f(p,q)作为密钥,要进行保密。一旦f(p,q)被别人获取,那么该RSA算法就不再安全。并且RSA算法的安全性和p,q的长度直接相关,长度越长安全性越高。因此,实际应用中p,q的长度至少为512比特。具体实现原理如图1所示。


图 1

RSA在加解密的运用中,公钥是公开的,即有很多人都能得到,第三方也很容易窃取到e和n的数值。所以破解的关键就在,从e和n这两个数值开始,想办法求出数值d,如果能够得到d的值,也就是能够找到私钥,那么就可以破解相应的信息,达到情报窃取的目的。RSA算法的安全性完全依赖于大数的分解。

         优缺点:由于RSA算法的理论基础是大数的分集,它是公认的世界难题,这就为RSA的安全性作了保障,所以它在一定程度上能抵抗外界的各种攻击。RSA是公钥加密系统中使用最广的加密算法,也是第一个既可以用于数据加密,同时还可以用于数字签名的算法。它的缺点:由于没有直接产生大素数的技术,RSA算法密钥产生比较麻烦;其次,为保证安全性,n一般要达到1024bit,使加密解密运算代价很高,严重影响了其加密速度,因此RSA算法不适合用于加密数据量大的信息;随着保密级别的提高,密钥的长度也在随着增加。

RSA is vulnerable to timing attacks. In a setup where attackers can measure the timeof RSA decryption or signature operations, blinding must be used to protect theRSA operation from that attack. RSA_blinding_on(),RSA_blinding_off():protectthe RSA operation from timing attacks.

1.      RSA_blinding_on():turnsblinding on for key B<rsa> and generates a random blinding factor.B<ctx> is B<NULL> or a pre-allocated and initializedB<BN_CTX>. The random number generator must be seeded prior to callingRSA_blinding_on().returns 1 on success, and 0 if an error occurred.

2.      RSA_blinding_off():turnsblinding off and frees the memory used for the blinding factor.

3.      RSA_check_key():validateprivate RSA keys. This function validates RSA keys. It checks that B<p>and B<q> are in fact prime, and that B<n = p*q>. It also checksthat B<d*e = 1 mod (p-1*q-1)>, and that B<dmp1>, B<dmq1> andB<iqmp> are set correctly or are B<NULL>. As such, this functioncan not be used with any arbitrary RSA key object, even if it is otherwise fitfor regular RSA operation. returns 1 if B<rsa> is a valid RSA key, and 0otherwise. -1 is returned if an error occurs while checking the key. Thisfunction does not work on RSA public keys that have only the modulus and publicexponent elements populated. It performs integrity checks on all the RSA keymaterial, so the RSA key structure must contain all the private key data too.

4.      RSA_generate_key():generates akey pair and returns it in a newly allocated B<RSA> structure. Thepseudo-random number generator must be seeded prior to callingRSA_generate_key().The modulus size will be B<num> bits, and the publicexponent will be B<e>. Key sizes with B<num> E<lt> 1024should be considered insecure. The exponent is an odd number, typically 3, 17or 65537. A callback function may be used to provide feedback about the progressof the key generation. If key generation fails, RSA_generate_key() returnsB<NULL>. RSA_generate_key() goes into an infinite loop for illegal inputvalues.

5.      RSA_set_ex_data():is used toset application specific data, the data is supplied in the B<arg>parameter and its precise meaning is up to the application. returns 1 onsuccess or 0 on failure.

6.      RSA_get_ex_data():is used toretrieve application specific data. The data is returned to the application,this will be the same value as supplied to a previousB<RSA_set_ex_data()> call. returns the application data or 0 on failure.0 may also be valid application data but currently it can only fail if given aninvalid B<idx> parameter.

7.      RSA_get_ex_new_index():returnsa new index or -1 on failure (note 0 is a valid index value).

8.      RSA_new():allocate RSA objects.allocates and initializes an B<RSA> structure. It is equivalent to callingRSA_new_method(NULL).

9.      RSA_free():free RSA objects. freesthe B<RSA> structure and its components. The key is erased before thememory is returned to the system.

10.  RSA_padding_xxx_xxx(): these functionsare called from the RSA encrypt, decrypt, sign and verify functions. Normallythey should not be called from application programs. However, they can also becalled directly to implement padding for other asymmetric ciphers.

11.  RSA_private_encrypt():owlevel signature operations. signs the B<flen> bytes atB<from> (usually a message digest with an algorithm identifier) using theprivate key B<rsa> and stores the signature in B<to>. B<to>must point to B<RSA_size(rsa)> bytes of memory. returns the size of thesignature (i.e.,RSA_size(rsa)).

12.  RSA_public_decrypt():ow levelsignature operations. recovers the message digest from the B<flen> byteslong signature at B<from> using the signer's public key B<rsa>.B<to> must point to a memory section large enough to hold the messagedigest (which is smaller than B<RSA_size(rsa) - 11>). B<padding> isthe padding mode that was used to sign the data. returns the size of the recoveredmessage digest.

13.  RSA_public_encrypt():encryptsthe B<flen> bytes at B<from> (usually a session key) using thepublic key B<rsa> and stores the ciphertext in B<to>. B<to>must point to RSA_size(B<rsa>) bytes of memory. returns the size of theencrypted data (i.e., RSA_size(B<rsa>)).

14.  RSA_private_decrypt():decryptsthe B<flen> bytes at B<from> using the private key B<rsa> andstores the plaintext in B<to>. B<to> must point to a memory sectionlarge enough to hold the decrypted data (which is smaller thanRSA_size(B<rsa>)). B<padding> is the padding mode that was used toencrypt the data. returns the size of the recovered plaintext.

15.  RSA_set_default_method():makesB<meth> the default method for all RSA structures created later.B<NB>: This is true only whilst no ENGINE has been set as a default forRSA, so this function is no longer recommended.

16.  RSA_get_default_method():returnsa pointer to the current default RSA_METHOD. However, the meaningfulness ofthis result is dependent on whether the ENGINE API is being used, so thisfunction is no longer recommended.

17.  RSA_set_method():selectsB<meth> to perform all operations using the key B<rsa>. This willreplace the RSA_METHOD used by the RSA key and if the previous method wassupplied by an ENGINE, the handle to that ENGINE will be released during thechange. It is possible to have RSA keys that only work with certain RSA_METHODimplementations (eg. from an ENGINE module that supports embeddedhardware-protected keys), and in such cases attempting to change the RSA_METHODfor the key can have unexpected results.

18.  RSA_get_method():returns apointer to the RSA_METHOD being used by B<rsa>. This method may or maynot be supplied by an ENGINE implementation, but if it is, the return value canonly be guaranteed to be valid as long as the RSA key itself is valid and doesnot have its implementation changed by RSA_set_method().

19.  RSA_flags():returns theB<flags> that are set for B<rsa>'s current RSA_METHOD.

20.  RSA_new_method():allocates andinitializes an RSA structure so that B<engine> will be used for the RSAoperations. If B<engine> is NULL, the default ENGINE for RSA operationsis used, and if no default ENGINE is set, the RSA_METHOD controlled byRSA_set_default_method() is used.

21.  RSA_sign():signs the messagedigest B<m> of size B<m_len> using the private key B<rsa> asspecified in PKCS #1 v2.0. It stores the signature in B<sigret> and thesignature size in B<siglen>. B<sigret> must point to RSA_size(B<rsa>)bytes of memory.

22.  RSA_verify():verifies that thesignature B<sigbuf> of size B<siglen> matches a given messagedigest B<m> of size B<m_len>. B<type> denotes the messagedigest algorithm that was used to generate the signature. B<rsa> is thesigner's public key.

23.  RSA_sign_ASN1_OCTET_STRING():signsthe octet string B<m> of size B<m_len> using the private keyB<rsa> represented in DER using PKCS #1 padding. It stores the signaturein B<sigret> and the signature size in B<siglen>. B<sigret>must point to B<RSA_size(rsa)> bytes of memory.

24.  RSA_verify_ASN1_OCTET_STRING():verifiesthat the signature B<sigbuf> of size B<siglen> is the DERrepresentation of a given octet string B<m> of size B<m_len>.B<dummy> is ignored. B<rsa> is the signer's public key.

25. RSA_size():getRSA modulus size. This function returns the RSA modulus size in bytes. It canbe used to determine how much memory must be allocated for an RSA encrypted value.

下面是测试用例代码:

1. cryptotest.h:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #ifndef _CRYPTOTEST_H_  
  2. #define _CRYPTOTEST_H_  
  3.   
  4. #include <string>  
  5.   
  6. using namespace std;  
  7.   
  8. typedef enum {  
  9.     GENERAL = 0,  
  10.     ECB,  
  11.     CBC,  
  12.     CFB,  
  13.     OFB,  
  14.     TRIPLE_ECB,  
  15.     TRIPLE_CBC  
  16. }CRYPTO_MODE;  
  17.   
  18. string DES_Encrypt(const string cleartext, const string key, CRYPTO_MODE mode);  
  19. string DES_Decrypt(const string ciphertext, const string key, CRYPTO_MODE mode);  
  20.   
  21. string RC4_Encrypt(const string cleartext, const string key);  
  22. string RC4_Decrypt(const string ciphertext, const string key);  
  23.   
  24. string MD5_Digest(const string cleartext);  
  25.   
  26. int GenerateRSAKey(string strKey[]);  
  27. //string RSA_Encrypt(string cleartext, string key);  
  28. //string RSA_Decrypt(string ciphertext, string key);  
  29. void RSA_test1(const string cleartext);  
  30. void RSA_test2(const string cleartext);  
  31.   
  32. #endif //_CRYPTOTEST_H_  
2. rsatest.cpp:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include "stdafx.h"  
  2. #include "cryptotest.h"  
  3. #include "openssl/err.h"  
  4. #include <iostream>  
  5.   
  6. using namespace std;  
  7.   
  8. #define KEY_LENGTH  2048  
  9. int padding = RSA_PKCS1_PADDING;  
  10. int encrypt_len = 0;  
  11. #define PUB_EXP     3  
  12. //#define PRINT_KEYS  
  13. //#define WRITE_TO_FILE  
  14.   
  15. int GenerateRSAKey(string strKey[])  
  16. {  
  17.     size_t pri_len;          // Length of private key  
  18.     size_t pub_len;          // Length of public key  
  19.     char *pri_key = NULL;           // Private key  
  20.     char *pub_key = NULL;           // Public key  
  21.   
  22.     RSA* keypair = RSA_generate_key(KEY_LENGTH, RSA_3, NULL, NULL);  
  23.   
  24.     BIO *pri = BIO_new(BIO_s_mem());  
  25.     BIO *pub = BIO_new(BIO_s_mem());  
  26.   
  27.     PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);  
  28.     PEM_write_bio_RSAPublicKey(pub, keypair);  
  29.   
  30.     pri_len = BIO_pending(pri);  
  31.     pub_len = BIO_pending(pub);  
  32.   
  33.     pri_key = new char[pri_len + 1];  
  34.     pub_key = new char[pub_len + 1];  
  35.   
  36.     BIO_read(pri, pri_key, pri_len);  
  37.     BIO_read(pub, pub_key, pub_len);  
  38.   
  39.     pri_key[pri_len] = '\0';  
  40.     pub_key[pub_len] = '\0';  
  41.   
  42.     strKey[0] = pub_key;  
  43.     strKey[1] = pri_key;  
  44.   
  45.     //printf("\n%s\n%s\n", pri_key, pub_key);  
  46.   
  47.     RSA_free(keypair);  
  48.     BIO_free_all(pub);  
  49.     BIO_free_all(pri);  
  50.     delete [] pri_key;  
  51.     delete [] pub_key;  
  52.   
  53.     return 0;  
  54. }  
  55.   
  56. RSA* createRSA(unsigned char* key, int flag)  
  57. {  
  58.     RSA *rsa= NULL;  
  59.     BIO *keybio ;  
  60.     keybio = BIO_new_mem_buf(key, -1);  
  61.   
  62.     if (keybio==NULL) {  
  63.         printf( "Failed to create key BIO");  
  64.         return 0;  
  65.     }  
  66.   
  67.     if(flag)  
  68.         rsa = PEM_read_bio_RSA_PUBKEY(keybio, &rsa, NULL, NULL);  
  69.     else  
  70.         rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);  
  71.   
  72.     if(rsa == NULL)  
  73.         printf( "Failed to create RSA");  
  74.   
  75.     return rsa;  
  76. }  
  77.   
  78. int public_encrypt(unsigned char* data, int data_len, unsigned char* key, unsigned char* encrypted)  
  79. {  
  80.     RSA * rsa = createRSA(key, 1);  
  81.     int result = RSA_public_encrypt(data_len, data, encrypted, rsa, padding);  
  82.     return result;  
  83. }  
  84.   
  85. int private_decrypt(unsigned char* enc_data, int data_len, unsigned char* key, unsigned char* decrypted)  
  86. {  
  87.     RSA * rsa = createRSA(key, 0);  
  88.     int  result = RSA_private_decrypt(data_len,enc_data,decrypted,rsa,padding);  
  89.     return result;  
  90. }  
  91.   
  92. int private_encrypt(unsigned char* data, int data_len, unsigned char* key, unsigned char* encrypted)  
  93. {  
  94.     RSA * rsa = createRSA(key, 0);  
  95.     int result = RSA_private_encrypt(data_len, data, encrypted, rsa, padding);  
  96.     return result;  
  97. }  
  98.   
  99. int public_decrypt(unsigned char* enc_data, int data_len, unsigned char* key, unsigned char* decrypted)  
  100. {  
  101.     RSA * rsa = createRSA(key, 1);  
  102.     int  result = RSA_public_decrypt(data_len, enc_data, decrypted, rsa, padding);  
  103.     return result;  
  104. }  
  105.   
  106. void printLastError(char *msg)  
  107. {  
  108.     char * err = (char*)malloc(130);;  
  109.     ERR_load_crypto_strings();  
  110.     ERR_error_string(ERR_get_error(), err);  
  111.     printf("%s ERROR: %s\n", msg, err);  
  112.     free(err);  
  113. }  
  114.   
  115. void RSA_test1(const string cleartext)  
  116. {  
  117.     //char plainText[2048/8] = "Hello this is Ravi"; //key length : 2048  
  118.     string plainText = cleartext;  
  119.   
  120.     //下面的公钥和私钥是通过命令行方式获取的  
  121.     //char publicKey[]="-----BEGIN PUBLIC KEY-----\n"  
  122.     string publicKey = "-----BEGIN PUBLIC KEY-----\n" \  
  123.         "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy8Dbv8prpJ/0kKhlGeJY\n" \  
  124.         "ozo2t60EG8L0561g13R29LvMR5hyvGZlGJpmn65+A4xHXInJYiPuKzrKUnApeLZ+\n" \  
  125.         "vw1HocOAZtWK0z3r26uA8kQYOKX9Qt/DbCdvsF9wF8gRK0ptx9M6R13NvBxvVQAp\n" \  
  126.         "fc9jB9nTzphOgM4JiEYvlV8FLhg9yZovMYd6Wwf3aoXK891VQxTr/kQYoq1Yp+68\n" \  
  127.         "i6T4nNq7NWC+UNVjQHxNQMQMzU6lWCX8zyg3yH88OAQkUXIXKfQ+NkvYQ1cxaMoV\n" \  
  128.         "PpY72+eVthKzpMeyHkBn7ciumk5qgLTEJAfWZpe4f4eFZj/Rc8Y8Jj2IS5kVPjUy\n" \  
  129.         "wQIDAQAB\n" \  
  130.         "-----END PUBLIC KEY-----\n";  
  131.   
  132.     //char privateKey[]="-----BEGIN RSA PRIVATE KEY-----\n"  
  133.     string privateKey = "-----BEGIN RSA PRIVATE KEY-----\n"\  
  134.         "MIIEowIBAAKCAQEAy8Dbv8prpJ/0kKhlGeJYozo2t60EG8L0561g13R29LvMR5hy\n"\  
  135.         "vGZlGJpmn65+A4xHXInJYiPuKzrKUnApeLZ+vw1HocOAZtWK0z3r26uA8kQYOKX9\n"\  
  136.         "Qt/DbCdvsF9wF8gRK0ptx9M6R13NvBxvVQApfc9jB9nTzphOgM4JiEYvlV8FLhg9\n"\  
  137.         "yZovMYd6Wwf3aoXK891VQxTr/kQYoq1Yp+68i6T4nNq7NWC+UNVjQHxNQMQMzU6l\n"\  
  138.         "WCX8zyg3yH88OAQkUXIXKfQ+NkvYQ1cxaMoVPpY72+eVthKzpMeyHkBn7ciumk5q\n"\  
  139.         "gLTEJAfWZpe4f4eFZj/Rc8Y8Jj2IS5kVPjUywQIDAQABAoIBADhg1u1Mv1hAAlX8\n"\  
  140.         "omz1Gn2f4AAW2aos2cM5UDCNw1SYmj+9SRIkaxjRsE/C4o9sw1oxrg1/z6kajV0e\n"\  
  141.         "N/t008FdlVKHXAIYWF93JMoVvIpMmT8jft6AN/y3NMpivgt2inmmEJZYNioFJKZG\n"\  
  142.         "X+/vKYvsVISZm2fw8NfnKvAQK55yu+GRWBZGOeS9K+LbYvOwcrjKhHz66m4bedKd\n"\  
  143.         "gVAix6NE5iwmjNXktSQlJMCjbtdNXg/xo1/G4kG2p/MO1HLcKfe1N5FgBiXj3Qjl\n"\  
  144.         "vgvjJZkh1as2KTgaPOBqZaP03738VnYg23ISyvfT/teArVGtxrmFP7939EvJFKpF\n"\  
  145.         "1wTxuDkCgYEA7t0DR37zt+dEJy+5vm7zSmN97VenwQJFWMiulkHGa0yU3lLasxxu\n"\  
  146.         "m0oUtndIjenIvSx6t3Y+agK2F3EPbb0AZ5wZ1p1IXs4vktgeQwSSBdqcM8LZFDvZ\n"\  
  147.         "uPboQnJoRdIkd62XnP5ekIEIBAfOp8v2wFpSfE7nNH2u4CpAXNSF9HsCgYEA2l8D\n"\  
  148.         "JrDE5m9Kkn+J4l+AdGfeBL1igPF3DnuPoV67BpgiaAgI4h25UJzXiDKKoa706S0D\n"\  
  149.         "4XB74zOLX11MaGPMIdhlG+SgeQfNoC5lE4ZWXNyESJH1SVgRGT9nBC2vtL6bxCVV\n"\  
  150.         "WBkTeC5D6c/QXcai6yw6OYyNNdp0uznKURe1xvMCgYBVYYcEjWqMuAvyferFGV+5\n"\  
  151.         "nWqr5gM+yJMFM2bEqupD/HHSLoeiMm2O8KIKvwSeRYzNohKTdZ7FwgZYxr8fGMoG\n"\  
  152.         "PxQ1VK9DxCvZL4tRpVaU5Rmknud9hg9DQG6xIbgIDR+f79sb8QjYWmcFGc1SyWOA\n"\  
  153.         "SkjlykZ2yt4xnqi3BfiD9QKBgGqLgRYXmXp1QoVIBRaWUi55nzHg1XbkWZqPXvz1\n"\  
  154.         "I3uMLv1jLjJlHk3euKqTPmC05HoApKwSHeA0/gOBmg404xyAYJTDcCidTg6hlF96\n"\  
  155.         "ZBja3xApZuxqM62F6dV4FQqzFX0WWhWp5n301N33r0qR6FumMKJzmVJ1TA8tmzEF\n"\  
  156.         "yINRAoGBAJqioYs8rK6eXzA8ywYLjqTLu/yQSLBn/4ta36K8DyCoLNlNxSuox+A5\n"\  
  157.         "w6z2vEfRVQDq4Hm4vBzjdi3QfYLNkTiTqLcvgWZ+eX44ogXtdTDO7c+GeMKWz4XX\n"\  
  158.         "uJSUVL5+CVjKLjZEJ6Qc2WZLl94xSwL71E41H4YciVnSCQxVc4Jw\n"\  
  159.         "-----END RSA PRIVATE KEY-----\n";  
  160.   
  161.     unsigned char  encrypted[4098] = {};  
  162.     unsigned char decrypted[4098] = {};  
  163.   
  164.     //int encrypted_length= public_encrypt((unsigned char*)plainText,strlen(plainText),(unsigned char*)publicKey,encrypted);  
  165.     int encrypted_length= public_encrypt((unsigned char*)plainText.c_str(), plainText.length(), (unsigned char*)publicKey.c_str(), encrypted);  
  166.     if (encrypted_length == -1) {  
  167.         printLastError("Public Encrypt failed ");  
  168.         exit(0);  
  169.     }  
  170.     printf("Encrypted length =%d\n", encrypted_length);  
  171.   
  172.     int decrypted_length = private_decrypt(encrypted, encrypted_length, (unsigned char*)privateKey.c_str(), decrypted);  
  173.     if (decrypted_length == -1) {  
  174.         printLastError("Private Decrypt failed ");  
  175.         exit(0);  
  176.     }  
  177.     printf("Decrypted Text =%s\n", decrypted);  
  178.     printf("Decrypted Length =%d\n", decrypted_length);  
  179.   
  180.     encrypted_length= private_encrypt((unsigned char*)plainText.c_str(), plainText.length(),(unsigned char*)privateKey.c_str(), encrypted);  
  181.     if(encrypted_length == -1) {  
  182.         printLastError("Private Encrypt failed");  
  183.         exit(0);  
  184.     }  
  185.     printf("Encrypted length =%d\n", encrypted_length);  
  186.   
  187.     decrypted_length = public_decrypt(encrypted, encrypted_length, (unsigned char*)publicKey.c_str(), decrypted);  
  188.     if(decrypted_length == -1) {  
  189.         printLastError("Public Decrypt failed");  
  190.         exit(0);  
  191.     }  
  192.     printf("Decrypted Text =%s\n", decrypted);  
  193.     printf("Decrypted Length =%d\n", decrypted_length);  
  194. }  
  195.   
  196. void RSA_test2(const string cleartext)  
  197. {  
  198.     size_t pri_len;            // Length of private key  
  199.     size_t pub_len;            // Length of public key  
  200.     char   *pri_key;           // Private key  
  201.     char   *pub_key;           // Public key  
  202.     char   msg[KEY_LENGTH/8];  // Message to encrypt  
  203.     char   *encrypt = NULL;    // Encrypted message  
  204.     char   *decrypt = NULL;    // Decrypted message  
  205.     char   *err;               // Buffer for any error messages  
  206.     string str;  
  207.   
  208.     // Generate key pair  
  209.     //printf("Generating RSA (%d bits) keypair...", KEY_LENGTH);  
  210.     fflush(stdout);  
  211.     RSA *keypair = RSA_generate_key(KEY_LENGTH, PUB_EXP, NULL, NULL);  
  212.   
  213.     // To get the C-string PEM form:  
  214.     BIO *pri = BIO_new(BIO_s_mem());  
  215.     BIO *pub = BIO_new(BIO_s_mem());  
  216.   
  217.     PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);  
  218.     PEM_write_bio_RSAPublicKey(pub, keypair);  
  219.   
  220.     pri_len = BIO_pending(pri);  
  221.     pub_len = BIO_pending(pub);  
  222.   
  223.     pri_key = (char*)malloc(pri_len + 1);  
  224.     pub_key = (char*)malloc(pub_len + 1);  
  225.   
  226.     BIO_read(pri, pri_key, pri_len);  
  227.     BIO_read(pub, pub_key, pub_len);  
  228.   
  229.     pri_key[pri_len] = '\0';  
  230.     pub_key[pub_len] = '\0';  
  231.   
  232. #ifdef PRINT_KEYS  
  233.     printf("\n%s\n%s\n", pri_key, pub_key);  
  234. #endif  
  235.     //printf("done.\n");  
  236.   
  237.     // Get the message to encrypt  
  238.     printf("Message to encrypt: ");  
  239.     fgets(msg, KEY_LENGTH-1, stdin);  
  240.     msg[strlen(msg)-1] = '\0';  
  241.     //string msg = cleartext;  
  242.     //cout<<"length:"<<strlen(msg)<<endl;  
  243.   
  244.     // Encrypt the message  
  245.     encrypt = (char*)malloc(RSA_size(keypair));  
  246.     int encrypt_len;  
  247.     err = (char*)malloc(130);  
  248.     if((encrypt_len = RSA_public_encrypt(strlen(msg)+1, (unsigned char*)msg, (unsigned char*)encrypt, keypair, RSA_PKCS1_OAEP_PADDING)) == -1) {  
  249.     //if((encrypt_len = RSA_public_encrypt(msg.length(), (unsigned char*)msg.c_str(), (unsigned char*)encrypt, keypair, RSA_PKCS1_OAEP_PADDING)) == -1) {  
  250.         ERR_load_crypto_strings();  
  251.         ERR_error_string(ERR_get_error(), err);  
  252.         fprintf(stderr, "Error encrypting message: %s\n", err);  
  253.         goto free_stuff;  
  254.     }  
  255.   
  256. #ifdef WRITE_TO_FILE  
  257.     // Write the encrypted message to a file  
  258.     FILE *out = fopen("out.bin""w");  
  259.     fwrite(encrypt, sizeof(*encrypt),  RSA_size(keypair), out);  
  260.     fclose(out);  
  261.     printf("Encrypted message written to file.\n");  
  262.     free(encrypt);  
  263.     encrypt = NULL;  
  264.   
  265.     // Read it back  
  266.     printf("Reading back encrypted message and attempting decryption...\n");  
  267.     encrypt = (char*)malloc(RSA_size(keypair));  
  268.     out = fopen("out.bin""r");  
  269.     fread(encrypt, sizeof(*encrypt), RSA_size(keypair), out);  
  270.     fclose(out);  
  271. #endif  
  272.   
  273.     // Decrypt it  
  274.     decrypt = (char*)malloc(encrypt_len);  
  275.     //decrypt = new char[encrypt_len + 1];  
  276.     //memset(decrypt, encrypt_len+1, 0);  
  277.   
  278.     if(RSA_private_decrypt(encrypt_len, (unsigned char*)encrypt, (unsigned char*)decrypt, keypair, RSA_PKCS1_OAEP_PADDING) == -1) {  
  279.             ERR_load_crypto_strings();  
  280.             ERR_error_string(ERR_get_error(), err);  
  281.             fprintf(stderr, "Error decrypting message: %s\n", err);  
  282.             goto free_stuff;  
  283.     }  
  284.     printf("Decrypted message: %s\n", decrypt);  
  285.   
  286. free_stuff:  
  287.     RSA_free(keypair);  
  288.     BIO_free_all(pub);  
  289.     BIO_free_all(pri);  
  290.     free(pri_key);  
  291.     free(pub_key);  
  292.     free(encrypt);  
  293.     free(decrypt);  
  294.     free(err);  
  295. }  

3. main.cpp:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include "stdafx.h"  
  2. #include "cryptotest.h"  
  3. #include <iostream>  
  4. #include <string>  
  5.   
  6. using namespace std;  
  7.   
  8. int main(int argc, char* argv[])  
  9. {  
  10.     //string strKey[2] = {};//[0]:public key; [1]:private key   
  11.     //GenerateRSAKey(strKey);  
  12.     //cout<<"public key:"<<endl<<strKey[0]<<endl;  
  13.     //cout<<"private key:"<<endl<<strKey[1]<<endl;  
  14.   
  15.     string cleartext = "中国北京12345$abcde%ABCDE@!!!!";  
  16.   
  17.     if (cleartext.length() > 256) {  
  18.         cout<<"cleartext too length!!!"<<endl;  
  19.         return -1;  
  20.     }  
  21.   
  22.     RSA_test1(cleartext);  
  23.     //RSA_test2(cleartext);  
  24.   
  25.     cout<<"ok!!!"<<endl;  
  26.   
  27.     return 0;  
  28. }  

RSA算法理论摘自:

1. 《基于DES_RSA加密算法的改进与实现》

2. 《DES和RSA混合加密算法的研究》

测试代码中:

1. RSA_test1中的代码主要来自于: http://hayageek.com/rsa-encryption-decryption-openssl-c/

2. RSA_test2中的代码主要来自于: https://shanetully.com/2012/04/simple-public-key-encryption-with-rsa-and-openssl/

GitHubhttps://github.com/fengbingchun/OpenSSL_Test

原文:http://blog.csdn.net/fengbingchun/article/details/43638013


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值