I know there is plenty of this questions with answers around but I have spent hours and hours googleing and have tried all suggestions that I have found.
I download a file and I want to store it encrypted in the isolated storage. This is how I store it:
using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
byte[] bytesInStream = new byte[args.Result.Length];
args.Result.Read(bytesInStream, 0, bytesInStream.Length);
var aes = new AesManaged
{
Key = GetBytes("aaaaaaaa"),
IV = GetBytes("bbbbbbbb")
};
byte[] encryptedArray;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(bytesInStream, 0, bytesInStream.Length);
cryptoStream.FlushFinalBlock();
encryptedArray = memoryStream.ToArray();
}
}
fs.Write(encryptedArray, 0, encryptedArray.Length);
fs.Flush();
}
The following code is for reading the file from isolated storage and decrypt it:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
{
var file = store.OpenFile(fileName, FileMode.Open,FileAccess.Read,FileShare.Read);
var reader = new BinaryReader(file);
var aes = new AesManaged
{
Key = GetBytes("aaaaaaaa"),
IV = GetBytes("bbbbbbbb")
};
byte[] decodedContent;
byte[] encodedContent = reader.ReadBytes(1280);
using (MemoryStream ms = new MemoryStream(encodedAudio))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
BinaryReader r= new BinaryReader(cs);
decodedContent= r.ReadBytes(encodedContent.Length);
}
}
}
When the program reaches this line: decodedContent= r.ReadBytes(encodedContent.Length); I get CryptographicException with the following message: Padding is invalid and cannot be removed.
Can anyone help me with this issue?