OpenSSL文档阅读笔记-How to Use OpenSSL to Generate RSA Keys in C/C++

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenSSL文档阅读笔记-How to Use OpenSSL to Generate RSA Keys in C/C++相关的知识,希望对你有一定的参考价值。

这篇文章是2014年2月26号的,有点老了,但挺有用的。

首先要配置好环境,再前一篇笔记中已经说明了,在此不再说明。

这里我把老外的这套代码,改写成Qt pro管理项目。

关键代码如下:

GenerateRSAKeys.pro

QT += core
QT -= gui

TARGET = GenerateRSAKeys
CONFIG += console
CONFIG += c++11
CONFIG -= app_bundle

QMAKE_CFLAGS = -fpermissive
QMAKE_CXXFLAGS = -fpermissive
QMAKE_LFLAGS = -fpermissive

INCLUDEPATH += /usr/local/ssl/include
LIBS += -L /usr/local/ssl/lib/ -lssl -lcrypto

TEMPLATE = app

SOURCES += main.cpp

main.cpp

#include <QCoreApplication>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <QDebug>

int main(int argc, char *argv[])

    QCoreApplication a(argc, argv);

    int ret = 0;
    RSA *r = nullptr;
    BIGNUM *bne = nullptr;
    BIO *bp_public = nullptr;
    BIO *bp_private = nullptr;
    int bits = 2048;
    unsigned long e = RSA_F4;

    //generate rsa key
    bne = BN_new();
    ret = BN_set_word(bne, e);
    if(!ret)

        qDebug() << "BN_set_word() error";
        BIO_free_all(bp_public);
        BIO_free_all(bp_private);
        RSA_free(r);
        BN_free(bne);
        return 0;
    

    r = RSA_new();
    ret = RSA_generate_key_ex(r, bits, bne, nullptr);
    if(!ret)

        qDebug() << "RSA_generate_key() error";
        BIO_free_all(bp_public);
        BIO_free_all(bp_private);
        RSA_free(r);
        BN_free(bne);
        return 0;
    

    //save public key
    bp_public = BIO_new_file("public.pem", "w+");
    ret = PEM_write_bio_RSAPublicKey(bp_public, r);
    if(!ret)

        qDebug() << "PEM_write_bio_RSAPublicKey() error";
        BIO_free_all(bp_public);
        BIO_free_all(bp_private);
        RSA_free(r);
        BN_free(bne);
        return 0;
    

    //save private key
    bp_private = BIO_new_file("private.pem", "w+");
    ret = PEM_write_bio_RSAPrivateKey(bp_private, r, nullptr, nullptr, 0, nullptr, nullptr);
    if(!ret)

        qDebug() << "PEM_write_RSAPrivateKey() error";
        BIO_free_all(bp_public);
        BIO_free_all(bp_private);
        RSA_free(r);
        BN_free(bne);
        return 0;
    

    //free
    BIO_free_all(bp_public);
    BIO_free_all(bp_private);
    RSA_free(r);
    BN_free(bne);
    qDebug() << "success";

    return a.exec();

运行截图如下:

此时输出两个文件:

private.pem:

public.pem

源码打包下载地址:

Qt/GenerateRSAKeys at master · fengfanchen/Qt · GitHub

 

 

 

 

以上是关于OpenSSL文档阅读笔记-How to Use OpenSSL to Generate RSA Keys in C/C++的主要内容,如果未能解决你的问题,请参考以下文章

Laravel文档阅读笔记-How to use @auth and @guest directives in Laravel

C++文档阅读笔记-Smart Pointers in C++ and How to Use Them

C++文档阅读笔记-Smart Pointers in C++ and How to Use Them

C++文档阅读笔记-Smart Pointers in C++ and How to Use Them

How to use the Custom Material node and create Metaballs 官方视频学习笔记

Laravel文档阅读笔记-How to deploy Laravel 8 project on Cpanel shared hosting