2014-12-22 120 views
0

我一直在C中使用OpenSSL库很长一段时间,但现在我需要迁移到C++。 OpenSSL的文档描述了这样的MD5功能。将字符串传递给接受指向字符的指针的函数

unsigned char *MD5(const unsigned char *d, unsigned long n, 
       unsigned char *md); 

我想通过string类型的变量该功能,但它仅接受char *是否可以通过string直接在C++中通过char *类型的参数?(我不想使用额外的操作与string类型的变量)

+0

的注意,如果你正在移植是写得很好的C代码,就没有必要“ C++ - ify“it –

回答

2

您可以使用c_str成员函数std::string运动。例如

std::string data; 
// load data somehow 
unsigned char md[16] = { }; 
unsigned char *ret = MD5(reinterpret_cast<const unsigned char*>(data.c_str()), 
         data.size(), 
         md); 

如果要废除这个丑陋的转换运算符,定义保存unsigned char!而非char S和使用一个字符串类。

typedef std::basic_string<unsigned char> ustring; 
ustring data; 
unsigned char *ret = MD5(data.c_str(), data.size(), md); 
+0

我知道了,但它会轻微的失去时间,难道不是吗? – ForceBru

+2

@ForceBru你认为”时间的浪费“会来自哪里? – Angew

+0

@Angew,它可能来自' c_str()'调用,但没关系,没关系 – ForceBru

2

只是一个小记录,这可能会为您节省后头痛。 MD5将一个无符号字符指针作为参数。这是一个线索,它实际上不是一个字符串,而是一个指向字节的指针。

在你的程序中,如果你开始在std :: string中存储字节向量,你最终将初始化一个包含零的字节向量的字符串,这会打开一个很难检测到的bug的可能性线。

它是安全的所有字节向量存储在std::vector<unsigned char>(或std::vector<uint8_t>因为这迫使安全初始化。

std::vector<unsigned char> plaintext; 
// initialise plaintext here 
std::vector<unsigned char> my_hash(16); 
MD5(plaintext.data(), plaintext.size(), &my_hash[0]); 
相关问题