是否可以制作DES / Triple DES文件加密器
问题描述:
我正在尝试制作DES和三重DES文件加密器,我无法找到关于DES文件加密的任何文章或视频,这就是我提出问题的原因。我已经尝试了以下代码,但我得到了无效的密钥错误,如果我将IV从16更改为8并不重要我仍然会收到此错误。
我试过的代码:
I am trying to make a DES and triple DES file encrypter i cant find any articles or videos on DES file encryption which is why i asked my question. I have tried the following code but i get invalided key error and it doesn't matter if i change the IV from 16 to 8 i still get this error.
The code i tried:
private void TDES_EncryptFile()
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Encrypted File (*.enc)|*.enc";
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == true)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
myStream.Close();
string keyText = keys2.Text;
byte[] keyBytes = ASCIIEncoding.ASCII.GetBytes(keyText);
byte[] ivBytes = ASCIIEncoding.ASCII.GetBytes(keyText);
string inputFile = Openfile.Text;
string encryptedFile = saveFileDialog1.FileName;
using (FileStream inputFileStream = File.Open(inputFile, FileMode.Open))
using (FileStream outputFileStream = File.Open(encryptedFile, FileMode.Create))
{
using (TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider())
{
tds.Key = keyBytes;
tds.IV = ivBytes;
ICryptoTransform cryptoTransform = tds.CreateEncryptor();
using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, cryptoTransform, CryptoStreamMode.Write))
{
byte[] buffer = new byte[inputFileStream.Length];
inputFileStream.Read(buffer, 0, buffer.Length);
cryptoStream.Write(buffer, 0, buffer.Length);
MessageBox.Show("The File Was Successfully Encrypted", "Encrypted!", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
}
}
答
事实证明我需要md5-hash我的密钥然后指定8个字符长IV
It turns out i needed to md5-hash my key and then specify 8 character long IV
byte[] keyBytes = md5.ComputeHash(utf.GetBytes(keyText));
byte[] ivBytes = ASCIIEncoding.ASCII.GetBytes(keyText.Substring(0, 8));