-
Encryption Problem
Hello everyone, I'm having a problem with my Decryption specifically. It works swell, except that the first 8 bytes of whatever I decrypt are mangled...Try it yourself on a simple text file.
If you can help me out, please do!
Code:
/************************************
Example of the problem.
************************************/
cEnc cDES = new cEnc(cEnc.ENCTYPE.eDES);
cDES.FileEncrypt("C:\\test.txt","C:\\testenc.txt");
cDES.FileDecrypt("C:\\testenc.txt","C:\\testdec.txt");
/************************************
Encryption Class I'm working on. Right now it just does DES.
************************************/
using System.IO;
using System.Security.Cryptography;
public class cEnc
{
public enum ENCTYPE {
eDES = 0x01,
eDSA = 0x02,
eRC2 = 0x03,
eRIJNDAEL = 0x04,
eRSA = 0x05,
eTRIPLEDES = 0x06
};
public ENCTYPE EncryptionType = ENCTYPE.eDES;
public cEnc(ENCTYPE enctype)
{
EncryptionType = enctype;
}
public cEnc()
{
}
private byte[] ToBytes( string s)
{
return System.Text.Encoding.ASCII.GetBytes(s);
}
public void FileEncrypt(string szFileIn, string szFileOut)
{
if(!File.Exists(szFileIn))
throw(new Exception("File Not Found: " + szFileIn));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//later we'll let the user pick a key.
ICryptoTransform DesEnc = des.CreateEncryptor(ToBytes("kitten21"),null);
FileStream fsIn = new FileStream(szFileIn, FileMode.Open, FileAccess.Read);
FileStream fsOut = new FileStream(szFileOut, FileMode.Create, FileAccess.ReadWrite);
byte[] buffer = new byte[2048];
CryptoStream cStream = new CryptoStream(fsOut, DesEnc, CryptoStreamMode.Write);
long pos = 0;
int BL = buffer.Length;
while(pos <= fsIn.Length)
{
if (pos + BL > fsIn.Length)
{
int t = (int)(fsIn.Length - pos);
fsIn.Read(buffer, 0, t);
cStream.Write(buffer, 0, t);
}
else
{
fsIn.Read(buffer, 0, BL);
cStream.Write(buffer, 0, BL);
}
pos += BL;
}
fsIn.Close();
cStream.Close();
fsOut.Close();
}
public void FileDecrypt(string szFileIn, string szFileOut)
{
if(!File.Exists(szFileIn))
throw(new Exception("File Not Found: " + szFileIn));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//later we'll let the user pick a key.
ICryptoTransform DesEnc = des.CreateDecryptor(ToBytes("kitten21"),null);
FileStream fsIn = new FileStream(szFileIn, FileMode.Open, FileAccess.Read);
FileStream fsOut = new FileStream(szFileOut, FileMode.Create, FileAccess.Write);
byte[] buffer = new byte[2048];
CryptoStream cStream = new CryptoStream(fsIn, DesEnc, CryptoStreamMode.Read);
long pos = 0;
int BL = buffer.Length;
while(pos <= fsIn.Length)
{
if (pos + BL > fsIn.Length)
{
int t = (int)(fsIn.Length - pos);
cStream.Read(buffer, 0, t);
fsOut.Write(buffer, 0, t);
}
else
{
cStream.Read(buffer, 0, BL);
fsOut.Write(buffer, 0, BL);
}
pos += BL;
}
fsIn.Close();
cStream.Close();
fsOut.Close();
}
}
}