2016-08-23 95 views
1

我有一個基於crypto ++例子(但使用硬編碼密鑰和iv)的方法,其中我加密和解密了一個字符串,工作正常。現在,當我註釋掉加密代碼並將密文設置爲從加密部分接收到的輸出時,我只得到廢話,而不是我開始使用的字符串。這裏是我的代碼(帶註釋的加密部分):AES解密只在Crypto ++中

byte iv[CryptoPP::AES::BLOCKSIZE]; 
byte key[CryptoPP::AES::MAX_KEYLENGTH]; 
std::string strKey = "F5C3DD6EA4F2AE1713F4B9B21FD0011CCECB5CA8858F313B5EA3E85CD1F6E70E"; 
std::string striv = "DEA43ED679566B66FD2B5126149F34A"; 

int x = 0; 
for (unsigned int i = 0; i < strKey.length(); i += 2) { 
    std::string bytestring = strKey.substr(i, 2); 
    key[x] = (char)strtol(bytestring.c_str(), NULL, 16); 
    x++; 
} 
int y = 0; 
for (unsigned int i = 0; i < striv.length(); i += 2) { 
    std::string bytestring = striv.substr(i, 2); 
    iv[y] = (char)strtol(bytestring.c_str(), NULL, 16); 
    y++; 
} 

std::string plain = "test mode"; 
std::string cipher, encoded, recovered; 
cipher = "F190D36A0FEEF07C5B"; 

/* 
//print key 
encoded.clear(); 
CryptoPP::StringSource(key, sizeof(key), true, 
    new CryptoPP::HexEncoder(new CryptoPP::StringSink(encoded))); 
std::cout << "key: " << encoded << std::endl; 

//print iv 
encoded.clear(); 
CryptoPP::StringSource(iv, sizeof(iv), true, 
    new CryptoPP::HexEncoder(new CryptoPP::StringSink(encoded))); 
std::cout << "iv: " << encoded << std::endl; 

try 
{ 
    std::cout << "plain text: " << plain << std::endl; 

    CryptoPP::CFB_Mode<CryptoPP::AES>::Encryption en; 
    en.SetKeyWithIV(key, sizeof(key), iv); 
    CryptoPP::StringSource(plain, true, new CryptoPP::StreamTransformationFilter(en, new CryptoPP::StringSink(cipher))); 
    std::cout << "cipher: " << cipher; 
} 
catch (const std::exception& e) 
{ 
    std::cout << "CryptInit Exception: " << e.what() << std::endl; 
} 

encoded.clear(); 
CryptoPP::StringSource(cipher, true, 
    new CryptoPP::HexEncoder(new CryptoPP::StringSink(encoded))); 
std::cout << "cipher text: " << encoded << std::endl; 
//*/ 
try 
{ 
    CryptoPP::CFB_Mode<CryptoPP::AES>::Decryption de; 
    de.SetKeyWithIV(key, sizeof(key), iv); 

    CryptoPP::StringSource s(cipher, true, 
     new CryptoPP::StreamTransformationFilter(de, new CryptoPP::StringSink(recovered))); 

    std::cout << "recovered text: " << recovered << std::endl; 

} 
catch (const std::exception& e) 
{ 
    std::cout << "CryptInit Exception: " << e.what() << std::endl; 
} 

這是我收到的輸出:├─Ö.k░®Y♫μμâƒ├v

的再生用在這裏是所需要的,包括:

#include <cryptopp\aes.h> 
#include <cryptopp\filters.h> 
#include <cryptopp\modes.h> 
#include <cryptopp\hex.h> 
#include <cryptopp\cryptlib.h> 

回答

1
cipher = "F190D36A0FEEF07C5B"; 

和:

CryptoPP::StringSource s(cipher, true, 
    new CryptoPP::StreamTransformationFilter(de, new CryptoPP::StringSink(recovered))); 

它看起來像你試圖解密一個十六進制編碼的字符串。您可能需要通過HexDecoder運行密文。也許是這樣的:

StringSource s(cipher, true, 
    new HexDecoder(
     new StreamTransformationFilter(de, new StringSink(recovered)))); 
+0

現在看來很明顯:)謝謝 – Paul