私はエース暗号を使ってファイルを暗号化しています。私は暗号化するためのreadByte関数を使用する場合ワード、パワーポイントファイルを解読する際のエラー
Encrypt(@"E:\test.docx", @"E:\test.enc");
Decrypt(@"E:\test.enc", @"E:\test_new.docx");
、各バイトを復号化:主な機能には
private static void Encrypt(string inputFilePath, string outputfilePath)
{
string EncryptionKey = "MAKV2SPBNI99212";
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
//int data;
//while ((data = fsInput.ReadByte()) != -1)
//{
// cs.WriteByte((byte)data);
//}
byte[] bytes = new byte[fsInput.Length];
while (fsInput.Read(bytes, 0, (int)fsInput.Length) > 0) ;
cs.Write(bytes, 0, bytes.Length);
}
}
}
}
}
private static void Decrypt(string inputFilePath, string outputfilePath)
{
string EncryptionKey = "MAKV2SPBNI99212";
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
{
using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
{
//int data;
//while ((data = cs.ReadByte()) != -1)
//{
// fsOutput.WriteByte((byte)data);
//}
byte[] bytes = new byte[fsInput.Length];
while (cs.Read(bytes, 0, (int)fsInput.Length) > 0) ;
fsOutput.Write(bytes, 0, bytes.Length);
}
}
}
}
}
私は、Wordファイルを復号化、暗号化します。ファイルtest_new.docxが作成され、正常にオープンされます。しかし、私がRead関数を使って多くのバイトを暗号化、解読すると、test_new.docxファイルが作成されますが、エラー内容は開けません。 アイデアはありますか?ありがとう!
デフォルトのパディングは、PKCS#7の[PaddingMode.PKCS7]です。パディングなしです。 MSDNの[SymmetricAlgorithm Properties](http://msdn.microsoft.com/en-us/library/System.Security.Cryptography.SymmetricAlgorithm_properties.aspx)ページを参照してください。 @Neil Humbyの答えを見てください。 – zaph
@zaphあなたは絶対に正しいです、私は答えを修正しました。しかし、私は 'BinaryReader'を使って内容を一度に読むことは、Neil Humbyのように' ReadByte() 'を使うよりもパフォーマンスが良いと思います。 – haindl
@zaph解読された 'bytes'の0は、PKCS#7のパディングからではなく、' fsInput.Length'が実際には大きすぎるため、 'byte [] bytes = new byte [fsInput.Length];'私はこの面を反映するために私の答えを修正しました。私の答えに何か誤りがありますか? (私は学ぶつもりです) – haindl