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

x33g5p2x  于2022-07-10 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(206)

这篇文章是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

相关文章

微信公众号

最新文章

更多