简体   繁体   English

加密然后解密后文件数据已更改

[英]File data changed after encrypting then decrypting

I encrypted a file using DES then After decrypting it successfully at the server and using 我使用DES加密了文件,然后在服务器上成功解密并使用

System.IO.File.WriteAllBytes(@"c:\test\" + fileName, decryptedFile);

method the file data changed a little it the text is "Encrypting and Decrypting usind DES blah blah blah blah" the text in the end file after decrypting is " k$nlng and Decrypting usind DES blah blah blah blah" and i also tried this: 方法文件数据稍有变化,其文本为“加密和解密usind DES等等等等”,解密后的最终文件中的文本为“ k $ nlng和解密usind DES等等等等”,我也尝试了以下方法:

using (BinaryWriter binWriter =
                        new BinaryWriter(File.Open(@"C:\Test\" + fileName, FileMode.Create)))
                {
                    binWriter.Write(decryptedFile);
                }

the text still not the same encrypting by : 文本仍然不是通过以下方式加密的:

public byte [] DESEncrypt(byte [] fileBytes)
    {
        CryptoStreamMode mode = CryptoStreamMode.Write;

        // Set up streams and encrypt
        MemoryStream memStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memStream, 
            cryptoProvider.CreateEncryptor(cryptoProvider.Key, cryptoProvider.Key), mode);
        cryptoStream.Write(fileBytes, 0, fileBytes.Length);
        cryptoStream.FlushFinalBlock();

        // Read the encrypted message from the memory stream
        byte[] encryptedMessageBytes = new byte[memStream.Length];
        memStream.Position = 0;
        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
        MessageBox.Show("encrypted DES");
        return encryptedMessageBytes;
    }

decrypting by: 解密者:

static public byte[] DESdecrypt(byte [] fileBytes)
    {

        ICryptoTransform decryptor = cryptoProvider.CreateDecryptor();
        byte[] originalAgain = decryptor.TransformFinalBlock(fileBytes, 0, fileBytes.Length);

        return originalAgain;
    }

Thanks 谢谢

hard to say, not an expert on the subject but compare your bytes before encrypting and after encrypting and decrypting. 很难说,不是这个问题的专家,而是在加密之前和加密解密之后比较您的字节。 If they are identical no issues with the process. 如果它们相同,则该过程没有问题。 WriteALLBytes might not be the only thing. WriteALLBytes可能不是唯一的东西。 think MIME type . 认为MIME类型。 a similar issue is i had to specifically say what type of file i am saving. 一个类似的问题是我必须特别说明我要保存的文件类型。

You are passing the same value for your "key" and "iv" value. 您正在为“键”和“ iv”值传递相同的值。 Each time you call the function, your "iv" value gets updated (thus, your key gets changed). 每次调用该函数时,“ iv”值都会更新(因此,键也会更改)。

So you basically are doing this: 因此,您基本上是在这样做:

key = "key" Encrypt (key, key) key =“ key”加密(密钥,密钥)

-- key has now changed. -密钥现已更改。

What you need to do is: 您需要做的是:

key = "key" iv = copy of key Encrypt (key, iv) 密钥=“密钥” iv =密钥副本(密钥,iv)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM