在C#中加密和解密字符串

Ric*_*ard 330 c# encryption

在C#中满足以下内容的最现代(最佳)方式是什么?

string encryptedString = SomeStaticClass.Encrypt(sourceString);

string decryptedString = SomeStaticClass.Decrypt(encryptedString);
Run Code Online (Sandbox Code Playgroud)

但最小的涉及盐,键,与字节[]等混乱的大惊小怪等.

谷歌搜索和混淆我发现的东西(你可以看到类似的SO Q列表,看这是一个欺骗性的问题).

Cra*_*gTP 709

更新2015年12月23日:由于这个答案似乎得到了很多赞成,我已经更新它以修复愚蠢的错误,并根据评论和反馈大致改进代码.有关具体改进的列表,请参阅帖子末尾.

正如其他人所说,密码学并不简单,所以最好避免"滚动自己的"加密算法.

但是,你可以在内置的RijndaelManaged加密类之类的"滚动你自己的"包装类.

Rijndael是当前高级加密标准的算法名称,因此您肯定使用的算法可被视为"最佳实践".

RijndaelManaged班的确通常需要你"渣土约"使用字节数组,盐,钥匙,初始化向量等,但这恰恰是一种具体的,可有些抽象掉你的"包装"类中.

下面的类是一个我写了前一阵子执行完全相同你后之类的话,简单的单一方法调用,让一些基于字符串的明文与基于字符串的密码进行加密,用得到的加密字符串也被表示为一个字符串.当然,有一种等效方法可以用相同的密码解密加密的字符串.

与此代码的第一个版本不同,每次使用完全相同的salt和IV值时,这个较新的版本每次都会生成随机的salt和IV值.由于在给定字符串的加密和解密之间盐和IV必须相同,因此在加密时将盐和IV预先加密到密文,并再次从密码中提取以便执行解密.结果是,用完全相同的密码加密完全相同的明文,每次都会产生完全不同的密文结果.

在使用这种"实力"来自使用RijndaelManaged类来执行加密的你,与使用沿着Rfc2898DeriveBytes的功能System.Security.Cryptography,这将产生使用标准和安全算法(具体地讲,您的加密密钥的命名空间PBKDF2基于与字符串)您提供的基于密码.(注意,这是对第一个版本使用旧版PBKDF1算法的改进).

最后,重要的是要注意这仍然是未经身份验证的加密.仅加密仅提供隐私(即第三方不知道消息),而经认证的加密旨在提供隐私和真实性(即,接收者知道消息是由发送者发送的).

在不知道您的确切要求的情况下,很难说这里的代码是否足够安全以满足您的需求,但是,它的生成是为了在实现的相对简单性与"质量"之间实现良好的平衡.例如,如果加密字符串的"接收者"直接从受信任的"发件人"接收字符串,则甚至可能不需要身份验证.

如果您需要更复杂的东西,并提供经过身份验证的加密,请查看此帖子以了解实施情况.

这是代码:

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Linq;

namespace EncryptStringSample
{
    public static class StringCipher
    {
        // This constant is used to determine the keysize of the encryption algorithm in bits.
        // We divide this by 8 within the code below to get the equivalent number of bytes.
        private const int Keysize = 256;

        // This constant determines the number of iterations for the password bytes generation function.
        private const int DerivationIterations = 1000;

        public static string Encrypt(string plainText, string passPhrase)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.  
            var saltStringBytes = Generate256BitsOfRandomEntropy();
            var ivStringBytes = Generate256BitsOfRandomEntropy();
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                        }
                    }
                }
            }
        }

        private static byte[] Generate256BitsOfRandomEntropy()
        {
            var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with cryptographically secure random bytes.
                rngCsp.GetBytes(randomBytes);
            }
            return randomBytes;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的类可以非常简单地使用类似于以下的代码:

using System;

namespace EncryptStringSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a password to use:");
            string password = Console.ReadLine();
            Console.WriteLine("Please enter a string to encrypt:");
            string plaintext = Console.ReadLine();
            Console.WriteLine("");

            Console.WriteLine("Your encrypted string is:");
            string encryptedstring = StringCipher.Encrypt(plaintext, password);
            Console.WriteLine(encryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Your decrypted string is:");
            string decryptedstring = StringCipher.Decrypt(encryptedstring, password);
            Console.WriteLine(decryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(你可以下载一个简单的VS2013样品溶液(其中包括一些单元测试)在这里).

更新2015年12月23日: 代码的具体改进列表如下:

  • 修复了加密和解密之间编码不同的愚蠢错误.由于生成盐和IV值的机制已经改变,因此不再需要编码.
  • 由于salt/IV更改,以前的代码注释错误地指示UTF8编码16个字符的字符串产生32个字节不再适用(因为不再需要编码).
  • 已取代的PBKDF1算法的使用已被更现代的PBKDF2算法的使用所取代.
  • 密码推导现在已经被正确腌制了,而之前它根本没有被腌制(另一个愚蠢的小虫被压扁).

  • **代码审查:**由于您正在生成关键材料的[超过160位](http://stackoverflow.com/questions/9231754/c-sharp-passwordderivebytes-confusion),因此PBKDF2会产生更多的感官.然而,与上述声明相反,你的PBKDF1甚至没有被腌制.你对IV的评论是不正确的,16个字符的UTF8是16个字节,无论如何它都适用,因为IV大小实际上是基于块大小而不是密钥大小.IV也是ascii解码而不是在解密中解码的utf8.你的答案谈到抽象盐和静脉注射,但你真的只是删除它们 - **不现代或安全** (11认同)
  • 任何.net核心更新的机会,因为RijndaelManaged()类在Core中不可用? (6认同)
  • 这在 .NET 6 中似乎不再起作用,解密的数据被截断。 (6认同)
  • 这是未经身份验证的加密.攻击者可以在您无法注意的情况下更改邮件.他不能*学习*消息,但他可以改变它. (4认同)
  • @CraigTP很好的解释,但1000次迭代非常低.当PBKDF2标准在2000年编写时,建议的最小迭代次数为1000,但随着CPU速度的增加,该参数将随着时间的推移而增加.截至2005年,Kerberos标准推荐4096次迭代,Apple iOS 3使用2000次,iOS 4使用10000次,而2011年,LastPass使用5000次迭代用于JavaScript客户端,100000次迭代用于服务器端散列. (4认同)
  • 我不被允许回答这个问题,所以我只是在这里发表评论.就.NET Standard 2而言,块大小必须为128.以下是它如何更改代码:https://github.com/nopara73/DotNetEssentials/blob/master/DotNetEssentials/Crypto/StringCipher.cs (4认同)
  • @Thurfir 有没有提到过这一点?它今天救了我:/sf/ask/4893775911/ (4认同)
  • 运行此代码时,我收到此错误:System.FormatException:Base-64 char数组或字符串的长度无效.在线... var cipherTextBytesEithSaltAndIV = Convert.FromBase64String(cipherText); (3认同)
  • 正如其他用户所说,在 .NET 6.0 上运行此代码时发现了一个错误,解密后值被截断。我使用 /sf/ask/4893775911/ 提供的修复程序更新了代码。 (3认同)
  • @FaisalMq - 在输出上执行 `System.Net.WebUtility.UrlEncode(output);` 以便通过 URL 传递它,然后在另一个上执行 `System.Net.WebUtility.UrlDecode(output);` 很简单在解密加密字符串之前结束。 (2认同)
  • ***PasswordDeriveBytes*** 不是 IDisposable (2认同)
  • @Alexandre很高兴你很享受这段代码.是的,使用相同密钥多次加密的相同纯文本产生不同的结果是正确的,因为加密是[salted](https://en.wikipedia.org/wiki/Salt_%28cryptography%29)来产生这个结果.此外,这不是"自制"加密.我的代码仅作为真实加密例程的"包装器",即[Rijndael](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard).启动`using(var symmetricKey = new RijndaelManaged())`的代码行是使用Rijndael的内置.NET托管版本的地方. (2认同)
  • @XGlib是的,这可以在两台计算机之间正常工作,只要代码是相同的(即你不改变两台计算机之间的KeySize或DerivationIterations常量).当字符串被加密并有效地存储在加密的字符串输出中时,生成salt和IV字节,允许"接收"计算机提取它们并使用相同的salt和IV字节进行解密. (2认同)
  • 真的需要Close for the stream吗?无论如何,它们都应该关闭,因为它们在使用中?我想使用此代码,还是现在有一种“更好”的方法?(2019) (2认同)
  • 这不适用于.NET Core,这里有一个公开讨论:https://github.com/dotnet/runtime/issues/18706 (2认同)
  • [这似乎是 .NET 5 的解决方案](https://github.com/2Toad/Rijndael256/issues/13#issuecomment-637724412) (2认同)

A G*_*zal 81

using System.IO;
using System.Text;
using System.Security.Cryptography;

public static class EncryptionHelper
{
    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "abc123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "abc123";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于我们不需要盐的复杂性的众多情况,这非常有用且简单.我只是将加密密钥作为参数,并且能够成功地使用代码. (10认同)
  • 为什么用+替换空格? (10认同)
  • 我的代码分析器警告变量`cs`被处理两次.我们在`Encrypt`和`Decrypt`方法中都不需要冗余语句`cs.Close()`,因为一旦控制存在于`using'块,两者都将被处理掉. (7认同)
  • 您可能不应该将加密密钥硬编码到方法中。 (5认同)
  • @FrenkyB使方法可移植,可以随时传递密钥作为方法参数.例如:`public static string Encrypt(string clearText,string encryptionKey)`这样,每个方法调用都可以有唯一的键. (5认同)
  • @ user1914368-他应该将加密密钥放在哪里,而不是将其硬编码到方法中? (2认同)

ja7*_*a72 29

试试这堂课:

public class DataEncryptor
{
    TripleDESCryptoServiceProvider symm;

    #region Factory
    public DataEncryptor()
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
    }
    public DataEncryptor(TripleDESCryptoServiceProvider keys)
    {
        this.symm = keys;
    }

    public DataEncryptor(byte[] key, byte[] iv)
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
        this.symm.Key = key;
        this.symm.IV = iv;
    }

    #endregion

    #region Properties
    public TripleDESCryptoServiceProvider Algorithm
    {
        get { return symm; }
        set { symm = value; }
    }
    public byte[] Key
    {
        get { return symm.Key; }
        set { symm.Key = value; }
    }
    public byte[] IV
    {
        get { return symm.IV; }
        set { symm.IV = value; }
    }

    #endregion

    #region Crypto

    public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); }
    public byte[] Encrypt(byte[] data, int length)
    {
        try
        {
            // Create a MemoryStream.
            var ms = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            var cs = new CryptoStream(ms,
                symm.CreateEncryptor(symm.Key, symm.IV),
                CryptoStreamMode.Write);

            // Write the byte array to the crypto stream and flush it.
            cs.Write(data, 0, length);
            cs.FlushFinalBlock();

            // Get an array of bytes from the 
            // MemoryStream that holds the 
            // encrypted data.
            byte[] ret = ms.ToArray();

            // Close the streams.
            cs.Close();
            ms.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string EncryptString(string text)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text)));
    }

    public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); }
    public byte[] Decrypt(byte[] data, int length)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream ms = new MemoryStream(data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cs = new CryptoStream(ms,
                symm.CreateDecryptor(symm.Key, symm.IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] result = new byte[length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            cs.Read(result, 0, result.Length);
            return result;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string DecryptString(string data)
    {
        return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0');
    }

    #endregion

}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

string message="A very secret message here.";
DataEncryptor keys=new DataEncryptor();
string encr=keys.EncryptString(message);

// later
string actual=keys.DecryptString(encr);
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个糟糕的答案,因为多样性可以使加密算法保持强大.我认为不需要对这种特殊方法的稳健性发出警告,因为毕竟没有加密机制是完美的. (3认同)
  • 多样性不是保持加密算法强大的原因.数学可以做到这一点:) DES(甚至是三重DES)是一种旧算法,对于大多数应用来说已不再足够强大. (2认同)

Uli*_*ses 19

如果您需要在内存中存储密码并希望加密,则应使用SecureString:

http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

对于更一般的用途,我会使用FIPS认可的算法,例如Advanced Encryption Standard,以前称为Rijndael.有关实现示例,请参阅此页面:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx


Ser*_*diy 18

如果您的目标是不支持的ASP.NET Core,则RijndaelManaged可以使用IDataProtectionProvider.

首先,配置您的应用程序以使用数据保护:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection();
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后,您将能够注入IDataProtectionProvider实例并使用它来加密/解密数据:

public class MyService : IService
{
    private const string Purpose = "my protection purpose";
    private readonly IDataProtectionProvider _provider;

    public MyService(IDataProtectionProvider provider)
    {
        _provider = provider;
    }

    public string Encrypt(string plainText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Protect(plainText);
    }

    public string Decrypt(string cipherText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Unprotect(cipherText);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此文章.

  • 关于您提供的文章的一个简短说明是,它指出:“_加密需要一个密钥,该密钥由数据保护系统创建和管理。创建密钥的默认生命周期为 90 天,并根据环境。密钥是临时的,因此数据保护API主要针对短期数据保护场景而设计_”。请注意,如果您实施此方法,您的密钥默认会在 90 天后过期。 (9认同)
  • 对我来说最好的一个,我正在使用 asp.netcore 3.1,谢谢。 (2认同)
  • 现在这应该是公认的答案,因为作者提到/正在要求“最现代(最好)的方式”和“最少涉及盐、关键”的实施。 (2认同)

SLa*_*aks 10

您可能正在寻找ProtectedData使用用户的登录凭据加密数据的类.

  • 我阅读了MSDN文档,但它没有说明如果我们将这些加密数据移动到具有不同凭据的另一台机器上会发生什么.所以我们仍然可以解密它? (3认同)
  • @RichardHein:我也这么认为,但似乎不是明智的建议。移动信息时,我不喜欢以普通的人类可读格式进行操作,否则所有这些加密操作的含义是什么。 (2认同)