AES заполнение и запись зашифрованного текста в файл на диске
У меня есть строка, которую я шифрую с помощью следующего метода в C ++ с использованием Crypto ++:
std::ifstream t(filename); //File to be encrypt
std::stringstream buffer;
buffer << t.rdbuf();
ofstream combined_file2(filename2); //Encrypted file
combined_file2 << encrypt(buffer.str());
string encrypt(string data)
{
// Key and IV setup
std::string key = "0123456789abcdef";
std::string iv = "aaaaaaaaaaaaaaaa";
//Alternative
//byte key[CryptoPP::AES::DEFAULT_KEYLENGTH], iv[CryptoPP::AES::BLOCKSIZE];
//memset(key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH);
//memset(iv, 0x00, CryptoPP::AES::BLOCKSIZE);
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());
//Alternative
//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();
return ciphertext;
}
Когда я пытаюсь расшифровать файл в моем приложении C #, я получаю сообщение о том, что длина данных неверна. Я думаю, что длина массива байтов не кратна 16, поэтому я получаю ошибку. Я пытаюсь использовать отступы, но это не работает правильно.
Вот как я расшифровываю файл:
string plaintext = Decrypt(File.ReadAllBytes(path));
private 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;
//for testing
rijAlg.IV = new byte[] { 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97 };
// 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;
}
Как я могу решить проблему? Есть ли какая-либо функция для заполнения, или, возможно, заполнение является неправильным способом?