There is really simple code to decrypt file (triple des encryption):
FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv),CryptoStreamMode.Read); //<---- Exceptions
And it does not work. 'cs' is invalid and it's impossible to read from it. There are some exceptions while creating CryptoStream:
Length = 'cs.Length' threw an exception of type 'System.NotSupportedException'
base {System.SystemException} = {"Stream does not support seeking."}
Why I can't create crypto stream and read from it and how to fix this issue?
[added]
Thanks for responses, now it's more clear for me. But - still, this is impossible to read from 'cs'.
Encryption:
FileStream fout = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fout, tdes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
byte[] d = Encoding.ASCII.GetBytes(Data);
cs.Write(d, 0, d.Length);
cs.WriteByte(0);
cs.Close();
fout.Close();
There is iv and key defined somewhere else. And, decryption - entire method:
FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
TripleDES tdes = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv),CryptoStreamMode.Read);
StringBuilder SB = new StringBuilder();
int ch;
for (int i = 0; i < fin.Length; i++)
{
ch = cs.ReadByte(); //Exception - CryptographicException: Bad data
if (ch == 0)
break;
SB.Append(Convert.ToChar(ch));
}
cs.Close();
fin.Close();
As you can see, there is the same key and iv like in encryption code. But it' still impossible to read from 'cs' stream -exception is thrown. How do you think - what's wrong here?
This is my key and iv used:
public static byte[] key = { 21, 10, 64, 10, 100, 40, 200, 4,
21, 54, 65, 246, 5, 62, 1, 54,
54, 6, 8, 9, 65, 4, 65, 9};
private static byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0 };