I use Crypto++ in C++ to encrypt a string. Now I want to decrypt this ciphertext with C# but it doesn't work.
My C++ Code to encrypted the string is as follow:
string encrypt(string data)
{
// Key and IV setup
std::string key = "0123456789abcdef";
std::string iv = "aaaaaaaaaaaaaaaa";
std::string plaintext = data;
std::string ciphertext;
// Create Cipher Text
CryptoPP::AES::Encryption aesEncryption((byte *)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, (byte *)iv.c_str());
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(ciphertext));
stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.length() + 1);
stfEncryptor.MessageEnd();
return ciphertext;
}
To decrypt the code in C++ I can use this code
CryptoPP::AES::Decryption aesDecryption((byte *)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, (byte *)iv.c_str() );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( result_string.c_str() ), result_string.size() );
stfDecryptor.MessageEnd()
But I need to decrypt the code in a C# application and therefor I use this methode:
static string Decrypt(byte[] cipherText)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
byte[] Key = GetBytes(ConfigurationManager.AppSettings["aes_key"]);
byte[] IV = GetBytes(ConfigurationManager.AppSettings["aes_iv"]);
// Declare the string used to hold the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
If I try to decrypt the ciphertext, I get the message, that the specified initialization vector does not match the block size for this algorithm.
I do not know why this doesn't work and I hope that someone can help me.