25
2019
09

How to Use OpenSSL to Generate RSA Keys in C/C++

It is known that RSA is a cryptosystem which is used for the security of data transmission. This tutorial introduces how to use RSA to generate a pair of public and private keys on Windows.

  1. Download and install OpenSSL https://www.openssl.org/community/binaries.html.

  2. Find libeay32.lib, ssleay32.lib and libeay32.dll.

  3. The following sample code will generate a public key “public.pem” and a private key “private.pem”.

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
#include <stdio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
 
bool generate_key()
{
    int             ret = 0;
    RSA             *r = NULL;
    BIGNUM          *bne = NULL;
    BIO             *bp_public = NULL, *bp_private = NULL;
 
    int             bits = 2048;
    unsigned long   e = RSA_F4;
 
    // 1. generate rsa key
    bne = BN_new();
    ret = BN_set_word(bne,e);
    if(ret != 1){
        goto free_all;
    }
 
    r = RSA_new();
    ret = RSA_generate_key_ex(r, bits, bne, NULL);
    if(ret != 1){
        goto free_all;
    }
 
    // 2. save public key
    bp_public = BIO_new_file("public.pem", "w+");
    ret = PEM_write_bio_RSAPublicKey(bp_public, r);
    if(ret != 1){
        goto free_all;
    }
 
    // 3. save private key
    bp_private = BIO_new_file("private.pem", "w+");
    ret = PEM_write_bio_RSAPrivateKey(bp_private, r, NULL, NULL, 0, NULL, NULL);
 
    // 4. free
free_all:
 
    BIO_free_all(bp_public);
    BIO_free_all(bp_private);
    RSA_free(r);
    BN_free(bne);
 
    return (ret == 1);
}
 
int main(int argc, char* argv[])
{
    generate_key();
        return 0;
}

You can feel free to download the sample code, and run it in Visual Studio.


https://www.codepool.biz/how-to-use-openssl-generate-rsa-keys-cc.html

« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。