以下是一个简单的示例程序,用于生成RSA密钥对并将其保存到文件中:

#include <stdio.h>
#include <stdlib.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>

int main() {
    RSA *rsa = RSA_new();
    BIGNUM *bn = BN_new();
    int bits = 2048; // 指定RSA密钥的位数
    unsigned long e = RSA_F4; // 指定公共指数
    int ret;

    // 生成RSA密钥对
    ret = RSA_generate_key_ex(rsa, bits, bn, NULL);
    if (ret != 1) {
        printf("RSA_generate_key_ex failed.\n");
        exit(1);
    }

    // 将私钥保存到文件中
    FILE *fp = fopen("private.pem", "w");
    if (fp == NULL) {
        printf("Failed to open private.pem.\n");
        exit(1);
    }
    ret = PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL);
    if (ret != 1) {
        printf("Failed to write private key.\n");
        exit(1);
    }
    fclose(fp);

    // 将公钥保存到文件中
    fp = fopen("public.pem", "w");
    if (fp == NULL) {
        printf("Failed to open public.pem.\n");
        exit(1);
    }
    ret = PEM_write_RSAPublicKey(fp, rsa);
    if (ret != 1) {
        printf("Failed to write public key.\n");
        exit(1);
    }
    fclose(fp);

    RSA_free(rsa);
    BN_free(bn);
    return 0;
}

该程序使用了OpenSSL库中的RSA和PEM模块。首先使用RSA_new函数创建了一个RSA结构体,然后使用RSA_generate_key_ex函数生成了RSA密钥对。接着使用PEM_write_RSAPrivateKey和PEM_write_RSAPublicKey函数将私钥和公钥分别保存到了private.pem和public.pem文件中。最后,通过RSA_free和BN_free函数释放了内存。

注意:在使用OpenSSL库时,应该注意安全问题,例如加密密钥的保护等

openssl C 语言生成RSA密钥

原文地址: https://www.cveoy.top/t/topic/cbh0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录