我有两个独立的程序(拼接在下面)。第一个生成密钥对并保存到文件(工作正常)。第二个打开私钥,用一个密码短语解密,然后我需要它签署一个文本字符串。下面的代码在pem_read_privatekey()调用(最后一次)时失败(看不出原因)。有人能告诉我我做错了什么,然后我应该用这个私钥来调用openssl来签署一些文本吗?

int main (int argc, char *argv[])
{
    char *priv_pem = "priv.pem";
    char *pub_pem  = "pub.pem";
    char *pass     = "Password";
    FILE *fp;
    int bits = 4096;
    unsigned long exp = RSA_F4;

    RSA *rsa;
    EVP_PKEY *pkey;

    //  GENERATE KEY
    rsa=RSA_generate_key(bits,exp,NULL,NULL);
    if (RSA_check_key(rsa)!=1)
        Exit(1,"Error whilst checking key","");
    pkey = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(pkey, rsa);

    //  WRITE ENCRYPTED PRIVATE KEY
    if (!(fp = fopen(priv_pem, "w")))
        Exit(2,"Error opening PEM file",priv_pem);
    if (!PEM_write_PrivateKey(fp,pkey,EVP_aes_256_cbc(),NULL,0,NULL,pass))
        Exit(3,"Error writing PEM file",priv_pem);
    fclose(fp);

    //  WRITE PUBLIC KEY
    if (!(fp = fopen(pub_pem, "w")))
        Exit(4,"Error opening PEM file",pub_pem);
    if (!PEM_write_PUBKEY(fp, pkey))
        Exit(5,"Error writing PEM file",pub_pem);
    fclose(fp);
    // ------- End of key generation program -------

    // ------- Start of text signing program -------
    //  READ IN ENCRYPTED PRIVATE KEY
    if (!(fp = fopen(priv_pem, "r")))
        Exit(6,"Error reading encrypted private key file",priv_pem);
    if (!PEM_read_PrivateKey(fp,&pkey,NULL,pass))
        Exit(7,"Error decrypting private key file",priv_pem);
    fclose(fp);

    // Sign some text using the private key....

    //  FREE
    RSA_free(rsa);
    return 0;
}

最佳答案

在将pkey传递到NULL之前,您是否已将&pkey初始化为PEM_read_PrivateKey()?如果不是,它将尝试重新使用EVP_PKEY指向的pkey结构,如果pkey未初始化,它将看到内存中的一个随机点。
当出现错误时,可以使用ERR_print_errors_fp(stderr);将openssl错误堆栈转储到stderr-这通常有助于找到问题。

10-08 03:55