如何在 C 中实现 RSA 加密?

How to implement RSA Encryption in C?

我正在尝试在 C 程序中使用非对称加密,以加密字符串

我选择使用 RSA,但是如果有更简单但更安全的方法,请告诉我

OpenSSL 是我查看过的一个库,但没有找到关于在 C 代码中实现它的文档。 (我可能只是运气不好,找了很多天)

YouTube/Google 也不走运...

请指出有关如何执行此操作的详细信息来源...

我非常了解 C 和 RSA 的基本概念,但是我不知道如何:

  1. 生成生成密钥所需的大素数。
  2. 修复 e = 65537 .
  3. 以字母数字格式生成 public / 私钥(它们实际上是数字,不是吗?)。
  4. 无缝组合 public 密钥中的 (e,n) 和私钥中的 (d,n),就像 OpenSSL 等工具所做的那样(在字母数字字符串中)。

这是您要执行的操作的示例。首先是打印 OpenSSL 错误消息的实用函数:

void log_ssl_err(const char *mes)
{
    unsigned long err, found;
    char errstr[1000];

    found = 0;
    while ((err = ERR_get_error())) {
        ERR_error_string(err, errstr);
        printf("%s: %s", mes, errstr);
        found = 1;
    }
    if (!found) {
        printf("%s", mes);
    }
}

正在生成具有给定指数的密钥:

RSA *rsa;
BIGNUM *e;
uint32_t exponent_bin, exponent_num;

exponent_num = 65537;
exponent_bin = htonl(exponent);
e = BN_bin2bn((const unsigned char *)&exponent_bin, 4, NULL);
if (e == NULL) {
    log_ssl_err("BN_bin2bn failed for e");
    exit(1);
}

if ((rsa = RSA_new()) == NULL) {
    log_ssl_err("RSA_new failed");
    BN_free(e);
    exit(1);
}
if (!RSA_generate_key_ex(rsa, 2048, e, NULL)) {
    log_ssl_err("couldn't generate rsa key");
    BN_free(e);
    exit(1);
}

加密和解密:

unsigned char plaintext[] = "this is the plaintext";
unsigned char *ciphertext, *decrypted;
int cipher_len, decrypted_len;

ciphertext = malloc(RSA_size(rsa));
if ((cipher_len = RSA_public_encrypt(strlen(plaintext), plaintext, ciphertext, 
                                    rsa, RSA_PKCS1_OAEP_PADDING)) == -1) {
    log_ssl_err("RSA_public_encrypt failed");
    exit(1);
}

decrypted = malloc(RSA_size(rsa));
if ((decrypted_len = RSA_private_decrypt(cipher_len, ciphertext, decrypted, 
                                         rsa, RSA_PKCS1_OAEP_PADDING)) == -1) {
    log_ssl_err("RSA_private_decrypt failed");
    return 0;
}

OpenSSL 的文档可能难以浏览,但您可以在手册页中找到所需的信息。如果你 运行 man 3 rsa 你会看到所有 RSA 相关函数的列表。从那里您可以查看每个函数的手册页。