C#里的一些加密解密标准函数示例——DES,SHA1,RSA

来源:互联网 发布:500价位的耳机知乎 编辑:程序博客网 时间:2024/06/06 19:50

注:以下示例需引用命名空间  using System.Security.Cryptography


一. DES 加密、解密

我相信一下注释相当清楚了,加上我博客里关于DES的文章确实不少,所以DES不做任何解释,怎么调用就更不用解释了吧,呵呵:

view plain
  1. //默认密钥向量  
  2.  private byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };  
  3.  /// <summary>  
  4.  /// DES加密字符串  
  5.  /// </summary>  
  6.  /// <param name="encryptString">待加密的字符串</param>  
  7.  /// <param name="encryptKey">加密密钥,要求为8位</param>  
  8.  /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>  
  9.  public string EncryptDES(string encryptString, string encryptKey)  
  10.  {  
  11.      try  
  12.      {  
  13.          byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));  
  14.          byte[] rgbIV = Keys;  
  15.          byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);  
  16.          DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();  
  17.          MemoryStream mStream = new MemoryStream();  
  18.          CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  19.          cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  20.          cStream.FlushFinalBlock();  
  21.          return Convert.ToBase64String(mStream.ToArray());  
  22.      }  
  23.      catch  
  24.      {  
  25.          return encryptString;  
  26.      }  
  27.  }  
  28.   
  29.  /// <summary>  
  30.  /// DES解密字符串  
  31.  /// </summary>  
  32.  /// <param name="decryptString">待解密的字符串</param>  
  33.  /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>  
  34.  /// <returns>解密成功返回解密后的字符串,失败返源串</returns>  
  35.  public string DecryptDES(string decryptString, string decryptKey)  
  36.  {  
  37.      try  
  38.      {  
  39.          byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));  
  40.          byte[] rgbIV = Keys;  
  41.          byte[] inputByteArray = Convert.FromBase64String(decryptString);  
  42.          DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();  
  43.          MemoryStream mStream = new MemoryStream();  
  44.          CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  45.          cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  46.          cStream.FlushFinalBlock();  
  47.          return Encoding.UTF8.GetString(mStream.ToArray());  
  48.      }  
  49.      catch  
  50.      {  
  51.          return decryptString;  
  52.      }  
  53.  }  

二. SHA1 加密 (HASH算法没有解密)
安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于2^64位的消息,SHA1会产生一个160位的消息摘要。当接收到消息的时候,这个消息摘要可以用来验证数据的完整性。在传输的过程中,数据很可能会发生变化,那么这时候就会产生不同的消息摘要。

SHA1有如下特性:不可以从消息摘要中复原信息;两个不同的消息不会产生同样的消息摘要。

代码如下:

view plain
  1. /// <summary>  
  2. /// use sha1 to encrypt string  
  3. /// </summary>  
  4. public string SHA1_Encrypt(string Source_String)  
  5. {  
  6.     byte[] StrRes = Encoding.Default.GetBytes(Source_String);  
  7.     HashAlgorithm iSHA = new SHA1CryptoServiceProvider();  
  8.     StrRes = iSHA.ComputeHash(StrRes);  
  9.     StringBuilder EnText = new StringBuilder();  
  10.     foreach (byte iByte in StrRes)  
  11.     {  
  12.         EnText.AppendFormat("{0:x2}", iByte);  
  13.     }  
  14.     return EnText.ToString();  
  15. }  

三.RSA 加密、解密 (本例来自 MSDN)

RSA加密算法是一种非对称加密算法。在公钥加密标准和电子商业中RSA被广泛使用。RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的。

RSA算法的可靠性基于分解极大的整数是很困难的。假如有人找到一种很快的分解因子的算法的话,那么用RSA加密的信息的可靠性就肯定会极度下降。但找到这样的算法的可能性是非常小的。今天只有短的RSA钥匙才可能被强力方式解破。到2008年为止,世界上还没有任何可靠的攻击RSA算法的方式。只要其钥匙的长度足够长,用RSA加密的信息实际上是不能被解破的。

具体算法过程请参考http://zh.wikipedia.org/wiki/RSA%E5%8A%A0%E5%AF%86%E6%BC%94%E7%AE%97%E6%B3%95

代码示例如下(来自MSDN):

view plain
  1. using System;  
  2. using System.Security.Cryptography;  
  3. using System.IO;   
  4. using System.Text;  
  5.   
  6. namespace Microsoft.Samples.Security.PublicKey  
  7. {  
  8.   class App  
  9.   {  
  10.     // Main entry point  
  11.     static void Main(string[] args)  
  12.     {  
  13.       // Instantiate 3 People for example. See the Person class below  
  14.       Person alice = new Person("Alice");  
  15.       Person bob = new Person("Bob");  
  16.       Person steve = new Person("Steve");  
  17.   
  18.       // Messages that will exchanged. See CipherMessage class below  
  19.       CipherMessage aliceMessage;  
  20.       CipherMessage bobMessage;  
  21.       CipherMessage steveMessage;  
  22.   
  23.       // Example of encrypting/decrypting your own message  
  24.       Console.WriteLine("Encrypting/Decrypting Your Own Message");  
  25.       Console.WriteLine("-----------------------------------------");  
  26.   
  27.       // Alice encrypts a message using her own public key  
  28.       aliceMessage = alice.EncryptMessage("Alice wrote this message");  
  29.       // then using her private key can decrypt the message  
  30.       alice.DecryptMessage(aliceMessage);  
  31.       // Example of Exchanging Keys and Messages  
  32.       Console.WriteLine();  
  33.       Console.WriteLine("Exchanging Keys and Messages");  
  34.       Console.WriteLine("-----------------------------------------");  
  35.   
  36.       // Alice Sends a copy of her public key to Bob and Steve  
  37.       bob.GetPublicKey(alice);  
  38.       steve.GetPublicKey(alice);  
  39.   
  40.       // Bob and Steve both encrypt messages to send to Alice  
  41.       bobMessage = bob.EncryptMessage("Hi Alice! - Bob.");  
  42.       steveMessage = steve.EncryptMessage("How are you? - Steve");  
  43.   
  44.       // Alice can decrypt and read both messages  
  45.       alice.DecryptMessage(bobMessage);  
  46.       alice.DecryptMessage(steveMessage);  
  47.   
  48.       Console.WriteLine();  
  49.       Console.WriteLine("Private Key required to read the messages");  
  50.       Console.WriteLine("-----------------------------------------");  
  51.   
  52.       // Steve cannot read the message that Bob encrypted  
  53.       steve.DecryptMessage(bobMessage);  
  54.       // Not even Bob can use the Message he encrypted for Alice.  
  55.       // The RSA private key is required to decrypt the RS2 key used  
  56.       // in the decryption.  
  57.       bob.DecryptMessage(bobMessage);  
  58.   
  59.     } // method Main  
  60.   } // class App  
  61.   
  62.   class CipherMessage  
  63.   {  
  64.     public byte[] cipherBytes;  // RC2 encrypted message text  
  65.     public byte[] rc2Key;       // RSA encrypted rc2 key  
  66.     public byte[] rc2IV;        // RC2 initialization vector  
  67.   }  
  68.   
  69.   class Person  
  70.   {  
  71.     private RSACryptoServiceProvider rsa;  
  72.     private RC2CryptoServiceProvider rc2;  
  73.     private string name;  
  74.   
  75.     // Maximum key size for the RC2 algorithm  
  76.     const int keySize = 128;  
  77.   
  78.     // Person constructor  
  79.     public Person(string p_Name)  
  80.     {  
  81.       rsa = new RSACryptoServiceProvider();  
  82.       rc2 = new RC2CryptoServiceProvider();  
  83.       rc2.KeySize = keySize;  
  84.       name = p_Name;  
  85.     }  
  86.   
  87.     // Used to send the rsa public key parameters  
  88.     public RSAParameters SendPublicKey()   
  89.     {  
  90.       RSAParameters result = new RSAParameters();  
  91.       try   
  92.       {  
  93.         result = rsa.ExportParameters(false);  
  94.       }  
  95.       catch (CryptographicException e)  
  96.       {  
  97.         Console.WriteLine(e.Message);  
  98.       }  
  99.       return result;  
  100.     }  
  101.   
  102.     // Used to import the rsa public key parameters  
  103.     public void GetPublicKey(Person receiver)  
  104.     {  
  105.       try   
  106.       {  
  107.         rsa.ImportParameters(receiver.SendPublicKey());   
  108.       }  
  109.       catch (CryptographicException e)  
  110.       {  
  111.         Console.WriteLine(e.Message);  
  112.       }  
  113.     }  
  114.   
  115.     public CipherMessage EncryptMessage(string text)  
  116.     {  
  117.       // Convert string to a byte array  
  118.       CipherMessage message = new CipherMessage();  
  119.       byte[] plainBytes = Encoding.Unicode.GetBytes(text.ToCharArray());  
  120.   
  121.       // A new key and iv are generated for every message  
  122.       rc2.GenerateKey();  
  123.       rc2.GenerateIV();  
  124.   
  125.       // The rc2 initialization doesnt need to be encrypted, but will  
  126.       // be used in conjunction with the key to decrypt the message.  
  127.       message.rc2IV = rc2.IV;  
  128.       try   
  129.       {  
  130.         // Encrypt the RC2 key using RSA encryption  
  131.         message.rc2Key = rsa.Encrypt(rc2.Key, false);  
  132.       }  
  133.       catch (CryptographicException e)  
  134.       {  
  135.         // The High Encryption Pack is required to run this  sample  
  136.         // because we are using a 128-bit key. See the readme for  
  137.         // additional information.  
  138.         Console.WriteLine("Encryption Failed. Ensure that the" +   
  139.           " High Encryption Pack is installed.");  
  140.         Console.WriteLine("Error Message: " + e.Message);  
  141.         Environment.Exit(0);  
  142.       }  
  143.       // Encrypt the Text Message using RC2 (Symmetric algorithm)  
  144.       ICryptoTransform sse = rc2.CreateEncryptor();  
  145.       MemoryStream ms = new MemoryStream();  
  146.       CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);  
  147.       try  
  148.       {  
  149.           cs.Write(plainBytes, 0, plainBytes.Length);  
  150.           cs.FlushFinalBlock();  
  151.           message.cipherBytes = ms.ToArray();  
  152.       }  
  153.       catch (Exception e)  
  154.       {  
  155.           Console.WriteLine(e.Message);  
  156.       }       
  157.       finally  
  158.       {  
  159.         ms.Close();  
  160.         cs.Close();  
  161.       }  
  162.       return message;  
  163.     } // method EncryptMessage  
  164.   
  165.   
  166.     public void DecryptMessage(CipherMessage message)  
  167.     {  
  168.       // Get the RC2 Key and Initialization Vector  
  169.       rc2.IV = message.rc2IV;  
  170.       try   
  171.       {  
  172.         // Try decrypting the rc2 key  
  173.         rc2.Key = rsa.Decrypt(message.rc2Key, false);  
  174.       }  
  175.       catch (CryptographicException e)  
  176.       {  
  177.         Console.WriteLine("Decryption Failed: " + e.Message);  
  178.         return;  
  179.       }  
  180.         
  181.       ICryptoTransform ssd = rc2.CreateDecryptor();  
  182.       // Put the encrypted message in a memorystream  
  183.       MemoryStream ms = new MemoryStream(message.cipherBytes);  
  184.       // the CryptoStream will read cipher text from the MemoryStream  
  185.       CryptoStream cs = new CryptoStream(ms, ssd, CryptoStreamMode.Read);  
  186.       byte[] initialText = new Byte[message.cipherBytes.Length];  
  187.   
  188.       try  
  189.       {  
  190.           // Decrypt the message and store in byte array  
  191.           cs.Read(initialText, 0, initialText.Length);  
  192.       }  
  193.       catch (Exception e)  
  194.       {  
  195.           Console.WriteLine(e.Message);  
  196.       }        
  197.       finally   
  198.       {  
  199.         ms.Close();  
  200.         cs.Close();  
  201.       }  
  202.   
  203.       // Display the message received  
  204.       Console.WriteLine(name + " received the following message:");  
  205.       Console.WriteLine("  " + Encoding.Unicode.GetString(initialText));  
  206.     } // method DecryptMessage  
  207.   } // class Person  
  208. // namespace PublicKey