这个sha 256功能有什么问题?

lrl*_*eon 1 c++ sha crypto++

我开始使用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;
}
Run Code Online (Sandbox Code Playgroud)

以下命令

./test-sha256 hello
Run Code Online (Sandbox Code Playgroud)

产生以下输出

str     = hello
sha 256 = DD9F20FF4F1DD817C567DE6C16915DC0A731A4DF51088F55CEF4CD2F89CF9620
Run Code Online (Sandbox Code Playgroud)

但是根据这个在线计算器在这里输入链接描述,正确的sha 256 "hello"将是2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824.

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

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

提前致谢

Ton*_*nyK 5

你不是在这里计算哈希的哈希值吗?你调用sha256_hex两次,一次用argv[1]as参数,一次用sha256自己作为参数.