How can I protect files and directories with a password in C#?
问题:
回答1:
If you need to protect files and folders you have several options:
Control the operating system level permissions with ACLs (Access Control Lists) so only the authorized users on the computer have access to those objects. This will not create a new password for the file, but will just deny access to every user that is not authorized. The downside is that this needs to be done on a machine (or Active Directory domain) level. So if you copy the file to another machine, the protection is no longer active.
You can use a compression algorithm, like zip or rar, to compress the protected files and assign a password that is required in order to uncompress them. This works even if you copy the zip file to other machines. You can package the files with no compression factor if you only need to protect the files and don't care about reducing file size. You can find online several open source zip libraries for .NET. One of them is http://www.icsharpcode.net/OpenSource/SharpZipLib/
Or you could perform file encryption with the classes in
System.Security.Cryptography
, using a symmetric algorithm where the cypher key would be your password, or asymmetric encryption with certificates, where the password would be the private key's password of the certificate. This generally provides stronger security than zip encryption, but you have to write a little more code and manage the user's certificates.
What are your specific security and authorization requirements?
回答2:
Have a look at C# Encryption examples. You can combine one of these with this Recursive Directory Search example (dead link) to encrypt all files in a directory (and its subdirectories, if needed).
回答3:
You can create a file, create an encrypted file system on it and then loopback-mount it.