我開始使用crypto ++ lib,也許我有一些誤解。這個sha 256函數有什麼問題?
我不明白爲什麼下面的代碼會產生不好的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,正確的sha 256爲"hello"
w應該是2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
。
所以我的問題是我做錯了什麼?
我還有一個問題:StringSink
對象使用的內存應該何時釋放?
在此先感謝
omg!我意識到我的錯誤;抱歉。感謝你和其他人 – lrleon