ファイルを暗号化し、暗号化されたコンテンツを同じファイルに書き込みました。しかし、ファイルを復号化して同じファイルに書き込もうとすると、古いコンテンツ、つまり暗号化されたテキストをクリアできません。どうすればそれができますか。
暗号化コード
static void EncryptFile(string sInputFilename,string sKey)
{
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.ReadWrite);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsInput,
desencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
fsInput.SetLength(0);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
}
コードの解読
static void DecryptFile(string sInputFilename,
string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
FileStream fsread = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.ReadWrite);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read);
int data;
while ((data = cryptostreamDecr.ReadByte()) != -1)
{
fsread.WriteByte((byte)data);
}
fsread.Close();
cryptostreamDecr.Close();
}