看來我的代碼添加6個字節加密解密後的結果文件名爲.. 我嘗試它放在一個MKV文件.. 請幫助我的三重DES包裝器有什麼問題?
這裏是我的代碼
class TripleDESCryptoService : IEncryptor, IDecryptor
{
public void Encrypt(string inputFileName, string outputFileName, string key)
{
EncryptFile(inputFileName, outputFileName, key);
}
public void Decrypt(string inputFileName, string outputFileName, string key)
{
DecryptFile(inputFileName, outputFileName, key);
}
static void EncryptFile(string inputFileName, string outputFileName, string sKey)
{
var outFile = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
// The chryptographic service provider we're going to use
var cryptoAlgorithm = new TripleDESCryptoServiceProvider();
SetKeys(cryptoAlgorithm, sKey);
// This object links data streams to cryptographic values
var cryptoStream = new CryptoStream(outFile, cryptoAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);
// This stream writer will write the new file
var encryptionStream = new BinaryWriter(cryptoStream);
// This stream reader will read the file to encrypt
var inFile = new FileStream(inputFileName, FileMode.Open, FileAccess.Read);
var readwe = new BinaryReader(inFile);
// Loop through the file to encrypt, line by line
var date = readwe.ReadBytes((int)readwe.BaseStream.Length);
// Write to the encryption stream
encryptionStream.Write(date);
// Wrap things up
inFile.Close();
encryptionStream.Flush();
encryptionStream.Close();
}
private static void SetKeys(SymmetricAlgorithm algorithm, string key)
{
var keyAsBytes = Encoding.ASCII.GetBytes(key);
algorithm.IV = keyAsBytes.Take(algorithm.IV.Length).ToArray();
algorithm.Key = keyAsBytes.Take(algorithm.Key.Length).ToArray();
}
static void DecryptFile(string inputFilename, string outputFilename, string sKey)
{
// The encrypted file
var inFile = File.OpenRead(inputFilename);
// The decrypted file
var outFile = new FileStream(outputFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
// Prepare the encryption algorithm and read the key from the key file
var cryptAlgorithm = new TripleDESCryptoServiceProvider();
SetKeys(cryptAlgorithm, sKey);
// The cryptographic stream takes in the encrypted file
var encryptionStream = new CryptoStream(inFile, cryptAlgorithm.CreateDecryptor(), CryptoStreamMode.Read);
// Write the new unecrypted file
var cleanStreamReader = new BinaryReader(encryptionStream);
var cleanStreamWriter = new BinaryWriter(outFile);
cleanStreamWriter.Write(cleanStreamReader.ReadBytes((int)inFile.Length));
cleanStreamWriter.Close();
outFile.Close();
cleanStreamReader.Close();
}
}
什麼是這個IV,和它們不一樣導致大小不一樣,IV是8個字節,關鍵是24個字節.. 解密文件確實有額外的6個字節,我應該擔心和切斷它嗎? – 2010-03-30 16:55:58
初始化矢量 - 它用於某些分組密碼模式,例如密碼分組鏈接(CBC) - 不必太擔心它!只要確保它與密鑰不一樣 - 這意味着完全不同,使用一個單獨的隨機數字而不是密鑰。 因此,我測試代碼的唯一更改是刪除IEncryptor和IDecryptor,因爲它們不在.NET Framework中 - 它們是什麼? – 2010-03-30 19:44:02