如何将 CryptoPP::Integer 转换为 char*

How to convert CryptoPP::Integer to char*

本文关键字:char 转换 Integer CryptoPP      更新时间:2023-10-16

我想将myVar从CryptoPP:Integer转换为char*或字符串:代码如下:

CryptoPP::Integer myVar = pubKey.ApplyFunction(m);
std::cout << "result: " << std::hex << myVar<< std::endl;

我一直在互联网上搜索将CryptoPP:Integer转换为char*但我没有运气找到。所以,要么CryptoPP:Integer转换为char*真的是所有的问题,要么我不太了解C++中的类型 CryptoPP:Integer.

有人可以帮我吗?

一种方法是使用std::stringstream,除了它明确支持您的问题所暗示的<<之外,对CryptoPP::Integer了解更多

std::stringstream ss;
ss << std::hex /*if required*/ << myVar;

使用std::string s = ss.str();提取底层std::string。然后,可以使用 s.c_str() 访问const char*缓冲区,只要s在范围内。一旦你调用并依赖c_str()的结果,就不要以任何方式改变s,因为这样做的行为以及随后依赖该结果的行为是不确定的。

有更整洁的C++11解决方案,但这需要您(和我(了解有关该类型的更多信息。

带 Boost:

boost::lexical_cast<std::string>(myVar);

C++98:

std::ostringstream stream;
stream << myVar;
stream.str();

几种不同的方法可以做到这一点,具体取决于您想要什么。 在这种情况下,char*没有提供足够的信息。

以下是使用插入运算符时获得的内容:

byte buff[] = { 'H', 'e', 'l', 'l', 'o' };
CryptoPP::Integer n(buff, sizeof(buff));
cout << "Oct: " << std::oct << n << endl;
cout << "Dec: " << std::dec << n << endl;
cout << "Hex: " << std::hex << n << endl;

这导致:

$ ./cryptopp-test.exe
Oct: 4414533066157o
Dec: 310939249775.
Hex: 48656c6c6fh

但是,如果您想获取原始字符串"hello"(re:您的原始 RSA 项目(:

byte buff[] = { 'H', 'e', 'l', 'l', 'o' };
CryptoPP::Integer n(buff, sizeof(buff));
size_t len = n.MinEncodedSize();
string str;
str.resize(len);
n.Encode((byte *)str.data(), str.size(), Integer::UNSIGNED);
cout << "Str: " << str << endl;

这导致:

$ ./cryptopp-test.exe
Str: Hello

但是,如果您只想在 Integer 中使用字符串,则:

Integer i("11111111111111111111");    
ostringstream oss;
oss << i;    
string str = oss.str();
cout << str << endl;

这导致:

$ ./cryptopp-test.exe
1111111111111111111.

如果CryptoPP::Integer可以发送到像std::cout这样的输出流(正如您的代码所建议的那样(,那么您可以使用std::ostringstream

#include <sstream>  // For std::ostringstream
....
std::string ToString(const CryptoPP::Integer& n)
{
    // Send the CryptoPP::Integer to the output stream string
    std::ostringstream os;
    os << n;    
    // or, if required:
    //     os << std::hex << n;  
    // Convert the stream to std::string
    return os.str();
}

然后,一旦您有了std::string实例,您就可以使用 std::string::c_str() 将其转换为 const char*
(但我认为在C++代码中,您应该使用像 std::string 这样的安全字符串类,而不是原始的 C 样式字符指针(。



附言我假设CryptoPP::Integer对于int来说是一个微不足道的 typedef.
如果要将int转换为std::string,那么您可能只想使用C++11的std::to_string()