How to use private key on a PKCS#11 module instead of perivate key file for mutual-authentication in OpenSSL?

99封情书 提交于 2019-12-08 03:24:08

问题


I've a simple SSL client that uses OpenSSL library. My server requires client authentication & so I've to set client's private key stored in a password protected PEM file. I use the following code for this purpose:

/* set the private key from KeyFile */
if (SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0)
{
    ERR_print_errors_fp(stderr);
    abort();
}

/* verify private key */
if ( !SSL_CTX_check_private_key(ctx) )
{
    fprintf(stderr, "Private key does not match the public certificate\n");
    abort();
}

Now I want to know how can I establish a SSL connection using private key stored on a security token (with PKCS#11 interface) instead of reading it from a file?


回答1:


Answer is a little bit complicated. First You need to load Engine of your PKCS#11:

ENGINE_load_builtin_engines();
{
    if (!(e = ENGINE_by_id("dynamic")))
        goto err;
    if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", "dstu", 0))
        goto err;
    if (!ENGINE_ctrl_cmd_string(e, "LIST_ADD", "2", 0))
        goto err;
    if (!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
        goto err;
    e = ENGINE_by_id("pkcs11_engine");
    if (!e)
      return error;

res = ENGINE_init(e);
if (!ENGINE_set_default(e, ENGINE_METHOD_ALL))
    goto err;

}

then you need load EVP_PKEY* from engine EVP_PKEY* key = ENGINE_load_private_key(e, "SecureToken", NULL, &cb_data);

and pass it to SSL: int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);

strings SecureToken and pkcs11_engine you should found in documentation to your engine pkcs11 module



来源:https://stackoverflow.com/questions/27129142/how-to-use-private-key-on-a-pkcs11-module-instead-of-perivate-key-file-for-mutu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!