Pregunta

I am trying to generate an RSA private key and set a passphrase for it programmatically.

Using the following code I can generate an unencrypted key without a passphrase no problem:

if (!PEM_write_PrivateKey(priv_f, key_p, NULL, NULL, 0, 0, NULL)) {
    fprintf(stderr, "Write private key failed\n");
    return -1;
}

But using this code, I keep getting the write private key failed error:

if (!PEM_write_PrivateKey(priv_f, key_p, EVP_des_ede3_cbc(), NULL, 0, 0, passphrase)) {
    fprintf(stderr, "Write private key failed\n");
    return -1;
}

I am trying to follow the code on the man page here. Is there any way I can get more information out of the error? Errno is always 0. Thanks!

¿Fue útil?

Solución

By adding the following code and making a slight alteration to the PEM_write_PrivateKey arguments I got it working.

void init_openssl(void)
{
    if (SSL_library_init()) {
        SSL_load_error_strings();
        OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();
        RAND_load_file(_RAND_FILENAME, _RAND_LOADSIZE);
    } else {
        exit(EXIT_FAILURE);
    }
}

And

if (!PEM_write_PrivateKey(priv_f, key_p,EVP_aes_256_cbc(),
                          (unsigned char*)passphrase,(int)strlen(passphrase), NULL, NULL)) {
    fprintf(stderr, "Write private key failed\n");
    handle_openssl_error();
    return -1;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top