C#如何参照advapi32流程实现文件加密(SHA替代MD5)
C# 原生无DllImport文件加密实现(SHA替换MD5)
现有代码报错根因
ImportCspBlob方法仅接收符合CSP规范的密钥Blob格式二进制数据,你直接传入密码的ASCII编码字节完全不符合格式要求,因此触发密钥错误。同时你选用的RSA非对称加密不适用于直接加密大体积文件,和参考的微软示例对称加密流程不匹配。
可运行原生实现方案
以下实现完全基于.NET内置类库,无需任何DllImport调用,流程对齐微软原加密示例,使用SHA256替换原MD5做哈希处理:
- 加密流程:读取源文件 -> 用SHA256从密码派生对称加密密钥与IV -> AES加密文件内容 -> 输出加密后文件
- 解密流程:读取加密文件 -> 用相同密码和SHA256派生密钥与IV -> AES解密 -> 输出原始文件
完整实现代码
using System.Security.Cryptography; using System.Text; using System.IO; public static class FileEncryptor { // 可自行调整盐值、迭代次数,盐值固定即可不要随意修改 private static readonly byte[] _salt = Encoding.UTF8.GetBytes("YOUR_CUSTOM_SALT_VALUE_123456"); private const int _iterations = 10000; private const int _keySize = 256; // AES256密钥长度 private const int _blockSize = 128; // AES块大小 // 加密文件 public static void EncryptFile(string sourceFilePath, string outputEncryptedFilePath, string password) { byte[] fileContent = File.ReadAllBytes(sourceFilePath); // 使用SHA256派生密钥和IV,替代原示例的MD5 using var deriveBytes = new Rfc2898DeriveBytes(password, _salt, _iterations, HashAlgorithmName.SHA256); byte[] key = deriveBytes.GetBytes(_keySize / 8); byte[] iv = deriveBytes.GetBytes(_blockSize / 8); using var aes = Aes.Create(); aes.Key = key; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using var encryptor = aes.CreateEncryptor(); byte[] encryptedContent = encryptor.TransformFinalBlock(fileContent, 0, fileContent.Length); File.WriteAllBytes(outputEncryptedFilePath, encryptedContent); } // 解密文件 public static void DecryptFile(string encryptedFilePath, string outputDecryptedFilePath, string password) { byte[] encryptedContent = File.ReadAllBytes(encryptedFilePath); using var deriveBytes = new Rfc2898DeriveBytes(password, _salt, _iterations, HashAlgorithmName.SHA256); byte[] key = deriveBytes.GetBytes(_keySize / 8); byte[] iv = deriveBytes.GetBytes(_blockSize / 8); using var aes = Aes.Create(); aes.Key = key; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using var decryptor = aes.CreateDecryptor(); byte[] decryptedContent = decryptor.TransformFinalBlock(encryptedContent, 0, encryptedContent.Length); File.WriteAllBytes(outputDecryptedFilePath, decryptedContent); } // 调用示例 public static void Test() { string password = "YOUR_PASSWORD"; EncryptFile("D:\\test.txt", "D:\\test.enc", password); DecryptFile("D:\\test.enc", "D:\\test_dec.txt", password); } }
注意事项
- 请自行修改代码中的
_salt值为自定义的随机字符串,不要使用示例中的默认值 - 若需要适配更大体积的文件,可改为流读写方式避免一次性加载全部文件内容到内存
- 加密解密时密码、盐值、迭代次数、哈希算法必须完全一致才能正确解密
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

