Decrypt file into memory - c#

I have function for decrypting files using Rijnadel (AES).
Looks like this:
public static bool FileDecrypt(string inputFile, string outputFile, string password)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] salt = new byte[32];
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
fsCrypt.Read(salt, 0, salt.Length);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.PKCS7;
AES.Mode = CipherMode.CFB;
CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int read;
byte[] buffer = new byte[1048576];
try
{
while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
fsOut.Write(buffer, 0, read);
}
}
catch (CryptographicException ex_CryptographicException)
{
fsOut.Close();
fsCrypt.Close();
LogWriter loger = new LogWriter("Cryptography error: " + ex_CryptographicException.ToString());
return false;
}
catch (Exception ex)
{
fsOut.Close();
fsCrypt.Close();
LogWriter loger = new LogWriter("Exception error: " + ex.ToString());
return false;
}
try
{
cs.Close();
}
catch (Exception ex)
{
fsCrypt.Close();
fsOut.Close();
LogWriter loger = new LogWriter("Error when closing Cryptostream. Error: " + ex.ToString());
return false;
}
finally
{
fsOut.Close();
fsCrypt.Close();
}
return true;
}
It decrypts the file and creates new decrypted file.
But i would like to decrypt that file and load it only into memory. Mostly xml configuration files so then i would like to read the xml configuration with xmlserializer and use it in my program and then dispose the file from memory. Is that possible? Thanks for all answers.
PS: Dont mind closing of streams in all catches. Finally block didnt work for some reason, still trying to figure that out.
//EDIT:
This is my try:
MemoryStream inMemoryCopy = new MemoryStream();
byte[] salt = new byte[32];
using (FileStream fs = File.OpenRead(inputfile))
{
fs.Read(salt, 0, salt.Length);
fs.CopyTo(inMemoryCopy);
}
byte[] bytesToBeDecrypted = inMemoryCopy.ToArray();
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.PKCS7;
AES.Mode = CipherMode.CFB;
CryptoStream cs = new CryptoStream(bytesToBeDecrypted, AES.CreateDecryptor(), CryptoStreamMode.Read);
Problem is i cannot use byte array in cryptostream. And can i somehow do that even without filestream?

You want to use XmlSerializer kinda like this to get some configuration object from stream. It doesn't matter wether the source stream is a FileStream, NetworkStream or even the CryptoStream itself. So there is no need to work with a byte buffer.
Note the following code is adapted from your code. I stripped the try catch from it to just only show the core code needed for the deserialization.
public SomeConfig ReadEncryptedConfiguration(string inputFile, string password)
{
using (var stream = CreateStream(inputFile, password))
{
var ser = new XmlSerializer(typeof(SomeConfig));
var config = (SomeConfig) ser.Deserialize(stream);
return config;
}
}
The CreateStream method will make the stream which is used and disposed in the previous part. I used another constructor to make sure that the underlying file stream is disposed when the CryptoStream is being disposed.
public CryptoStream CreateStream(string inputFile, string password)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] salt = new byte[32];
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
fsCrypt.Read(salt, 0, salt.Length);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.PKCS7;
AES.Mode = CipherMode.CFB;
return new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read, false);
}

Related

Coroutines and Asynchronous commands in Unity, Encryption and Decryption. How to make this function run asynchronosly to the rest of my code?

I am working on a project that requires encryption and decryption of downloaded files. Some of these files are quite large. I need a way to do these functions asynchronously. For some reason, this code is causing a complete slowdown on the machine when they are called. Instead of doing the task in the backend, the machine drops all tasks and freezes up while doing encryption and decryption.
Here is the code in question.
string encryptedFilePath = Path.Combine(FolderPath, SessionData.instance.email + "/", download.FileName + ".mp4");
yield return StartCoroutine(DownloadManagementPage.instance.EncryptFile(originalFile, encryptedFilePath));
DownloadManagementPage.instance.DeleteFile("TEMP.mp4");
public IEnumerator EncryptFile(string srcFilename, string destFilename)
{
Debug.LogError("Encrypting");
Debug.LogError("Source " + srcFilename);
Debug.LogError("Destination " + destFilename);
var aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
byte[] salt = Encoding.ASCII.GetBytes(SaltKey);
var key = new Rfc2898DeriveBytes(SKey, salt, Iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);
using (var dest = new FileStream(destFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (var cryptoStream = new CryptoStream(dest, transform, CryptoStreamMode.Write))
{
using (var source = new FileStream(srcFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
}
yield return null;
Debug.LogError("Done Encryption");
}
public IEnumerator DecryptFile(string srcFilename, string destFilename)
{
Debug.LogError("Decrypting");
Debug.LogError("Source " + srcFilename);
Debug.LogError("Destination " + destFilename);
var aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
byte[] salt = Encoding.ASCII.GetBytes(SaltKey);
var key = new Rfc2898DeriveBytes(SKey, salt, Iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
using (var dest = new FileStream(destFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
using (var cryptoStream = new CryptoStream(dest, transform, CryptoStreamMode.Write))
{
try
{
using (var source = new FileStream(srcFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
source.CopyTo(cryptoStream);
}
}
catch (CryptographicException exception)
{
throw new ApplicationException("Decryption failed.", exception);
}
}
}
yield return null;
Debug.LogError("Done Decryption");
}
I thought that having the code in a coroutine would work but it didn't work the same as my other coroutines. I also tried the async keywords as well as source.CopyToAsync(cryptoStream) but I have no idea how those would work in this context.
=======EDIT=======
I managed to get the Copy to Async function working
public async Task EncryptFileAndDeleteOriginal(string srcFilename, string destFilename)
{
Debug.LogError("Encrypting");
Debug.LogError("Source " + srcFilename);
Debug.LogError("Destination " + destFilename);
var aes = new AesManaged();
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
byte[] salt = Encoding.ASCII.GetBytes(SaltKey);
var key = new Rfc2898DeriveBytes(SKey, salt, Iterations);
aes.Key = key.GetBytes(aes.KeySize / 8);
aes.IV = key.GetBytes(aes.BlockSize / 8);
aes.Mode = CipherMode.CBC;
ICryptoTransform cryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV);
FileStream source = new FileStream(srcFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
FileStream dest = new FileStream(destFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None);
CryptoStream cryptoStream = new CryptoStream(dest, cryptoTransform, CryptoStreamMode.Write);
Task task = source.CopyToAsync(cryptoStream);
await task;
source.Close();
dest.Close();
Debug.LogError("Finished Encryption");
//DeleteFilePath(srcFilename);
Debug.LogError("Deleted Original");
}

Issues with Decrypt data with length and padding

I have issues to get the data decrypted and not sure what I do wrong as tried almost everything.
private static byte[] AES_Encrypt(byte[] byteArray)
{
byte[] salt = GenerateRandomSalt();
MemoryStream fsCrypt = new MemoryStream();
byte[] ms = new byte[0];
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(keyName);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
AES.Padding = PaddingMode.None;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CFB;
fsCrypt.Write(salt, 0, salt.Length);
CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write);
MemoryStream fsIn = new MemoryStream(byteArray);
byte[] buffer = new byte[1048576];
int read;
try
{
if (byteArray.Length <= buffer.Length)
cs.Write(buffer, 0, buffer.Length);
else
while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
{
cs.Write(buffer, 0, read);
}
ms = fsCrypt.ToArray();
fsIn.Close();
}
catch (Exception ex)
{
}
finally
{
try
{
cs.Close();
fsCrypt.Close();
}
catch (Exception err)
{
}
}
string response = Encoding.UTF8.GetString(ms.ToArray());
return ms.ToArray();
}
private static byte[] AES_Decrypt(byte[] byteArray)
{
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(keyName);
byte[] salt = new byte[32];
byte[] ms = new byte[0];
MemoryStream fsCrypt = new MemoryStream(byteArray);
fsCrypt.Read(salt, 0, salt.Length);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.None;
AES.Mode = CipherMode.CFB;
MemoryStream fsOut = new MemoryStream();
CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);
int read;
byte[] buffer = new byte[1048576];
try
{
string response = Encoding.UTF8.GetString(byteArray);
if (byteArray.Length <= buffer.Length)
{
while ((read = cs.Read(byteArray, 0, byteArray.Length)) > 0)
{
fsOut.Read(byteArray, 0, read);
}
string vresponse = Encoding.UTF8.GetString(fsOut.ToArray());
}
else
while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
{
fsOut.Write(buffer, 0, read);
}
}
catch (System.Security.Cryptography.CryptographicException ex_CryptographicException)
{
}
catch (Exception ex)
{
}
try
{
cs.Close();
}
catch (Exception ex)
{
}
finally
{
fsOut.Close();
//fsCrypt.Close();
}
return ms.ToArray();
}
My data is sometimes shorter than the 1MB being used so I want to catch th shorter data to use less byte, however its for later concern.
The data I send to the decryptor is using the same static keys now and the inbound encrypted data is identical as the out type encrypted data.
If I put the PaddingMode.None; to PaddingMode.PKCS7 it gives me a mapping error, which comes as I assume in the shorter string than the buffer actually is, so as far my assumations this is correct, so I use for now 'none'.
I have looked to lots of links as:
https://stackoverflow.com/questions/31486028/decrypting-cryptostream-into-memorystream
https://stackoverflow.com/questions/31486028/decrypting-cryptostream-into-memorystream
https://stackoverflow.com/questions/8583112/padding-is-invalid-and-cannot-be-removed
[Encrypt to memory stream, pass it to file stream
[AES encryption on large files
The problem I cant figure out why the encrypted data wont decrypt as should.
100% sure I do something not correct but cant figure out what, any help would be appriciated.
I have changes some code and tried different options, now using this but on both option I get errors.
using (var msi = new MemoryStream())
{
try
{
using (var cs = new CryptoStream(msi, aesAlg.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytes, 0, bytes.Length); //Option 1, gives error, length is invalid of byte array
do //Option 2, give error, Padding is invalid and cannot be removed.
{
count = msi.Read(bytes, 0, blockSizeBytes);
offset += count;
cs.Write(data, 0, count);
}
while (count > 0);
}
var plainText = msi.ToArray();
var text = Encoding.Unicode.GetString(plainText);
}
catch (Exception e)
{
}
//return text;
}
I checked the data length and using Unicode encoding it is 4258 and the bytes are 8516, which should be from my point of view as using Unicode.
Not sure if using the right encoding as found this https://stackoverflow.com/a/10380166/3763117 and can do without but gives same lengthas unicode. little stucked on this any help with some samples would be appriciated.

Padding is invalid and cannot be removed. c# decrypt AES Rijndael, AES Managed

I am trying to encrypt and decrypt the file. Using AES methods in a MVC web application. I am able to encrypt file and decrypt only once. If I try for second time it gives me "Padding is invalid and cannot be removed error."
I have tried almost every combination with different properties of AES properties.
I have tried using statement for disposing the objects.
I have tried using FlushFinalBlock() after CryptoStream write.
I have tried with using AES.Padding to Zero (gives me no error but the file doesnt decrypt ), AES.Padding to None gives me error('Length of the data to encrypt is invalid.'). AES.Padding to PKCS7 gives me error (padding is invalid.)
Please find my code below.
public class EncryptionDecryption
{
// Call this function to remove the key from memory after use for security
[DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
/// <summary>
/// Creates a random salt that will be used to encrypt your file. This method is required on FileEncrypt.
/// </summary>
/// <returns></returns>
public static byte[] GenerateRandomSalt()
{
byte[] data = new byte[32];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
// Ten iterations.
for (int i = 0; i < 10; i++)
{
// Fill buffer.
rng.GetBytes(data);
}
}
return data;
}
/// <summary>
/// Encrypts a file from its path and a plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="password"></param>
public static void FileEncrypt(string inputFile, string password)
{
//generate random salt
byte[] salt = GenerateRandomSalt();
//create output file name
using (FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create))
{
//convert password string to byte arrray
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
//Set Rijndael symmetric encryption algorithm
using (AesManaged AES = new AesManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
AES.Padding = PaddingMode.None;
//http://stackoverflow.com/questions/2659214/why-do-i-need-to-use-the-rfc2898derivebytes-class-in-net-instead-of-directly
//"What it does is repeatedly hash the user password along with the salt." High iteration counts.
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
//Cipher modes: http://security.stackexchange.com/questions/52665/which-is-the-best-cipher-mode-and-padding-mode-for-aes-encryption
AES.Mode = CipherMode.CBC;
// write salt to the begining of the output file, so in this case can be random every time
fsCrypt.Write(salt, 0, salt.Length);
using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
//create a buffer (1mb) so only this amount will allocate in the memory and not the whole file
byte[] buffer = new byte[1048576];
int read;
try
{
while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
{
// Application.DoEvents(); // -> for responsive GUI, using Task will be better!
cs.Write(buffer, 0, read);
}
// Close up
fsIn.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
cs.Close();
fsCrypt.Close();
}
}
}
}
}
}
/// <summary>
/// Decrypts an encrypted file with the FileEncrypt method through its path and the plain password.
/// </summary>
/// <param name="inputFile"></param>
/// <param name="outputFile"></param>
/// <param name="password"></param>
public static void FileDecrypt(string inputFile, string outputFile, string password)
{
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
byte[] salt = new byte[32];
using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
{
fsCrypt.Read(salt, 0, salt.Length);
using (AesManaged AES = new AesManaged ())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.PKCS7;
AES.Mode = CipherMode.CBC;
using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read))
{
using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
{
int read;
byte[] buffer = new byte[1048576];
try
{
while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
{
//Application.DoEvents();
fsOut.Write(buffer, 0, read);
//if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
}
}
catch (CryptographicException ex_CryptographicException)
{
Console.WriteLine("CryptographicException error: " + ex_CryptographicException.Message);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
try
{
cs.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error by closing CryptoStream: " + ex.Message);
}
finally
{
fsOut.Close();
fsCrypt.Close();
}
}
}
}
}
}
}
calling methods
Encryption
string password = "ThePasswordToDecryptAndEncryptTheFile";
// For additional security Pin the password of your files
GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);
// Encrypt the file
EncryptionDecryption.FileEncrypt(inputFilePath, password);
// To increase the security of the encryption, delete the given password from the memory !
EncryptionDecryption.ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);
gch.Free();
Decryption
GCHandle gch2 = GCHandle.Alloc(password, GCHandleType.Pinned);
// Decrypt the file
EncryptionDecryption.FileDecrypt(encryptedFilePath, outputPath, password);
// To increase the security of the decryption, delete the used password from the memory !
EncryptionDecryption.ZeroMemory(gch2.AddrOfPinnedObject(), password.Length * 2);
gch2.Free();
I got it resolved by removing all the AES properties to default and just keeping few. Find the code below. Specially the padding fields.
public static void FileEncrypt(string inputFile, string outputFile, string password, byte[] salt)
{
try
{
using (RijndaelManaged AES = new RijndaelManaged())
{
byte[] passwordBytes = ASCIIEncoding.UTF8.GetBytes(password);
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
/* This is for demostrating purposes only.
* Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/
//byte[] IV = ASCIIEncoding.UTF8.GetBytes(skey);
using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
{
using (ICryptoTransform encryptor = AES.CreateEncryptor(AES.Key, AES.IV))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
int data;
while ((data = fsIn.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static void FileDecrypt(string inputFile, string outputFile, string password, byte[] salt)
{
try
{
using (RijndaelManaged AES = new RijndaelManaged())
{
//byte[] key = ASCIIEncoding.UTF8.GetBytes(password);
/* This is for demostrating purposes only.
* Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/
//byte[] IV = ASCIIEncoding.UTF8.GetBytes(password);
byte[] passwordBytes = ASCIIEncoding.UTF8.GetBytes(password);
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
{
using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
{
using (ICryptoTransform decryptor = AES.CreateDecryptor(AES.Key, AES.IV))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read))
{
int data;
while ((data = cs.ReadByte()) != -1)
{
fsOut.WriteByte((byte)data);
}
if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
// failed to decrypt file
}
}
}

Encrypt/Decrypt Stream in C# using RijndaelManaged

I am trying to encrypt a Generic Stream in C#. Although the program has no problems, the encryption and decryption return blank when converted to strings. Any help is appreciated.
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 10000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 10000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}
private void Encrypt(Stream input, Stream output, String password)
{
input.Position = 0;
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
using (var stream = new MemoryStream())
{
byte[] buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, bytesRead);
var tmp = AES_Encrypt(buffer, passwordBytes);
output.Write(tmp, 0, tmp.Length);
}
}
}
private void Decrypt(Stream input, Stream output, String password)
{
input.Position = 0;
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
using (var stream = new MemoryStream())
{
byte[] buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, bytesRead);
var tmp = AES_Decrypt(buffer, passwordBytes);
output.Write(tmp, 0, tmp.Length);
}
}
}
static void Main(string[] args)
{
Program obj = new Program();
var message = new MemoryStream();
var cipher = new MemoryStream();
string tmp = "This is a test if the encryption is working!";
StreamWriter sw = new StreamWriter(message);
sw.Write(tmp);
obj.Encrypt(message, cipher, "password");
cipher.Position = 0;
message = new MemoryStream();
obj.Decrypt(cipher, message, "password");
using (var memoryStream = new MemoryStream())
{
message.CopyTo(memoryStream);
var bytesdecrypt = memoryStream.ToArray();
string result = Encoding.UTF8.GetString(bytesdecrypt);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
}
The problem is probably when I am reading and writing from and to the streams.
There are many problems with this code.
The reason why nothing is decrypted is because you forgot to reset the message stream before doing message.CopyTo(memoryStream), because CopyTo works from the current position and you haven't changed the position after decryption.
You could reset it with
message.Position = 0;
If arbitrary data is encrypted, AES with some mode of operation like CBC is not enough. We generally need some kind of padding scheme. In C# the default scheme is PKCS#7 padding. Unambiguous padding is always added even when the plaintext is already a multiple of the block size. In those cases a full padding block is added.
Now the problem is that you're reading 2048 byte chunks during encryption and decryption, but the encryption produces 2064 byte ciphertext chunks which must be read as such during decryption. This is a simple fix, but it would be better to use streams all the way instead of encrypting such separate chunks.
You're invoking Rfc2898DeriveBytes for every 2048 byte chunk, but it never changes. Either introduce randomness, but actually using a random salt and random IV, or cache the key. (random salt and random IV are still necessary to reach semantic security)

Error RijndaelManaged, "Padding is invalid and cannot be removed"

I have error from CryptoStream:
Padding is invalid and cannot be removed.
Code
public MemoryStream EncrypteBytes(Stream inputStream, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Padding = PaddingMode.PKCS7;
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
var buffer = new byte[1024];
var read = inputStream.Read(buffer, 0, buffer.Length);
while (read > 0)
{
cryptoStream.Write(buffer, 0, read);
read = inputStream.Read(buffer, 0, buffer.Length);
}
cryptoStream.FlushFinalBlock();
memoryStream.Position = 0;
return memoryStream;
}
// Example usage: DecryptBytes(encryptedBytes, "SensitivePhrase", "SodiumChloride");
public byte[] DecrypteBytes(MemoryStream memoryStream, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Padding = PaddingMode.PKCS7;
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] plainBytes = new byte[memoryStream.Length];
int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
return plainBytes;
}
Use PaddingMode.Zeros to fix problem , Following code:
public byte[] EncryptFile(Stream input, string password, string salt)
{
// Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
// 1.The block size is set to 128 bits
// 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
var algorithm = new RijndaelManaged { KeySize = 256, BlockSize = 128 };
var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt));
algorithm.Key = key.GetBytes(algorithm.KeySize / 8);
algorithm.IV = key.GetBytes(algorithm.BlockSize / 8);
algorithm.Padding = PaddingMode.Zeros;
using (Stream cryptoStream = new MemoryStream())
using (var encryptedStream = new CryptoStream(cryptoStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
{
CopyStream(input, encryptedStream);
return ReadToEnd(cryptoStream);
}
}
public byte[] DecryptFile(Stream input, Stream output, string password, string salt)
{
// Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
// 1.The block size is set to 128 bits
// 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
var algorithm = new RijndaelManaged { KeySize = 256, BlockSize = 128 };
var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt));
algorithm.Key = key.GetBytes(algorithm.KeySize / 8);
algorithm.IV = key.GetBytes(algorithm.BlockSize / 8);
algorithm.Padding = PaddingMode.Zeros;
try
{
using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
{
CopyStream(input, decryptedStream);
return ReadToEnd(output);
}
}
catch (CryptographicException ex)
{
throw new InvalidDataException("Please supply a correct password");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I hop help you.
Please check your pass phrase - it should be same in both methods EncrypteBytes and DecrypteBytes. If both are not same, then it will generate the error.
My problem was I was taking the encryped output in bytes and converting it to a string. The string back to byte array (for decrypting) was not the same. I was using UTF8Encoding, then I tried ASCIIEnconding. Neither worked.
Convert.FromBase64String/ToBase64String worked fine, got rid of the padding issues and actually decrypted the data.
It's work
using (FileStream fs = new FileStream( absolute, FileMode.Open )) {
// create a CryptoStream in read mode
using (CryptoStream cryptoStream = new CryptoStream( fs, decryptor, CryptoStreamMode.Read )) {
int readLength = ( int )fs.Length;
byte[] buffer = new byte[readLength];
cryptoStream.Read( buffer, 0, readLength );
using (MemoryStream ms = new MemoryStream( buffer )) {
BinaryFormatter bf = new BinaryFormatter( );
settings = ( SettingsJson )bf.Deserialize( ms );// Deserialize SettingsJson array
}
}
fs.Close( );
}

Categories

Resources