2012-12-21 52 views
4

目前我与这方面的工作:BOOST ASIO负载key.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"); 
... 

到目前为止,一切都运行完美,但我真正需要做的是加载相同key.pem但使用密码,看着ASIO文档发现,根据ssl::context::set_password_callback至极的信息调用SSL_CTX_set_default_passwd_cb,并允许处理加密PEM文件,请记得,我和高级语言如Python更熟悉,所以C++是不是我的专长

任何帮助表示感谢,谢谢!

回答

4

你应该熟悉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)将被抛出 如果密钥无法解密,可能是因为密码错误或文件不能被发现。