Answer the question
In order to leave comments, you need to log in
AES decryption?
It is necessary to implement AES encryption in the application. Actually, we go into the documentation, copy the code, and it does not work. To be precise, decryption fails due to an error
System.Security.Cryptography.CryptographicException The padding is invalid and cannot be removed.(see code). What could be the problem and how to fix it?
//Всё нормально работает. Возвращается какой-то новый массив байт.
byte[] EncryptAes(byte[] data, byte[] key, byte[] initVector)
{
using (var aes = new AesManaged())
{
aes.Key = key;
aes.IV = initVector;
var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (var encryptedStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
return encryptedStream.ToArray();
}
}
}
}
//Ошибка на самом последнем шаге
byte[] DecryptAes(byte[] data, byte[] key, byte[] initVector)
{
using (var aes = new AesManaged())
{
aes.Key = key;
aes.IV = initVector;
var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (var dataStream = new MemoryStream(data))
{
using (var cryptoStream = new CryptoStream(dataStream, decryptor, CryptoStreamMode.Read))
{
using (var decryptedStream = new MemoryStream())
{
//System.Security.Cryptography.CryptographicException Заполнение неверно и не может быть удалено.
cryptoStream.CopyTo(decryptedStream);
return decryptedStream.ToArray();
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
While cryptoStream has not finished its work, it is pointless to read the data.
Correct encryption option:
using (var encryptedStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
}
return encryptedStream.ToArray();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question