读取受3DES保护的DSA私钥

时间:2015-03-17 15:06:36

标签: c++ openssl

以下是我如何成功创建密钥对并在文件中存储的方法。当读取受密码保护的私钥时,问题就来了,我总是得到NULL。有什么提示可以解决这个问题?感谢。

FILE *dsa_privatekey_file;
FILE *dsa_publickey_file;

const char *pkeykey = "password";

int result = 0;

DeleteFile("dsapub.pem");
DeleteFile("dsapriv.pem");

dsa_publickey_file = fopen("dsapub.pem", "r");
dsa_privatekey_file = fopen("dsapriv.pem", "r");

if (dsa_privatekey_file == NULL || dsa_publickey_file == NULL)
{
    if (dsa_privatekey_file != NULL)
    {
        fclose(dsa_privatekey_file);
    }
    if (dsa_publickey_file != NULL)
    {
        fclose(dsa_publickey_file);
    }

    dsa_publickey_file = fopen("dsapub.pem", "w");
    dsa_privatekey_file = fopen("dsapriv.pem", "w");

    DSA* dsa = DSA_new();
    result = DSA_generate_parameters_ex(dsa, 2048, NULL, 0, NULL, NULL, NULL);
    result = DSA_generate_key(dsa);

    result = PEM_write_DSAPrivateKey(dsa_privatekey_file, dsa, EVP_des_ede3_cbc(), NULL, 0, NULL, (void *)pkeykey);
    //result = PEM_write_DSAPrivateKey(dsa_privatekey_file, dsa, EVP_des_ede3_cbc(), (unsigned char *) pkeykey, strlen(pkeykey), NULL, NULL);
    //result = PEM_write_DSAPrivateKey(dsa_privatekey_file, dsa, NULL, NULL, 0, NULL, NULL);

    result = PEM_write_DSA_PUBKEY(dsa_publickey_file, dsa);

    fclose(dsa_privatekey_file);
    fclose(dsa_publickey_file);

    DSA_free(dsa);

    dsa_publickey_file = fopen("dsapub.pem", "r");
    dsa_privatekey_file = fopen("dsapriv.pem", "r");
}

DSA *dsa_sign = PEM_read_DSAPrivateKey(dsa_privatekey_file, NULL, default_set_password, (void *)pkeykey);

DSA *dsa_verify = PEM_read_DSA_PUBKEY(dsa_publickey_file, NULL, NULL, NULL);

这是我用来硬插入密码的简单函数,但无论如何它似乎都没有被调用。

static int default_set_password(char *buf, int size, int rwflag, void *descr){ memcpy(buf, descr, size); return size; }

1 个答案:

答案 0 :(得分:1)

致电

OpenSSL_add_all_algorithms(); 

需要按预期工作。