栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用C#加密和解密字符串[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用C#加密和解密字符串[重复]

2015年12月23日更新:由于此答案似乎获得了很多好评,因此我已对其进行了更新,以修复愚蠢的错误并根据注释和反馈总体上改进代码。
有关特定改进的列表,请参见文章末尾。

正如其他人所说,密码术并不简单,因此最好避免“自己动手”加密算法。

但是,您可以围绕内置

RijndaelManaged
加密类之类的东西“滚动自己的”包装器类。

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

RijndaelManaged
实际上,该类确实确实需要您“弄乱”字节数组,盐,键,初始化向量等,但这正是可以在“包装”类中稍微抽象出来的那种细节。

下面的类是我前一段时间写的,可以完全执行您要执行的操作,一个简单的单一方法调用,允许使用基于字符串的密码对一些基于字符串的纯文本进行加密,并且生成的加密字符串也被表示为字符串。当然,有一种等效的方法可以用相同的密码解密加密的字符串。

与该代码的第一个版本每次都使用完全相同的salt和IV值不同,此新版本每次都会生成随机的salt和IV值。由于Salt和IV在给定字符串的加密和解密之间必须相同,因此Salt和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 pre 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;        }    }}

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

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();        }    }}

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

2015年12月23日更新: 该代码的特定改进列表如下:

  • 修复了一个愚蠢的错误,该错误的加密和解密之间的编码不同。由于生成盐和IV值的机制已经改变,因此不再需要编码。
  • 由于盐/ IV的更改,先前的代码注释错误地指示了对16个字符串进行编码的UTF8会产生32个字节,因此不再适用(因为不再需要编码)。
  • 被取代的PBKDF1算法的使用已被更现代的PBKDF2算法的使用所取代。
  • 现在,密码派生已正确添加了盐,而以前则完全没有添加盐(挤压了另一个愚蠢的错误)。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号