带有密码的BOOST ASIO加载key.pem

Alv*_*olm 4 c++ ssl openssl boost-asio pem

目前,我正在与此:

...
    ctx.use_certificate_chain_file("./C/cert.pem");
    ctx.use_private_key_file("./C/key.pem", boost::asio::ssl::context::pem);
    ctx.load_verify_file("./C/ca.pem");
...
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都运行完美,但我真正需要做的是加载相同key.pem但有密码,望着ASIO文档发现SSL ::背景:: set_password_callback根据信息至极调用SSL_CTX_set_default_passwd_cb并允许处理加密的PEM文件,请记住,我对python等高级语言更加熟悉,因此c ++不是我的强项

任何帮助表示赞赏,谢谢!

Ano*_*ard 5

您应该熟悉python的回调。

首先定义回调函数:

using namespace boost::asio;

// this function is called to obtain password info about an encrypted key
std::string my_password_callback(
    std::size_t max_length,  // the maximum length for a password
    ssl::context::password_purpose purpose ) // for_reading or for_writing
{
    std::string password; 
    // security warning: !! DO NOT hard-code the password here !!
    // read it from a SECURE location on your system
    return password;
}
Run Code Online (Sandbox Code Playgroud)

然后设置回调set_password_callback()

// set the callback before you load the protected key
ctx.set_password_callback(my_password_callback);
// ...
// this will call my_password_callback if a password is required
ctx.use_private_key_file("key.pem",ssl::context::pem);
Run Code Online (Sandbox Code Playgroud)

如果您想使用类方法作为回调,

class server {
    std::string password_callback(); //NOTE: no parameters
    // ...
};
Run Code Online (Sandbox Code Playgroud)

您可以boost::bind()用来设置回调:

#include <boost/bind.hpp>

void server::startup() {
    ctx_.set_password_callback(
        boost::bind(&server::password_callback,this) );
    // ...
}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,如果无法解密密钥(可能是由于密码错误或找不到文件),都会引发boost::system::system_error异常(基于std::exception)。