使用FileEncrypt方法对文件加密, 该方法期望将要加密的文件的路径作为第一个参数, 并将第二个参数用作加密文件的密码。以后可以使用密码解密文件。为使一切正常, 建议你使用ZeroMemory方法从内存中删除密码。出于安全目的, 调用此函数以在使用后从内存中删除密钥:
string password = "ThePasswordToDecryptAndEncryptTheFile"; // For additional security Pin the password of your files GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned); // Encrypt the file FileEncrypt(@"C:\Users\username\Desktop\wordFileExample.doc", password); // To increase the security of the encryption, delete the given password from the memory ! ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2); gch.Free(); // You can verify it by displaying its value later on the console (the password won't appear) Console.WriteLine("The given password is surely nothing: " + password);FileEncrypt方法将在原始文件的同一目录中生成文件, 其扩展名为aes(例如wordFileExample.doc)。
解密文件要解密文件, 我们将遵循相同的过程, 只是使用FileDecrypt。此方法将加密文件的路径作为第一个参数, 将解密文件应放置的路径作为第二个参数。作为第三个参数, 你需要提供最初用于加密文件的字符串:
string password = "ThePasswordToDecryptAndEncryptTheFile"; // For additional security Pin the password of your files GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned); // Decrypt the file FileDecrypt(@"C:\Users\sdkca\Desktop\example.doc.aes", @"C:\Users\sdkca\Desktop\example_decrypted.doc", password); // To increase the security of the decryption, delete the used password from the memory ! ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2); gch.Free(); // You can verify it by displaying its value later on the console (the password won't appear) Console.WriteLine("The given password is surely nothing: " + password); 最后的笔记加密/解密过程会消耗大量内存, 并且需要花费时间, 因此建议在另一个线程中运行这些任务, 以防止主UI冻结。
可以将扩展名aes更改为所需的扩展名。
编码愉快!
未经允许不得转载:srcmini » 如何在C#中使用AES加密算法对文件进行加密和解密
分享到: (0)
标签: