gpt4 book ai didi

c++ - 如何从 unsigned char * 模数和指数 65537(RSA_F4) 创建 RSA 公钥

转载 作者:IT王子 更新时间:2023-10-29 00:53:45 28 4
gpt4 key购买 nike

我正在尝试从模数类型 char[] 生成一个 rsa 公钥,我现在的指数是 RSA_F4(65537);但是当我尝试使用“n”和“e”的值生成我的公钥时,RSA_public_encrypt 返回 -1;

谢谢!

我的代码:

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <crypt.h>
#include <iostream>
#include <stdlib.h>
#include <openssl/rsa.h>
#include <openssl/aes.h>
#include <openssl/opensslconf.h>
#include <openssl/engine.h>
#include <openssl/pem.h>
#include <openssl/rc4.h>

using namespace std;
int main(void)
{

//modulus in format char hex;
char key[] = "C0E7FC730EB5CF85B040EC25DAEF288912641889AD651B3707CFED9FC5A1D3F6C40062AD46E3B3C3E21D4E71CC4800C80226D453242AEB2F86D748B41DDF35FD";

char palavra[] = "teste";
char crip[512];
int ret;
RSA * pubkey = RSA_new();
BIGNUM * modul = BN_new();
BIGNUM * expon = BN_new();

BN_hex2bn(&modul, (const char *) key);
BN_hex2bn(&expon, "010001");

cout << "N KEY: " << BN_bn2hex(modul) << endl;
cout << "E KEY: " << BN_bn2hex(expon) << endl;

pubkey->n = modul;
pubkey->e = expon;

cout << "N PUB KEY: " << BN_bn2hex(pubkey->n) << endl;
cout << "E PUB KEY: " << BN_bn2hex(pubkey->e) << endl;

if (RSA_public_encrypt(strlen((const char *) palavra), (const unsigned char *) palavra, (unsigned char *) crip, pubkey, RSA_PKCS1_PADDING ))
{
printf("ERRO encrypt\n");
}
else
{
printf("SUC encrypt\n");
}
return 0;
}

最佳答案

您可能想要看起来更像的东西:

RSA *pubkey = RSA_new();
int len = BN_hex2bn(&pubkey->n, (const char *)p);
if (len == 0 || p[len])
fprintf(stderr, "'%s' does not appear to be a valid modulus\n", p);
BN_hex2bn(&pubkey->e, "010001");

编辑

除了错误检查,您的代码工作正常。 RSA_public_encrypt 在成功时返回密文的大小,而不是 0,因此要使上面的代码有效,请添加 <= 0测试 if行:

if (RSA_public_encrypt(....) <= 0)

关于c++ - 如何从 unsigned char * 模数和指数 65537(RSA_F4) 创建 RSA 公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10742451/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com