带有密码的BOOST ASIO负载键

BOOST ASIO load key.pem with passphrase

本文关键字:ASIO 负载 BOOST 密码      更新时间:2023-10-16

目前我正在处理:

...
    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");
...

到目前为止,一切正常,但是我真正需要做的就是加载相同的键。处理加密的PEM文件,请记住,我对像Python这样的高级语言更加熟悉,因此C 不是我的Forte

任何帮助将不胜感激,谢谢!

您应该熟悉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;
}

然后用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);

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

class server {
    std::string password_callback(); //NOTE: no parameters
    // ...
};

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

#include <boost/bind.hpp>
void server::startup() {
    ctx_.set_password_callback(
        boost::bind(&server::password_callback,this) );
    // ...
}

无论哪种情况,boost::system::system_error异常(基于std::exception)都将被抛弃如果无法解密密钥,可能是因为密码错误或找不到文件。