2013-02-20 56 views
0

我正在使用crypto ++来加密和解密字符串。代码如下所示。 该代码加密用户名和密码。但我不知道如何将其解密为一个字符串。将加密的SHA256代码解密为字符串的代码是什么? 任何人都可以帮助我。将加密的SHA256代码解密为crypto ++中的字符串的代码

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

int main() 
{ 
    CryptoPP::SHA256 hash; 
    byte digest[CryptoPP::SHA256::DIGESTSIZE]; 
    std::string username, password, salt, output; 
    std::cout << "Enter username: "; 
    std::getline(std::cin,username); 
    std::cout << std::endl << "Enter password: "; 
    std::getline(std::cin,password); 
    salt = username + password; 

    hash.CalculateDigest(digest,(const byte *)salt.c_str(),salt.size()); 

    CryptoPP::HexEncoder encoder; 
    CryptoPP::StringSink *SS = new CryptoPP::StringSink(output); 
    encoder.Attach(SS); 
    encoder.Put(digest,sizeof(digest)); 
    encoder.MessageEnd(); 

    std::cout << "The username/password salted hash is => " << output << std::endl; 
    return 0; 
} 
+2

请阅读http://en.wikipedia.org/wiki/Cryptographic_hash_function - 你所要求的是不可行*通过设计*。 – 2013-02-20 17:06:05

+0

另请参阅[pigeonhole原理](https://en.wikipedia.org/wiki/Pigeonhole_principle) – Praetorian 2013-02-20 17:09:52

回答

3

这个代码不执行加密,作为评论者已经指出的那样,但散列。中心区别在于,按设计哈希是不可逆的廉价。这在密码应用程序中很重要,因为您明确不想以任何可访问的形式存储用户的密码,但只能检查它们。

所以,简而言之:你不能“解密”你的散列。

当你想检查一个提供的密码的正确性时,你再次散列它,就像在你的代码中,并将散列与原始密码的散列进行比较。

+0

“...并将散列与原始密码的散列进行比较” - 请务必使用Crypto ++的“ VerifyBufsEqual'来避免比较中的定时攻击。 – jww 2014-01-28 03:38:38