如何轻松应用Crypto ++哈希函数?

时间:2015-04-06 08:18:28

标签: c++ windows md5 sha1 crypto++

有人可以帮助我如何轻松使用Crypto ++库中的哈希函数? 我尝试将这些代码用于SHA1和MD5。我在线上有很多错误StringSink。错误如下:

undefined reference to `CryptoPP::StringSinkTemplate::StringSinkTemplate(std::string&)'

感谢您的帮助。

 // SHA
CryptoPP::SHA1 sha1;
std::string source = "Hello";
std::string hash = "";
CryptoPP::StringSource(source, true, new CryptoPP::HashFilter(sha1, new CryptoPP::HexEncoder(new CryptoPP::StringSink(hash))));
std::cout << hash;

// MD5
CryptoPP::MD5 hash;
byte digest[ CryptoPP::MD5::DIGESTSIZE ];
std::string message = "abcdefghijklmnopqrstuvwxyz";

hash.CalculateDigest( digest, (byte*) message.c_str(), message.length() );

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

std::cout << output << std::endl;

1 个答案:

答案 0 :(得分:2)

  

我在线上有很多错误,其中有StringSink

StringSink这一行看起来不错。您应该提供您遇到的确切错误。


  

StringSink的错误是:对CryptoPP :: StringSinkTemplate :: StringSinkTemplate(std :: string&amp;)&#39;

的未定义引用

根据您提供的其他信息,请参阅Building and linking test code for Crypto++


  

如何轻松应用Crypto ++哈希函数?

以下是来自ChannelSwitch课程的Crypto ++ wiki。由于您需要MD5,因此需要#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1,然后#include <cryptopp/md5.h>。之后,您可以在Weak::MD5中找到MD5。

string message = "Now is the time for all good men to come to the aide of their country";
if(argc == 2 && argv[1] != NULL)
    message = string(argv[1]);

string s1, s2, s3, s4;
SHA1 sha1; SHA224 sha224; SHA256 sha256; SHA512 sha512;

HashFilter f1(sha1, new HexEncoder(new StringSink(s1)));
HashFilter f2(sha224, new HexEncoder(new StringSink(s2)));
HashFilter f3(sha256, new HexEncoder(new StringSink(s3)));
HashFilter f4(sha512, new HexEncoder(new StringSink(s4)));

ChannelSwitch cs;
cs.AddDefaultRoute(f1);
cs.AddDefaultRoute(f2);
cs.AddDefaultRoute(f3);
cs.AddDefaultRoute(f4);

StringSource ss(message, true /*pumpAll*/, new Redirector(cs));

cout << Message: " << message << endl;
cout << "SHA-1: " << s1 << endl;
cout << "SHA-224: " << s2 << endl;
cout << "SHA-256: " << s3 << endl;
cout << "SHA-512: " << s4 << endl;

程序的运行产生如下所示的结果:

$ ./cryptopp-test.exe password
Message: password
SHA-1: 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
SHA-224: D63DC919E201D7BC4C825630D2CF25FDC93D4B2F0D46706D29038D01
SHA-256: 5E884898DA28047151D0E56F8DC6292773603D0D6AABBDD62A11EF721D1542D8
SHA-512: B109F3BBBC244EB82441917ED06D618B9008DD09B3BEFD1B5E07394C706A8BB9
         80B1D7785E5976EC049B46DF5F1326AF5A2EA6D103FD07C95385FFAB0CACBC86