简体   繁体   中英

How do I encrypt/decrypt the same xml file in C#?

So I need the ability to encrypt/decrypt the same settings XML file in my application. I can only find examples that use a seperate output file. I don't need an output file. Nothing super secure. I just basically need to make the settings file not readable to protect a couple connections strings. I am able to encrypt the file just fine using this code:

    public static void EncryptAndSerialize(Object obj)
{
    UnicodeEncoding aUE = new UnicodeEncoding();
    byte[] key = aUE.GetBytes("password");
    RijndaelManaged RMCrypto = new RijndaelManaged();
    using (FileStream fs = File.Open(@"D:\Sample.xml", FileMode.Create))
    {
    using (CryptoStream cs = new CryptoStream(fs, RMCrypto.CreateEncryptor(key,   key), CryptoStreamMode.Write))
        {
            XmlSerializer xmlser = new XmlSerializer(obj.GetType());
            xmlser.Serialize(cs, obj);
        }
        fs.Close();
}

I just need to know how to use this same sort of process to decrypt that same file. If anyone could point me in the right direction it would be much appreciated. Keep in mind ultra security is not an issue. Forgive my ignorance this task is new to me.

Something like this. Notice that this calls CreateDecryptor with the CryptoStreamMode.Read flag telling it to read from the stream.

var decryptor = new RijndaelManaged (); 
var transformer = decryptor.CreateDecryptor(_decryptKey, _decryptSeed);
var cryptoStream = new CryptoStream(encryptedStream, transformer, CryptoStreamMode.Read);
cryptoStream.CopyTo(resultStream);
resultStream.Close();

Some editorial comments:

1) AES would be better and here's why: https://blogs.msdn.microsoft.com/shawnfa/2006/10/09/the-differences-between-rijndael-and-aes/

2) Don't underestimate .net encryption - Microsoft doesn't fool around

3) Bad encryption can be worse than no encryption because it provides a false sense of security

What he said plus... MemoryStream...

https://msdn.microsoft.com/en-us/library/system.io.memorystream(v=vs.110).aspx

using (var sink = new MemoryStream())
{
    // Write your encyphered data to the sink 
    // (from your FileStream, via the encryption provider) 
    // and then later, read (or copy) from sink back into 
    // the FileStream. Don't forget to re-position your 
    // FileStream before doing so.
}

If it were me I'd use independent FileStreams. 独立的FileStreams。 One for read only and, later, another one for writing back to the .xml file (that you just read from). I'd only bother constructing and writing the later if and only if I knew I had a fully formed/filled sink.

You might also investigate the use of SecureString (but I'm digressing):

https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx

All that said, you want to directly overwrite a file (ie, in place edit). 不想直接覆盖文件(即,就地编辑)。 If you do, and the write fails (part way through) your original file will be, well, corrupt. Leaving you with zip/nadda/crap. Always write to a new, temp file and only after that completes 100% do you promote the temp file to the source path (typically via FileInfo.MoveTo).

https://msdn.microsoft.com/en-us/library/system.io.fileinfo.moveto(v=vs.110).aspx

If bad stuff happens along the way (and it will!!!), all you do is delete the temp file (off of a catch block, etc.) and you're back where you started from.

The humans won't know that you actually worked two files (and if you have some monitor automation that is getting tripped up by tandem files then rewrite it cause it's well, crap).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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