【问题标题】:What is wrong with this sha 256 function?这个 sha 256 函数有什么问题?
【发布时间】:2016-04-11 14:16:31
【问题描述】:

我开始使用crypto++ lib,也许我有一些误解。

我不明白为什么下面的代码会产生错误的 sha 256

# include <string>
# include <iostream>
# include "cryptopp/cryptlib.h"
# include <cryptopp/sha.h>
# include <cryptopp/hex.h>

using namespace std;

string sha256_hex(const string & str)
{
  byte digest[CryptoPP::SHA256::DIGESTSIZE];
  CryptoPP::SHA256().CalculateDigest(digest, (byte*) &str[0], str.size());

  string ret;
  CryptoPP::HexEncoder encoder;
  encoder.Attach(new CryptoPP::StringSink(ret));
  encoder.Put(digest, sizeof(digest));
  encoder.MessageEnd();

  return ret;
}

int main(int argc, char *argv[])
{
  auto sha256 = sha256_hex(argv[1]);
  cout << "str     = " << argv[1] << endl
       << "sha 256 = " << sha256_hex(sha256) << endl;

  return 0;
}

以下命令

./test-sha256 hello

产生以下输出

str     = hello
sha 256 = DD9F20FF4F1DD817C567DE6C16915DC0A731A4DF51088F55CEF4CD2F89CF9620

但是根据这个在线计算器enter link description here"hello" 的正确 sha 256 应该是 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

所以我的问题是我做错了什么?

我还有一个问题:应该如何以及何时释放StringSink 对象使用的内存?

提前致谢

【问题讨论】:

  • 嗨@lrleon 我正面临这种错误 --> 错误:未定义引用'vtable for CryptoPP::SHA256' 我想用cryptopp生成SHA256,你能帮帮我吗?跨度>

标签: c++ sha crypto++


【解决方案1】:

你这里不是计算散列的散列吗?你调用sha256_hex 两次,一次以argv[1] 作为参数,一次以sha256 本身作为参数。

【讨论】:

    【解决方案2】:

    关于问题的第二部分:

    在 Crypto++ Pipelining system 中,过滤器和接收器归它们所附加的对象所有。它们会被该对象的析构函数自动删除。

    来自ReadMe.txt中的“重要使用说明”:

    如果 A 的构造函数采用指向对象 B 的指针(除了基本类型,如 int 和 char),则 A 拥有 B 并将在 A 销毁时删除 B。如果 A 的构造函数引用对象 B,则调用者保留 B 的所有权,并且在 A 不再需要它之前不应销毁它。

    【讨论】:

      【解决方案3】:

      很可能,我发现问题出在这里:

      CryptoPP::SHA256().CalculateDigest(digest, (byte*) &str[0], str.size());
      

      你最好通过str.c_str()。使用调试器查看到底传递了什么 - 它是否转换为 hello

      【讨论】:

      • @lrleon 是的,使用调试器和.或添加打印语句,这是开发代码的一部分。所以不是你的调试器,它是你完成基本调试后的最后帮助。
      • &amp;str[0]str.c_str() 返回的值有何不同?当然,C++ 标准并不能保证这一点,但是您是否遇到过那些表达式在语义上不相同的实现?我不知道,为什么这个“答案”得到了投票......
      • &amp;str[0] 是正确的,因为它提供了一个非常量指针。 str.c_str() 提供了一个 cont-pointer,写入它是未定义的行为。
      猜你喜欢
      • 2015-04-14
      • 1970-01-01
      • 2017-03-26
      • 2014-06-29
      • 2011-02-13
      • 2011-04-24
      • 2011-08-26
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多