找回密码
 立即注册
首页 业界区 业界 .NET中的加密算法总结(自定义加密Helper类续) ...

.NET中的加密算法总结(自定义加密Helper类续)

旌磅箱 2025-5-29 16:03:04
1.1.1 摘要

          相信许多人都使用过.NET提供的加密算法,而且在使用的过程我们必须了解每种加密算法的特点(对称或非对称,密钥长度和初始化向量等等)。我也看到过很多人写过.NET中加密算法总结,但我发现个别存在一些问题,很多人喜欢罗列每种加密算法的具体实现,假设我们要求实现AES和Triple DES加密算法,的确可以很多地分别给出它们的具体实现。
         那我们真的有必要给出每个加密算法的具体实现吗?而且这样的设计不符合OOP设计思想,最重要的是我们要维护多个加密算法啊!OK接下来让我们实行一个可扩展和好维护的加密算法Helper。
   
  1.1.2 正文

         
1.jpeg

  
图1 Hash加密算法继承层次

  
 

         从上面的继承层次我们可以知道.NET中提供七种Hash加密算法,它们都继承于抽象类HashAlgorithm,而且我们经常使用MD5,SHA1和SHA256等加密算法。下面我们将给出MD5和SHA1的实现。
   
  
2.jpeg

  
图2 对称加密算法继承层次

  
 

         从上面的继承层次我们可以知道.NET中提供五种对称加密算法,它们都继承于抽象类SymmetricAlgorithm,下面我们将给出它们的通用实现。
   
  
3.jpeg

  
图3 非对称加密算法继承层次

  
 

         从上面的继承层次我们可以知道.NET中提供四种非对称加密算法,它们都继承于抽象类AsymmetricAlgorithm,下面我们将给出RSA实现。
         除了以上加密算法,.NET还提供了很多其他类型的加密,这里我们主要介绍一些常用的加密算法,如果大家需要了解的话可以查阅MSDN。OK接下来让我们给出Hash加密算法的实现吧。
   
  Hash加密算法

        在给出具体的算法实现之前,首先让我们回忆一下什么是Hash加密算法?
        Hash加密是通过使用hash函数对要加密的信息进行加密,然后生成相应的哈希值,那么我们可以定义一个hash()函数,要加密的信息m和加密后的哈希值h。
  
4.gif

   
        我们对信息m1和m2进行hash加密,就可以获取相应哈希值hash(m1)和hash(m2)。
  
5.gif

   
         如果信息m1=m2那么,那么将得到同一的哈希地址,但是信息m1!=m2也可能得到同一哈希地址,那么就发生了哈希冲突(collision),在一般的情况下,哈希冲突只能尽可能地减少,而不能完全避免。当发生哈希冲突时,我们要使用冲突解决方法,而主要的冲突解决方法:开放地址法、再哈希法、链地址法和建立一个公共溢出区。
   
  
6.jpeg

  
图4 Hash加密过程(图片来源wiki)

  
 

         现在让我们来实现通用的hash加密方法。
   
  1. /// <summary>
  2. /// Encrypts the specified hash algorithm.
  3. /// 1. Generates a cryptographic Hash Key for the provided text data.
  4. /// </summary>
  5. /// <param name="hashAlgorithm">The hash algorithm.</param>
  6. /// <param name="dataToHash">The data to hash.</param>
  7. /// <returns></returns>
  8. public static string Encrypt(HashAlgorithm hashAlgorithm, string dataToHash)
  9. {
  10.     var tabStringHex = new string[16];
  11.     var UTF8 = new System.Text.UTF8Encoding();
  12.     byte[] data = UTF8.GetBytes(dataToHash);
  13.     byte[] result = hashAlgorithm.ComputeHash(data);
  14.     var hexResult = new StringBuilder(result.Length);
  15.     for (int i = 0; i < result.Length; i++)
  16.     {
  17.         //// Convert to hexadecimal
  18.         hexResult.Append(result[i].ToString("X2"));
  19.     }
  20.     return hexResult.ToString();
  21. }
复制代码
 
       上面的加密方法包含一个HashAlgorithm类型的参数,我们可以传递继承于抽象类HashAlgorithm的具体hash算法(MD5,SHA1和SHA256等),通过继承多态性我们使得加密方法更加灵活、简单,最重要的是现在我们只需维护一个通用的加密方法就OK了。
       接着我们要添加判断加密后哈希值是否相等的方法,判断哈希值是否相等的方法IsHashMatch()方法。
 
  1. /// <summary>
  2. /// Determines whether [is hash match] [the specified hash algorithm].
  3. /// </summary>
  4. /// <param name="hashAlgorithm">The hash algorithm.</param>
  5. /// <param name="hashedText">The hashed text.</param>
  6. /// <param name="unhashedText">The unhashed text.</param>
  7. /// <returns>
  8. ///   <c>true</c> if [is hash match] [the specified hash algorithm];
  9. /// otherwise, <c>false</c>.
  10. /// </returns>
  11. public static bool IsHashMatch(HashAlgorithm hashAlgorithm,
  12.     string hashedText, string unhashedText)
  13. {
  14.     string hashedTextToCompare = Encrypt(
  15.         hashAlgorithm, unhashedText);
  16.     return (String.Compare(hashedText,
  17.         hashedTextToCompare, false) == 0);
  18. }
复制代码
对称加密算法

       现在我们完成了通用的Hash加密方法了,接下来我们继续介绍对称和非对称算法(具体Demo可以参考这里)。
       在实现对称加密算法之前,先让我们了解一下对称加密的过程,假设我们有一组数据要加密那么我们可以使用一个或一组密钥对数据进行加密解密,但存在一个问题对称加密算法的密钥长度不尽相同,如DES的密钥长度为64 bit,而AES的长度可以为128bit、192bit或256 bit,难道要我们hard code每种算法的密钥长度吗?能不能动态地产生对应算法的密钥呢?
       其实.NET已经提供我们根据不同的对称算法生成对应密钥的方法了,并且把这些方法都封装在PasswordDeriveBytes和Rfc2898DeriveBytes类中。
       首先让我们看一下PasswordDeriveBytes类包含两个方法CryptDeriveKey和GetBytes用来产生对应算法的密钥,现在让我们看一下它们如何产生密钥。
 
CryptDeriveKey:

 
  1. // The sample function.
  2. public void Encrypt()
  3. {
  4.     // The size of the IV property must be the same as the BlockSize property.
  5.     // Due to the RC2 block size is 64 bytes, so iv size also is 64 bytes.
  6.     var iv = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
  7.     var pdb = new PasswordDeriveBytes("pwd", null);
  8.     // Set the encrypted algorithm and export key algorithm.
  9.     // Then get the key base on encrypt algorithm.
  10.     byte[] key = pdb.CryptDeriveKey("RC2", "SHA1", 128, iv);
  11.     Console.WriteLine(key.Length * 8);
  12.     Console.WriteLine(new RC2CryptoServiceProvider().BlockSize);
  13.     // Creates an RC2 object to encrypt with the derived key
  14.     var rc2 = new RC2CryptoServiceProvider
  15.                   {
  16.                       Key = key,
  17.                       IV = new byte[] { 21, 22, 23, 24, 25, 26, 27, 28 }
  18.                   };
  19.     // now encrypt with it
  20.     byte[] plaintext = Encoding.UTF8.GetBytes("NeedToEncryptData");
  21.     using (var ms = new MemoryStream())
  22.     {
  23.         var cs = new CryptoStream(
  24.             ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);
  25.         cs.Write(plaintext, 0, plaintext.Length);
  26.         cs.Close();
  27.         byte[] encrypted = ms.ToArray();
  28.     }
  29. }
复制代码
       示意例子一:我们使用SHA1哈希算法为RC2加密算法生成128bit的密钥,这样我们就可以根据不同对称加密算法获取相应长度的密钥了,注意我们并没用动态地生成初始化向量iv,这是为了简单起见实际中不应该这样获取初始化向量。
        接下来让我们看一下通过PBKDF1和PBKDF2s算法生成密钥的实现。
 
PBKDF1

        GetBytes:PasswordDeriveBytes的GetBytes()方法实现了PBKDF1(Password Based Key Derivation Function)。
 
  PBKDF1算法过程:
  1.拼接密钥和盐:R0 = Pwd + Salt
  2.哈希加密过程:R1 = Hash(R2-1)
  ……..
  3.哈希加密过程:Rn = Hash(Rn - 1)
  4.n是迭代的次数(参考PBKDF1规范请点这里)
 
      现在我们对PBKDF1算法的原理有了初步的了解,接下来我们将通过GetBytes()调用该算法生成密钥。
 
  1. /// <summary>
  2. /// Uses the PBKDF1 to genernate key,
  3. /// then use it to encrypt plain text.
  4. /// </summary>
  5. public void PBKDF1()
  6. {
  7.     byte[] salt = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
  8.     // Creates an RC2 object to encrypt with the derived key
  9.     var pdb = new PasswordDeriveBytes("pwd", salt)
  10.     {IterationCount = 23, HashName = "SHA1"};
  11.     // Gets the key and iv.
  12.     byte[] key = pdb.GetBytes(16);
  13.     byte[] iv = pdb.GetBytes(8);
  14.     var rc2 = new RC2CryptoServiceProvider { Key = key, IV = iv };
  15.     byte[] plaintext = Encoding.UTF8.GetBytes("NeedToEncryptData");
  16.     using (var ms = new MemoryStream())
  17.     {
  18.         // Encrypts data.
  19.         var cs = new CryptoStream(
  20.             ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);
  21.         cs.Write(plaintext, 0, plaintext.Length);
  22.         cs.Close();
  23.         byte[] encrypted = ms.ToArray();
  24.     }
  25. }
复制代码
 
       示意例子二:我们使用PBKDF1算法为RC2加密算法生成128 bit的密钥和64 bit的初始化向量,要注意的是PasswordDeriveBytes的GetBytes()方法已经过时了,而它的替代项就是接下来要介绍的Rfc2898DeriveBytes的GetBytes()方法。
 
PBKDF2

       GetBytes:由于Rfc2898DeriveBytes的GetBytes()方法实现了PBKDF2算法,而且它也替代了PBKDF1过时的GetBytes()方法,所以我们推荐使用Rfc2898DeriveBytes的GetBytes()方法。
 
  1. /// <summary>
  2. /// Uses the PBKDF2 to genernate key,
  3. /// then use it to encrypt plain text.
  4. /// </summary>
  5. public void PBKDF2()
  6. {
  7.     byte[] salt = new byte[] { 23, 21, 32, 33, 46, 59, 60, 74 };
  8.     var rfc = new Rfc2898DeriveBytes("pwd", salt, 23);
  9.     // generate key and iv.
  10.     byte[] key = rfc.GetBytes(16);
  11.     byte[] iv = rfc.GetBytes(8);
  12.     // Creates an RC2 object to encrypt with the derived key
  13.     var rc2 = new RC2CryptoServiceProvider { Key = key, IV = iv };
  14.     // Encrypts the data.
  15.     byte[] plaintext = Encoding.UTF8.GetBytes("NeedToEncryptData");
  16.     using (var ms = new MemoryStream())
  17.     {
  18.         var cs = new CryptoStream(
  19.             ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);
  20.         cs.Write(plaintext, 0, plaintext.Length);
  21.         cs.Close();
  22.         byte[] encrypted = ms.ToArray();
  23.     }
  24. }
复制代码
 
       示意例子三:我们发现PBKDF2()方法和之前的PBKDF1()方法没有什么区别,就是无需指定加密密钥的哈希算法(参考PBKDF2规范请点这里)。
      前面通过三种方法来动态的生成加密密钥,而且我们将使用Rfc2898DeriveBytes的GetBytes()方法来获取密钥,那么接下来让我们使用该方法实现通用的对称加密算法吧!
 
7.jpeg

图5 对称算法加密过程

 

      首先我们对加密的平文进行编码,这里默认使用UTF8对平文进行编码,也可以使用其他编码方式,接着使用相应加密算法对编码后的平文进行加密,最后把加密后的Byte数组转换为Base64格式字符串返回。
 
  1. /// <summary>
  2. /// Encrypts with specified symmetric algorithm.
  3. /// Can be Aes, DES, RC2, Rijndael and TripleDES.
  4. /// </summary>
  5. /// <param name="algorithm">The symmertric algorithm (Aes, DES, RC2, Rijndael and TripleDES).</param>
  6. /// <param name="plainText">The plain text need to be encrypted.</param>
  7. /// <param name="key">The secret key to encrypt plain text.</param>
  8. /// <param name="iv">The iv should be 16 bytes.</param>
  9. /// <param name="salt">Salt to encrypt with.</param>
  10. /// <param name="pwdIterations">The number of iterations for plain text.</param>
  11. /// <param name="keySize">Size of the key.</param>
  12. /// <param name="cipherMode">The cipher mode.</param>
  13. /// <param name="paddingMode">The padding mode.</param>
  14. /// <returns></returns>
  15. public static byte[] Encrypt(SymmetricAlgorithm algorithm, byte[] plainText, string key, string iv,
  16.     string salt, int pwdIterations, int keySize, CipherMode cipherMode, PaddingMode paddingMode)
  17. {
  18.     if (null == plainText)
  19.         throw new ArgumentNullException("plainText");
  20.     if (null == algorithm)
  21.         throw new ArgumentNullException("algorithm");
  22.     if (String.IsNullOrEmpty(key))
  23.         throw new ArgumentNullException("key");
  24.     if (String.IsNullOrEmpty(iv))
  25.         throw new ArgumentNullException("iv");
  26.     if (String.IsNullOrEmpty(salt))
  27.         throw new ArgumentNullException("salt");
  28.     // Note the salt should be equal or greater that 64bit (8 byte).
  29.     var rfc = new Rfc2898DeriveBytes(key, salt.ToByteArray(), pwdIterations);
  30.     using (SymmetricAlgorithm symmAlgo = algorithm)
  31.     {
  32.         symmAlgo.Mode = cipherMode;
  33.         //symmAlgo.Padding = paddingMode;
  34.         byte[] cipherTextBytes = null;
  35.         using (var encryptor = symmAlgo.CreateEncryptor(
  36.             rfc.GetBytes(keySize / 8), iv.ToByteArray()))
  37.         {
  38.             using (var ms = new MemoryStream())
  39.             {
  40.                 using (var cs = new CryptoStream(
  41.                     ms, encryptor, CryptoStreamMode.Write))
  42.                 {
  43.                     cs.Write(plainText, 0, plainText.Length);
  44.                     cs.FlushFinalBlock();
  45.                     cipherTextBytes = ms.ToArray();
  46.                     ms.Close();
  47.                     cs.Close();
  48.                 }
  49.             }
  50.             symmAlgo.Clear();
  51.             return cipherTextBytes;
  52.         }
  53.     }
  54. }
复制代码
 
8.jpeg

图5 对称算法解密过程

 

        通过上图的解密过程,我们发现解密过程恰恰是加密的反向,首先把Base64格式的密文转换为Byte数组,接着使用对应的解密算法解密密文,最后对解密后的数据进行编码返回平文(默认使用UTF8)。
 
  1. /// <summary>
  2. /// Decrypts the specified algorithm.
  3. /// Can be Aes, DES, RC2, Rijndael and TripleDES.
  4. /// </summary>
  5. /// <param name="algorithm">The symmertric algorithm (Aes, DES, RC2, Rijndael and TripleDES).</param>
  6. /// <param name="cipherText">The cipher text.</param>
  7. /// <param name="key">The secret key to decrypt plain text.</param>
  8. /// <param name="iv">The iv should be 16 bytes.</param>
  9. /// <param name="salt">Salt to decrypt with.</param>
  10. /// <param name="pwdIterations">The number of iterations for plain text.</param>
  11. /// <param name="keySize">Size of the key.</param>
  12. /// <param name="cipherMode">The cipher mode.</param>
  13. /// <param name="paddingMode">The padding mode.</param>
  14. /// <returns></returns>
  15. public static byte[] Decrypt(SymmetricAlgorithm algorithm, byte[] cipherText,
  16.     string key, string iv, string salt, int pwdIterations, int keySize,
  17.     CipherMode cipherMode, PaddingMode paddingMode)
  18. {
  19.     if (null == cipherText)
  20.         throw new ArgumentNullException("cipherText");
  21.     if (null == algorithm)
  22.         throw new ArgumentNullException("algorithm");
  23.     if (String.IsNullOrEmpty(key))
  24.         throw new ArgumentNullException("key");
  25.     if (String.IsNullOrEmpty(iv))
  26.         throw new ArgumentNullException("iv");
  27.     if (String.IsNullOrEmpty(salt))
  28.         throw new ArgumentNullException("salt");
  29.     // Note the salt should be equal or greater that 64bit (8 byte).
  30.     var rfc = new Rfc2898DeriveBytes(key, salt.ToByteArray(), pwdIterations);
  31.     using (SymmetricAlgorithm symmAlgo = algorithm)
  32.     {
  33.         symmAlgo.Mode = cipherMode;
  34.         //symmAlgo.Padding = paddingMode;
  35.         byte[] plainTextBytes = new byte[cipherText.Length];
  36.         int cnt = -1;
  37.         using (var encryptor = symmAlgo.CreateDecryptor(
  38.             rfc.GetBytes(keySize / 8), iv.ToByteArray()))
  39.         {
  40.             using (var ms = new MemoryStream(cipherText))
  41.             {
  42.                 using (var cs = new CryptoStream(
  43.                     ms, encryptor, CryptoStreamMode.Read))
  44.                 {
  45.                     cnt = cs.Read(plainTextBytes, 0, plainTextBytes.Length);
  46.                     ms.Close();
  47.                     cs.Close();
  48.                 }
  49.             }
  50.         }
  51.         symmAlgo.Clear();
  52.         Array.Resize(ref plainTextBytes, cnt);
  53.         return plainTextBytes;
  54.     }
  55. }
复制代码
      在前面的加密和解密方法,我们通过Rfc2898DeriveBytes获取密码、salt 值和迭代次数,然后通过调用GetBytes方法生成密钥。
       现在我们已经完成了通用的对称加密算法,我们只需一组加密和解密方法就可以随意的使用任意一种对称加密算法了,而不是为每个加密和解密算法编写相应的加密和解密方法。
 
非对称加密算法

      .NET Framework中提供四种非对称加密算法(DSA,ECDiffieHellman, ECDsa和RSA),它们都继承于抽象类AsymmetricAlgorithm,接下来我们将提供RSA算法的实现。
      RSA加密算法是一种非对称和双钥加密算法,在公钥加密标准和电子商业中RSA被广泛使用。
      在双钥加密的情况下,密钥有两把,一把是公开的公钥,还有一把是不公开的私钥。
 
  双钥加密的原理如下:
  a) 公钥和私钥是一一对应的关系,有一把公钥就必然有一把与之对应的、独一无二的私钥,反之亦成立。
  b) 所有的(公钥, 私钥)对都是不同的。
  c) 用公钥可以解开私钥加密的信息,反之亦成立。
  d) 同时生成公钥和私钥应该相对比较容易,但是从公钥推算出私钥,应该是很困难或者是不可能的。
 
       现在的数字签名加密主要是使用RSA算法,什么是数字签名大家请点这里(中文)和这里(英文)。
       现在我们知道RSA算法是使用公钥和密钥进行加密和解密,所以我们先定义一个方法来生成公钥和密钥。
 
  1. /// <summary>
  2. /// Generates the RSA public and private key.
  3. /// </summary>
  4. /// <param name="algorithm">The algorithm to creates key.</param>
  5. /// <returns></returns>
  6. public static void GenerateRSAKey(RSACryptoServiceProvider algorithm)
  7. {
  8.     // Contains public and private key.
  9.     RSAPrivateKey = algorithm.ToXmlString(true);
  10.     using (var streamWriter = new StreamWriter("PublicPrivateKey.xml"))
  11.     {
  12.         streamWriter.Write(RSAPrivateKey);
  13.     }
  14.     // Only contains public key.
  15.     RSAPubicKey = algorithm.ToXmlString(false);
  16.     using (var streamWriter = new StreamWriter("PublicOnlyKey.xml"))
  17.     {
  18.         streamWriter.Write(RSAPubicKey);
  19.     }
  20. }
复制代码
 
       通过RSACryptoServiceProvider的ToXmlString()方法我们生成了一对公钥和密钥,当参数为true 表示同时包含 RSA 公钥和私钥,反之表示仅包含公钥。
 
  1. /// <summary>
  2. /// Encrypts with the specified RSA algorithm.
  3. /// </summary>
  4. /// <param name="rsa">A RSA object.</param>
  5. /// <param name="plainText">The plain text to decrypt.</param>
  6. /// <param name="key">The key.</param>
  7. /// <param name="encoding">The encoding.</param>
  8. /// <returns></returns>
  9. public static string Encrypt(RSACryptoServiceProvider rsa,
  10.     string plainText, string key, Encoding encoding)
  11. {
  12.     if (null == rsa)
  13.         throw new ArgumentNullException("rsa");
  14.     if (String.IsNullOrEmpty(plainText))
  15.         throw new ArgumentNullException("plainText");
  16.     if (String.IsNullOrEmpty(key))
  17.         throw new ArgumentNullException("key");
  18.     if (null == encoding)
  19.         throw new ArgumentNullException("encoding");
  20.     string publicKey;
  21.     // Reads public key.
  22.     using (var streamReader = new StreamReader("PublicOnlyKey.xml"))
  23.     {
  24.         publicKey = streamReader.ReadToEnd();
  25.     }
  26.     rsa.FromXmlString(publicKey);
  27.     byte[] cipherBytes = rsa.Encrypt(plainText.ToBytesEncoding(encoding), true);
  28.     rsa.Clear();
  29.     return cipherBytes.ToBase64String();
  30. }
复制代码
 
       接着我们定义RSA的加密方法,首先我们从流中读取密钥和公钥,然后传递给FromXmlString()方法,最后对平文进行加密。
 
  1. /// <summary>
  2. /// Decrypts with the specified RSA algorithm.
  3. /// </summary>
  4. /// <param name="rsa">a RSA object.</param>
  5. /// <param name="cipherText">The cipher text to encrypt.</param>
  6. /// <param name="key">The key.</param>
  7. /// <param name="encoding">The encoding.</param>
  8. /// <returns></returns>
  9. public static string Decrypt(RSACryptoServiceProvider rsa,
  10.     string cipherText, string key, Encoding encoding)
  11. {
  12.     string privateKey;
  13.     // Reads the private key.
  14.     using (var streamReader = new StreamReader("PublicPrivateKey.xml"))
  15.     {
  16.         privateKey = streamReader.ReadToEnd();
  17.     }
  18.     rsa.FromXmlString(privateKey);
  19.     byte[] plainBytes = rsa.Decrypt(cipherText.FromBase64String(), true);
  20.     rsa.Clear();
  21.     return plainBytes.FromByteToString(encoding);
  22. }
复制代码
 
       参照加密方法我们很快的实现RSA的解密方法,同样我们从流中读取密钥,然后传递给FromXmlString()方法,最后对密文进行解密,注意调用的是RSA算法的Decrypt()方法,在使用胶水代码时千万别忘记修改了。
       现在我们终于完成了通用的加密解密方法,接下来肯定是要测试一下这些方法的效果如何,这次我使用单元测试,如果大家要参考应用程序效果可以点这里。
 
  1. [TestMethod]
  2. public void TestStart()
  3. {
  4.     try
  5.     {
  6.         string cipherText;
  7.         string plainText;
  8.         #region Hash Algo
  9.         cipherText = CryptographyUtils.Encrypt(
  10.             CryptographyUtils.CreateHashAlgoMd5(), @"您们好(Hello everyone).");
  11.         Assert.IsTrue(CryptographyUtils.IsHashMatch(
  12.             CryptographyUtils.CreateHashAlgoMd5(),
  13.             cipherText, @"您们好(Hello everyone)."));
  14.         cipherText = CryptographyUtils.Encrypt(
  15.             CryptographyUtils.CreateHashAlgoSHA1(),
  16.             @"您们好(Hello everyone).");
  17.         Assert.IsTrue(CryptographyUtils.IsHashMatch(
  18.             CryptographyUtils.CreateHashAlgoSHA1(),
  19.             cipherText, @"您们好(Hello everyone)."));
  20.         #endregion
  21.         #region Asymm Algo
  22.         CryptographyUtils.GenerateRSAKey(CryptographyUtils.CreateAsymmAlgoRSA());
  23.         cipherText = CryptographyUtils.Encrypt(
  24.             CryptographyUtils.CreateAsymmAlgoRSA(), @"%dk>JK.RusH", @"c579D-E>?$)_");
  25.         plainText = CryptographyUtils.Decrypt(
  26.             CryptographyUtils.CreateAsymmAlgoRSA(), cipherText, @"c579D-E>?$)_");
  27.         Assert.AreEqual<string>(@"%dk>JK.RusH", plainText);
  28.         #endregion
  29.         #region Symm Algo
  30.         cipherText = CryptographyUtils.Encrypt(
  31.             CryptographyUtils.CreateSymmAlgoAes(),
  32.             "JK_huangJK_huangJK_huang黄钧航",
  33.             "JK_huangJK_huang", 256);
  34.         plainText = CryptographyUtils.Decrypt(
  35.             CryptographyUtils.CreateSymmAlgoAes(),
  36.        cipherText, "JK_huangJK_huang", 256);
  37.         Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航",
  38.             plainText);
  39.         cipherText = CryptographyUtils.Encrypt(
  40.             CryptographyUtils.CreateSymmAlgoDES(),
  41.        "JK_huangJK_huangJK_huang黄钧航",
  42.        "JK_huangJK_huang", 64);
  43.         plainText = CryptographyUtils.Decrypt(
  44.             CryptographyUtils.CreateSymmAlgoDES(),
  45.        cipherText, "JK_huangJK_huang", 64);
  46.         Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航",
  47.             plainText);
  48.         cipherText = CryptographyUtils.Encrypt(
  49.             CryptographyUtils.CreateSymmAlgoRC2(),
  50.             "JK_huangJK_huangJK_huang黄钧航",
  51.             "JK_huangJK_huang", 128);
  52.         plainText = CryptographyUtils.Decrypt(CryptographyUtils.CreateSymmAlgoRC2(),
  53.        cipherText, "JK_huangJK_huang", 128);
  54.         Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText);
  55.         cipherText = CryptographyUtils.Encrypt(
  56.             CryptographyUtils.CreateSymmAlgoRijndael(),
  57.             "JK_huangJK_huangJK_huang黄钧航",
  58.             "JK_huangJK_huang", 256);
  59.         plainText = CryptographyUtils.Decrypt(
  60.             CryptographyUtils.CreateSymmAlgoRijndael(),
  61.        cipherText, "JK_huangJK_huang", 256);
  62.         Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText);
  63.         cipherText = CryptographyUtils.Encrypt(
  64.             CryptographyUtils.CreateSymmAlgoTripleDes(),
  65.             "JK_huangJK_huangJK_huang黄钧航",
  66.             "JK_huangJK_huang", 192);
  67.         plainText = CryptographyUtils.Decrypt(
  68.             CryptographyUtils.CreateSymmAlgoTripleDes(),
  69.        cipherText, "JK_huangJK_huang", 192);
  70.         Assert.AreEqual<string>("JK_huangJK_huangJK_huang黄钧航", plainText);
  71.         #endregion
  72.     }
  73.     catch (Exception ex)
  74.     {
  75.         Debug.Assert(false, ex.Message);
  76.     }
  77. }
复制代码
 
9.jpeg

图6 单元测试结果

 

1.1.3 总结

       本文给出了.NET中的一些加密算法的通用实现(哈希加密,对称加密和非对称加密算法),由于加密和解密的方法都是比较固定,而且每中算法有具有其特性,所以这里我们给出了它们的实现,而且我们可以把上的方法封装在一个加密Helper类,这样可以大大提高我们开发效率,而且它充分的利用多态性使得加密算法灵活性和维护性大大提高。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册