【问题标题】:SecByteBlock to string conversion errorsSecByteBlock 到字符串的转换错误
【发布时间】:2015-09-08 13:49:31
【问题描述】:

我必须在一个数据包中发送一个随机生成的数字 (rng),因此必须转换一个 SecByteBlock。我使用libcrafterrng 数组放入RawLayer 数据包中。

我关注了this answer;但它给我一个无效转换错误。

这是我使用的代码:

AutoSeededRandomPool prng;
SecByteBlock rng1;
prng.GenerateBlock( rng1, rng1.size() );

string rng1_str(reinterpret_cast<char const*>(rng1));

std::string rng1_str = std::string(rng1.data(), rng1.size());

Crafter::RawLayer number(rng1_str);

这两个想法都不行,都给我:

error: invalid conversion from ‘CryptoPP::AllocatorWithCleanup<unsigned char>::pointer {aka unsigned char*}’
to ‘const char*’ [-fpermissive]
std::string rng1_str = std::string(rng1.data(), rng1.size());

由于RawLayer 接受std::stringconst byte* 作为构造函数,我想将SecBlockByte 转换为这两种格式之一...

【问题讨论】:

  • 尝试再次阅读错误消息,它会告诉您传递给std::string 构造函数的内容,以及构造函数所期望的内容。它们之间的差异非常小,可以通过简单的reinterpret_cast 合理地解决。然而,更大的问题是您将如何使用 字符串对象。您会尝试将其用作文本吗?那么您可能会遇到问题,因为数据很可能不是文本。
  • 我认为它需要unsigned char *,但我试图用它重新解释演员阵容,但它也不起作用......
  • 错误信息说你尝试传递unsigned char *,而构造函数需要const char *。尝试投射到char*
  • 也没有用。我也尝试投到unsigned char...
  • 现在你正在做一些不同的。问题中的错误信息明确指出unsigned char *,即一个指针

标签: c++ crypto++ libcrafter


【解决方案1】:

PRNG 的输出可能具有嵌入的 NULL,因此您无法使用常规的 C 字符串操作对其数据进行操作。这意味着第一个陈述可能是错误的。

string rng1_str(reinterpret_cast<char const*>(rng1));

std::string rng1_str = std::string(rng1.data(), rng1.size());

我不确定你对第二个语句做了什么,但它需要像第一个语句一样强制转换(你可以取消赋值):

std::string rng1_str(reinterpret_cast<const char*>(rng1.data()), rng1.size());

既然你说你RawLayer接受std::stringconst byte*作为构造函数”,你可以试试:

SecByteBlock rng(16);
prng.GenerateBlock( rng, rng.size() );

Crafter::RawLayer number( rng.data(), rng.size() );

另外,一定要调整SecByteBlock 的大小。 one 的原始声明是一个大小为 0 的数组,其中有 no 内存块支持它。也就是说,rng.size() 将是 0,只有以下内容:

SecByteBlock rng;

您还可以执行以下操作:

SecByteBlock rng;
// Make it 16-bytes in size, memory uninitialized
rng.New(16);

或者:

SecByteBlock rng;
// Make it 16-bytes in size, memory initialized to 0
rng.CleanNew(16);

如果你想真正花哨并避免内存块的运行时分配,那么使用FixedSizeSecBlock

FixedSizeSecBlock<byte, 16> rng;

但这是一种更先进的技术,所以不要陷入困境。


我发现 C/C++ 不愿意在 signed charunsigned char 之间自动转换非常烦人,因为它对我来说只是 8 位二进制数据(我理解语言规则的必要性)。但我认为我需要reinterpret_cast 而不是static_cast,这很荒谬。

【讨论】:

    【解决方案2】:

    由于目标是将SecByteBlock 放入Crafter::RawLayer,我只需将其转换为const byte*...

    下面这几行就可以了。

    SecByteBlock rng1;
    prng.GenerateBlock( rng1, rng1.size() );
    
    Crafter::RawLayer number(reinterpret_cast<const byte*>(rng1.data()), rng1.size());
    

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 1970-01-01
      • 2014-11-26
      • 2017-12-02
      • 2012-07-21
      • 2015-02-26
      • 2012-07-15
      • 2014-02-27
      • 1970-01-01
      相关资源
      最近更新 更多