2013-05-10 52 views
0

我正在嘗試使用cryptopp中的AES編寫2個不同的函數來加密和解密數據。我想將密文作爲參數傳遞給解密函數。但是在解密函數中,它接收到一些特殊符號,因此密文&因此不能正確解密。請幫忙。傳遞AES密文作爲參數

// -- AES encryption function ---------- 
void Security_packetAgent::encryption(char out[]) 
{ 
    std::string plaintext = out; 
    std::string ciphertext = ""; 

    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH); 
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv); 

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(ciphertext)); 
    stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.length() + 1); 
    stfEncryptor.MessageEnd(); 

    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl; 

    for(int i = 0; i < ciphertext.size(); i++) 
    { 
     std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " "; 
    } 

    std::cout<<"\nMessage encrypted ..."; 
    std::cout << std::endl << std::endl; 
    sprintf(out, "%s", ciphertext.c_str()); 
    printf("Final Data: %s : %s ", out, reinterpret_cast<const unsigned char*>(ciphertext.c_str())); 
} 

// ---- AES decryption ------------------ 
void Security_packetAgent::decryption(char out[]) 
{ 
    cout<<"\nCipher recieved: "<<out; 
    std::cout<<"\nEntered decryption .."; 
    std::string ciphertext = out; 
    std::string decryptedtext; 

    cout<<"\nCipher recieved: "<<reinterpret_cast<const unsigned char*>(ciphertext.c_str()); 
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH); 
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv); 

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decryptedtext)); 
    stfDecryptor.Put(reinterpret_cast<const unsigned char*>(ciphertext.c_str()), ciphertext.size()); 
    stfDecryptor.MessageEnd(); 

    std::cout << "Decrypted Text: " << std::endl; 
    std::cout << decryptedtext; 
    std::cout << std::endl << std::endl;  
} 
+0

你能提供一個代碼示例重現問題嗎?此外,請顯示錯誤是什麼以及您預期的輸出是什麼。 – 2013-05-10 14:20:43

+0

dauphic回答了你的問題。你可以考慮給予他答案的禮貌。 – jww 2013-10-02 05:27:46

回答

3

你不應該構建std::stringchar*的,如果char*指向的東西是不是一個文本字符串,如加密的數據。

std::string ciphertext = out; 

ciphertext的建設將會因爲它達到0字節儘快停止從out複製。相反,您還需要傳遞加密數據的長度並使用std::string(const char* data, size_t size)構造函數。

std::string ciphertext(out, outSize); 

或者,您也可以使用構造函數來開始和結束迭代器。