I was doing a program for encrypting private files on another computer apart, where this same formula worked correctly, I don't understand why this part of code doesn't work, even though it worked before:
public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
byte[] saltBytes = new byte[] { 2, 0, 0, 4, 0, 3, 0, 3 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 256;
AES.Padding = PaddingMode.PKCS7;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CFB;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}
I've been trying to find out for about 2 hours because it gives me that error when decrypting, but counting on the little encryption knowledge that I have have it's absolutely impossible.
First of all, when i say ChunkSize i mean ChunkSize, because first of all I split the file into 5Mb bytes array, then i encrypt or decrypt the Byte Array and write the data into the file. Problem was, that ChunkSize was like less than 1Mb and thats why CryptographicException arises.
if (File.Exists(FileToDecrypt)) {
byte[] PasswordBytes;
if (IsFileTypePassword) {
PasswordBytes = File.ReadAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),"K3ys\\" + PasswordToDecrypt));
} else {
PasswordBytes = Encoding.UTF8.GetBytes(PasswordToDecrypt);
}
DecryptFile(5000000, FileToDecrypt, PasswordBytes); // Here was the problem
DecThread.Abort();
}
And here is the function that splits the file, its a little bit different than mine but it does the same, also this piece of code is grabbed from another Question form StackOverflow.
public static void SplitFile(string inputFile, int chunkSize, string path)
{
byte[] buffer = new byte[chunkSize];
using (Stream input = File.OpenRead(inputFile))
{
int index = 0;
while (input.Position < input.Length)
{
using (Stream output = File.Create(path + "\\" + index))
{
int chunkBytesRead = 0;
while (chunkBytesRead < chunkSize)
{
int bytesRead = input.Read(buffer,
chunkBytesRead,
chunkSize - chunkBytesRead);
if (bytesRead == 0)
{
break;
}
chunkBytesRead += bytesRead;
}
output.Write(buffer, 0, chunkBytesRead);
}
index++;
}
}
}