How to create a RSA public key from a unsigned char * modulus and exponent 65537(RSA_F4)
c, c++, linux, openssl
Solution
You probably want something that looks more like:
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");
edit
Your code works fine, except for the error check. RSA_public_encrypt returns the size of the ciphertext on success, not 0, so to make the code above work, add a `<= 0` test to `if` line:
if (RSA_public_encrypt(....) <= 0)
Problem
I'm trying generate a rsa public key from a modulus type char[], and I now the exponent is RSA_F4(65537); But when I'm trying generate my public key using this values for "n" and "e", the RSA_public_encrypt, return -1; Thanks! My code: ``` #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; } ```