c - 如何在 C 中实现 RSA 加密?
问题描述
我正在尝试在 C 程序中使用非对称加密来加密字符串。
我选择使用 RSA,但如果有更简单但安全的方法,请告诉我。
OpenSSL 是我查看过的一个库,但没有找到关于在 C 代码中实现它的文档。(我可能只是运气不好,我已经找了很多天了)
在 YouTube/Google 上也没有运气......
请指出有关如何执行此操作的详细信息来源...
我非常了解 C 和 RSA 的基本概念,但我不知道如何:
- 生成生成密钥所需的大素数。
- 修复 e = 65537 。
- 以字母数字格式生成公钥/私钥(它们实际上是数字,不是吗?)。
- 无缝结合公钥中的 (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 相关函数的列表。从那里您可以查看每个函数的手册页。
推荐阅读
- spring-boot - Spring Boot - 使用 H2 进行单元测试和快速开发(使用 Spring 配置文件)
- batch-file - 将文件编译成一个自解压安装程序
- java - 我不明白为什么会收到 ArrayIndexOutOfBoundsException?
- java - 将空格分隔的整数字符串解析为过滤的整数数组
- c# - 如何使用 Unity 一次性注入两个实现?
- node.js - Linux EC2上的升级节点-解压缩gz文件后如何安装?
- javascript - 如何导出命名空间的 TypeScript 接口?
- sql - 当另一半为空时,联合从一半查询中消除行
- php - 如何在 Laravel 的对象数组中获取特定项目
- java - playbook 需要检查 java 版本,如果 java 版本低于 1.8* 版本,则 playbook 安装 java 1.8*