我如何 encrypt/decrypt .Net Core 中的文件?

How do I encrypt/decrypt a file in .NetCore?

我想 encrypt/decrypt 使用 .NetCore 库的文件 to/from 磁盘。

我看到的示例是基于帐户的,因此只有用于加密文件的帐户才能解密它。 https://docs.microsoft.com/en-us/dotnet/api/system.io.file.encrypt?view=net-5.0

我需要能够用密码加密我的文件。 是否有可用的 .Net 库(标准 .NetCore 库的一部分或第 3 方)?

互联网上有很多 encryption/decryption 的资源,只需简单搜索,您就可以找到它们。

加密:

public static string EncryptString(string text, string keyString)
{
    var key = Encoding.UTF8.GetBytes(keyString);

    using (var aesAlg = Aes.Create())
    {
        using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
        {
            using (var msEncrypt = new MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(text);
                }

                var iv = aesAlg.IV;

                var decryptedContent = msEncrypt.ToArray();

                var result = new byte[iv.Length + decryptedContent.Length];

                Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);

                return Convert.ToBase64String(result);
            }
        }
    }
}

解密:

public static string DecryptString(string cipherText, string keyString)
{
    var fullCipher = Convert.FromBase64String(cipherText);

    var iv = new byte[16];
    var cipher = new byte[16];

    Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
    Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
    var key = Encoding.UTF8.GetBytes(keyString);

    using (var aesAlg = Aes.Create())
    {
        using (var decryptor = aesAlg.CreateDecryptor(key, iv))
        {
            string result;
            using (var msDecrypt = new MemoryStream(cipher))
            {
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var srDecrypt = new StreamReader(csDecrypt))
                    {
                        result = srDecrypt.ReadToEnd();
                    }
                }
            }

            return result;
        }
    }
}

Symmetric and Asymmetric Encryption in .NET Core

Cryptography with Practical Examples in .Net Core

Encryption And Decryption Using A Symmetric Key In C#