C# Encrypt an XML File

前端 未结 4 1749
暗喜
暗喜 2020-12-13 23:30

I need two methods one to encrypt and one to decrypt an xml file with a key= \"hello world\",the key hello world should be used to encrypt and decrypt the xml file.These met

4条回答
  •  孤城傲影
    2020-12-13 23:53

    If you want the same key for encrypting and decrypting you should use a symmetric method (that's the definition, really). Here's the closest one to your sample (same source). http://msdn.microsoft.com/en-us/library/sb7w85t6.aspx

    The posted sample isn't working because they aren't using the same keys. Not only on different machines: running the program on the same machine twice should not work either (didn't work for me), because they use different random keys every time.
    try adding this code after creating your key:

    key = new RijndaelManaged();
    
    string password = "Password1234"; //password here
    byte[] saltBytes = Encoding.UTF8.GetBytes("Salt"); // salt here (another string)
    var p = new Rfc2898DeriveBytes(password, saltBytes); //TODO: think about number of iterations (third parameter)
    // sizes are devided by 8 because [ 1 byte = 8 bits ]
    key.IV = p.GetBytes(key.BlockSize / 8);
    key.Key = p.GetBytes(key.KeySize / 8);
    

    Now the program is using the same key and initial vector, and Encrypt and Decrypt should work on all machines.
    Also, consider renaming key to algorithm, otherwise this is very misleading. I'd say it's a bad, not-working-well example from MSDN.

    NOTE: PasswordDeriveBytes.GetBytes() has been deprecated because of serious (security) issues within the PasswordDeriveBytes class. The code above has been rewritten to use the safer Rfc2898DeriveBytes class instead (PBKDF2 instead of PBKDF1). Code generated with the above using PasswordDeriveBytes may be compromised.

    See also: Recommended # of iterations when using PKBDF2-SHA256?

提交回复
热议问题