c++ - 如何将 SecByteBlock 转换为字符串?

标签 c++ security aes crypto++

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

我想使用带有静态 key 和动态 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;

上面的代码应该:

  1. 从文件中加载 key ;

  2. 创建 iv;

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

  4. 将 iv 与加密的用户数据访问连接起来以创建“ token ”;

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

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

我希望有人能帮助我。

最佳答案

I'm having a problem trying to convert SecByteBlock to string

如果问题来自 SecByteBlock 的转换及其 byte数组到 std::string及其 char数组,那么你应该:

SecByteBlock iv;
...

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

或者,

SecByteBlock iv;
...

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

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

SecByteBlock iv;
...

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

std::string userAccess;
...

token += userAccess;

您可能遇到的另一个问题是 stringSecByteBlock .你应该这样做:

std::string str;
...

// C-style cast
SecByteBlock sbb((const byte*)str.data(), str.size());

或者:

std::string str;
...

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

关于c++ - 如何将 SecByteBlock 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929531/

相关文章:

c++ - Apache拦截一些http请求

c++ - 如何获取指向原始数据的 std::vector 指针?

php - 带有 for 循环的安全 PDO mySQL SELECT 语句

node.js - 在 Coldfusion 中加密,在 Node.js 中解密

android - 在 iOS 上解密 android AES 示例

c++ - 如何生成丢失的 #include 文件列表

android - 是否可以保护加密 key 不被 iOS/Android 中的恶意应用程序读取?

php - 在同一主站点上运行多个子站点时要采取的安全预防措施

java - 如何在Java中使用AES算法解密加密的字符串?

c++ - 散列数组的排列