C# 加密文件夹 内部程序可以访问 外部输入密码才可以访问 代码
时间: 2024-09-13 14:14:29 浏览: 41
在C#中,我们可以使用`System.IO.Packaging`和`System.Security.Cryptography`库来创建加密的文件夹,只有通过正确的密码才能访问其中的内容。以下是一个基本示例,展示了如何使用AES(高级加密标准)对文件夹进行加密:
```csharp
using System;
using System.IO;
using System.IO.Compression;
using System.IO.Packaging;
using System.Security.Cryptography;
public class EncryptedFolder {
private string encryptionKey; // 密钥存储或生成
public EncryptedFolder(string password) {
if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password cannot be null or empty.");
this.encryptionKey = Convert.ToBase64String(BitConverter.GetBytes(GenerateKeyFromPassword(password)));
}
private byte[] GenerateKeyFromPassword(string password) {
using var sha256 = SHA256.Create();
return sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
}
public void EncryptDirectory(string sourcePath, string destinationPath) {
if (!Directory.Exists(sourcePath)) throw new DirectoryNotFoundException($"Source directory not found: {sourcePath}");
// 创建一个新的PackagePart来承载加密内容
PackageRelationship relationship = CreatePackageRelationship(sourcePath);
PackagePart packagePart = AddEncryptedZipToPackage(destinationPath, relationship);
// 将源目录复制到加密包内
CopyDirectoryToPackage(packagePart, sourcePath);
}
private PackageRelationship CreatePackageRelationship(string sourcePath) {
PackagePart part = PackageRelationship.CreatePart(PackagePartNames.RootPartName, typeof(PackageRelationship).GUID.ToString(), CompressionOption.None);
PackageRelationship relationship = new PackageRelationship(part.Uri, "http://schemas.microsoft.com/pkg/rels/#" + part.Uri.LocalPath, RelationshipTypes.Resolves);
part.Properties["Target"] = sourcePath;
return relationship;
}
private PackagePart AddEncryptedZipToPackage(string destinationPath, PackageRelationship relationship) {
Package package = Package.Open(destinationPath, FileMode.Create);
package_relationships.Add(relationship);
Uri partUri = new Uri("/" + PackagePartNames.EncryptedFolderPartName, UriKind.Relative);
PackagePart encryptedPart = package.CreatePart(partUri, "application/vnd.ms-zip", CompressionOption.Optimal);
encryptedPart.FeedbackStream = new CryptoStream(Stream.Null, GetAesCryptoServiceProvider().CreateEncryptor(), CryptoStreamMode.Write);
return encryptedPart;
}
private void CopyDirectoryToPackage(PackagePart packagePart, string sourcePath) {
ZipArchiveEntry zipEntry = new ZipArchiveEntry(Path.GetFileName(sourcePath), ZipArchiveEntryMode.Create);
using (var entryStream = packagePart.GetStream()) {
zipEntry.Open();
File.Copy(sourcePath, entryStream, true);
}
}
private Aes CreateAesCryptoServiceProvider() {
// AES encryption provider
var aes = Aes.Create();
aes.KeySize = 256;
aes.BlockSize = 128;
return aes;
}
private ICryptoTransform GetAesCryptoServiceProvider() {
return CreateAesCryptoServiceProvider().CreateEncryptor();
}
}
// 使用示例
public static void Main(string[] args) {
string sourceDir = @"C:\source\";
string encryptedFolder = @"C:\encryptedfolder.zip";
EncryptedFolder folderEncryption = new EncryptedFolder("your_password_here");
folderEncryption.EncryptDirectory(sourceDir, encryptedFolder);
}
```
注意:这个示例创建的是一个ZIP格式的加密文件夹,实际应用可能需要结合Windows的封装技术(如`FileStream`包装`ICryptoTransform`)以提供更完整的保护。
阅读全文