如何将 SecByteBlock 转换为字符串?

Pau*_*raz 4 c++ security aes crypto++

我在尝试转换SecByteBlock为字符串时遇到问题。这是我的情况:

我想使用带有静态密钥和动态 iv 的 AES 加密用户访问数据。我的代码是这样的:

AesKeyIvFactory aesKeyIvFactory;
SecByteBlock key = aesKeyIvFactory.loadKey();
SecByteBlock iv = aesKeyIvFactory.createIv();

encryptionService->encode(&userAccess, key, iv);
std::string token = std::string(iv.begin(), iv.end()) + userAccess;
Run Code Online (Sandbox Code Playgroud)

上面的代码应该是:

  1. 从文件加载密钥;

  2. 创建四;

  3. 加密(AES)用户访问数据;

  4. 将iv与加密的用户数据访问连接起来,创建一个“令牌”;

多次运行测试,有时(1 到 10 次)std::string(iv.begin(), iv.end())无法正常工作。iv 中似乎有一个“换行符”,导致转换失败。

我尝试了很多东西,但没有任何效果,而且我没有使用 C++ 的经验。

我希望有人可以帮助我。

Eri*_*sui 5

我在尝试将 SecByteBlock 转换为字符串时遇到问题

如果问题出在 fromSecByteBlock及其byte数组到 astd::string及其char数组的转换,那么您应该:

SecByteBlock iv;
...

// C-style cast
std::string token = std::string((const char*)iv.data(), iv.size()) + userAccess;
Run Code Online (Sandbox Code Playgroud)

或者,

SecByteBlock iv;
...

// C++-style cast
std::string token = std::string(reinterpret_cast<const char*>(iv.data()), iv.size()) + userAccess;
Run Code Online (Sandbox Code Playgroud)

你也可以放弃赋值,只初始化然后追加:

SecByteBlock iv;
...

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

std::string userAccess;
...

token += userAccess;
Run Code Online (Sandbox Code Playgroud)

你可能有另一个问题是stringSecByteBlock。你应该做这个:

std::string str;
...

// C-style cast
SecByteBlock sbb((const byte*)str.data(), str.size());
Run Code Online (Sandbox Code Playgroud)

或者:

std::string str;
...

// C++-style cast
SecByteBlock sbb(reinterpret_cast<const byte*>(str.data()), str.size());
Run Code Online (Sandbox Code Playgroud)