C#/.NET字符串加密和解密實現(AES和RSA代碼舉例)

在不少C#項目中,都須要實現對字符串的加密和解密,那麼如何實現呢?如今對稱密鑰加密中最流行的就是AES加密法。html

密碼學中的高級加密標準(Advanced Encryption Standard,AES),又稱Rijndael加密法,是美國聯邦政府採用的一種區塊加密標準。這個標準用來替代原先的DES,已經被多方分析且廣爲全世界所使用。通過五年的甄選流程,高級加密標準由美國國家標準與技術研究院 (NIST)於2001年11月26日發佈於FIPS PUB 197,並在2002年5月26日成爲有效的標準。2006年,高級加密標準已然成爲對稱密鑰加密中最流行的算法之一。算法

  在這裏能夠提供一個基於AES加密和解密的實現代碼:ide

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
public  class  Crypto
{
     private  static  byte [] _salt = Encoding.ASCII.GetBytes( "o6806642kbM7c5" );
     /// <summary>
     /// Encrypt the given string using AES.  The string can be decrypted using
     /// DecryptStringAES().  The sharedSecret parameters must match.
     /// </summary>
     /// <param name="plainText">The text to encrypt.</param>
     /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
     public  static  string  EncryptStringAES( string  plainText,  string  sharedSecret)
     {
         if  ( string .IsNullOrEmpty(plainText))
             throw  new  ArgumentNullException( "plainText" );
         if  ( string .IsNullOrEmpty(sharedSecret))
             throw  new  ArgumentNullException( "sharedSecret" );
         string  outStr =  null ;                        // Encrypted string to return
         RijndaelManaged aesAlg =  null ;               // RijndaelManaged object used to encrypt the data.
         try
         {
             // generate the key from the shared secret and the salt
             Rfc2898DeriveBytes key =  new  Rfc2898DeriveBytes(sharedSecret, _salt);
             // Create a RijndaelManaged object
             aesAlg =  new  RijndaelManaged();
             aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
             // Create a decryptor to perform the stream transform.
             ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
             // Create the streams used for encryption.
             using  (MemoryStream msEncrypt =  new  MemoryStream())
             {
                 // prepend the IV
                 msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0,  sizeof ( int ));
                 msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                 using  (CryptoStream csEncrypt =  new  CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                 {
                     using  (StreamWriter swEncrypt =  new  StreamWriter(csEncrypt))
                     {
                         //Write all data to the stream.
                         swEncrypt.Write(plainText);
                     }
                 }
                 outStr = Convert.ToBase64String(msEncrypt.ToArray());
             }
         }
         finally
         {
             // Clear the RijndaelManaged object.
             if  (aesAlg !=  null )
                 aesAlg.Clear();
         }
         // Return the encrypted bytes from the memory stream.
         return  outStr;
     }
     /// <summary>
     /// Decrypt the given string.  Assumes the string was encrypted using
     /// EncryptStringAES(), using an identical sharedSecret.
     /// </summary>
     /// <param name="cipherText">The text to decrypt.</param>
     /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
     public  static  string  DecryptStringAES( string  cipherText,  string  sharedSecret)
     {
         if  ( string .IsNullOrEmpty(cipherText))
             throw  new  ArgumentNullException( "cipherText" );
         if  ( string .IsNullOrEmpty(sharedSecret))
             throw  new  ArgumentNullException( "sharedSecret" );
         // Declare the RijndaelManaged object
         // used to decrypt the data.
         RijndaelManaged aesAlg =  null ;
         // Declare the string used to hold
         // the decrypted text.
         string  plaintext =  null ;
         try
         {
             // generate the key from the shared secret and the salt
             Rfc2898DeriveBytes key =  new  Rfc2898DeriveBytes(sharedSecret, _salt);
             // Create the streams used for decryption.              
             byte [] bytes = Convert.FromBase64String(cipherText);
             using  (MemoryStream msDecrypt =  new  MemoryStream(bytes))
             {
                 // Create a RijndaelManaged object
                 // with the specified key and IV.
                 aesAlg =  new  RijndaelManaged();
                 aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                 // Get the initialization vector from the encrypted stream
                 aesAlg.IV = ReadByteArray(msDecrypt);
                 // Create a decrytor to perform the stream transform.
                 ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                 using  (CryptoStream csDecrypt =  new  CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                 {
                     using  (StreamReader srDecrypt =  new  StreamReader(csDecrypt))
                         // Read the decrypted bytes from the decrypting stream
                         // and place them in a string.
                         plaintext = srDecrypt.ReadToEnd();
                 }
             }
         }
         finally
         {
             // Clear the RijndaelManaged object.
             if  (aesAlg !=  null )
                 aesAlg.Clear();
         }
         return  plaintext;
     }
     private  static  byte [] ReadByteArray(Stream s)
     {
         byte [] rawLength =  new  byte [ sizeof ( int )];
         if  (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
         {
             throw  new  SystemException( "Stream did not contain properly formatted byte array" );
         }
         byte [] buffer =  new  byte [BitConverter.ToInt32(rawLength, 0)];
         if  (s.Read(buffer, 0, buffer.Length) != buffer.Length)
         {
             throw  new  SystemException( "Did not read byte array properly" );
         }
         return  buffer;
     }
}

   另外再提供一段基於RSA的加密算法,RSA公鑰加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美國麻省理工學院)開發的。RSA取名來自開發他們三者的名字。RSA是目前最有影響力的公鑰加密算法,它可以抵抗到目前爲止已知的全部密碼攻擊,已被ISO推薦爲公鑰數據加密標準。RSA算法基於一個十分簡單的數論事實:將兩個大素數相乘十分容易,但那時想要對其乘積進行因式分解卻極其困難,所以能夠將乘積公開做爲加密密鑰。
加密

C#中實現RSA加密代碼以下:spa

1
2
3
4
5
6
var  provider =  new  System.Security.Cryptography.RSACryptoServiceProvider();
provider.ImportParameters(your_rsa_key);
var  encryptedBytes = provider.Encrypt(
     System.Text.Encoding.UTF8.GetBytes( "Hello World!" ),  true );
string  decryptedTest = System.Text.Encoding.UTF8.GetString(
     provider.Decrypt(encryptedBytes,  true ));



轉載請註明:文章轉載自:[169IT-最新最全的IT資訊]
本文標題:C#/.NET字符串加密和解密實現(AES和RSA代碼舉例)code

相關文章
相關標籤/搜索