C#中byte[] 與string相互轉化問題

rgqancy發表於2016-09-06
  1 using System;
  2 using System.IO;
  3 using System.Security.Cryptography;
  4 
  5 namespace ShareX.UploadersLib.OtherServices
  6 {
  7     class TripleDESManagedExample
  8     {
  9         public static void Main()
 10         {
 11             try
 12             {
 13                 string original = "Here is some data to encrypt!";
 14 
 15                 // Create a new instance of the TripleDESCryptoServiceProvider
 16                 // class.  This generates a new key and initialization 
 17                 // vector (IV).
 18                 using (TripleDESCryptoServiceProvider myTripleDES = new TripleDESCryptoServiceProvider())
 19                 {
 20                     // Encrypt the string to an array of bytes.
 21                     byte[] encrypted = EncryptStringToBytes(original, myTripleDES.Key, myTripleDES.IV);
 22 
 23                     string str0 = System.Text.Encoding.Default.GetString(encrypted);
 24                     byte[] bt0 = System.Text.Encoding.Default.GetBytes(str0);
 25 
 26                     string str1 = Convert.ToBase64String(encrypted);
 27                     byte[] bt1 = Convert.FromBase64String(str1);
 28 
 29                     // Decrypt the bytes to a string.
 30                     string roundtrip = DecryptStringFromBytes(encrypted, myTripleDES.Key, myTripleDES.IV);
 31                     string roundtrip1 = DecryptStringFromBytes(bt1, myTripleDES.Key, myTripleDES.IV);
 32 
 33                     //Display the original data and the decrypted data.
 34                     Console.WriteLine("Original:   {0}", original);
 35                     Console.WriteLine("Round Trip: {0}", roundtrip);
 36                     Console.WriteLine("Round Trip 1: {0}", roundtrip1);
 37                 }
 38 
 39             }
 40             catch (Exception e)
 41             {
 42                 Console.WriteLine("Error: {0}", e.Message);
 43             }
 44         }
 45         static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
 46         {
 47             // Check arguments.
 48             if (plainText == null || plainText.Length <= 0)
 49                 throw new ArgumentNullException("plainText");
 50             if (Key == null || Key.Length <= 0)
 51                 throw new ArgumentNullException("Key");
 52             if (IV == null || IV.Length <= 0)
 53                 throw new ArgumentNullException("Key");
 54             byte[] encrypted;
 55             // Create an TripleDESCryptoServiceProvider object
 56             // with the specified key and IV.
 57             using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
 58             {
 59                 tdsAlg.Key = Key;
 60                 tdsAlg.IV = IV;
 61 
 62                 // Create a decrytor to perform the stream transform.
 63                 ICryptoTransform encryptor = tdsAlg.CreateEncryptor(tdsAlg.Key, tdsAlg.IV);
 64 
 65                 // Create the streams used for encryption.
 66                 using (MemoryStream msEncrypt = new MemoryStream())
 67                 {
 68                     using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
 69                     {
 70                         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
 71                         {
 72 
 73                             //Write all data to the stream.
 74                             swEncrypt.Write(plainText);
 75                         }
 76                         encrypted = msEncrypt.ToArray();
 77                     }
 78                 }
 79             }
 80 
 81 
 82             // Return the encrypted bytes from the memory stream.
 83             return encrypted;
 84 
 85         }
 86 
 87         static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
 88         {
 89             // Check arguments.
 90             if (cipherText == null || cipherText.Length <= 0)
 91                 throw new ArgumentNullException("cipherText");
 92             if (Key == null || Key.Length <= 0)
 93                 throw new ArgumentNullException("Key");
 94             if (IV == null || IV.Length <= 0)
 95                 throw new ArgumentNullException("Key");
 96 
 97             // Declare the string used to hold
 98             // the decrypted text.
 99             string plaintext = null;
100 
101             // Create an TripleDESCryptoServiceProvider object
102             // with the specified key and IV.
103             using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
104             {
105                 tdsAlg.Key = Key;
106                 tdsAlg.IV = IV;
107 
108                 // Create a decrytor to perform the stream transform.
109                 ICryptoTransform decryptor = tdsAlg.CreateDecryptor(tdsAlg.Key, tdsAlg.IV);
110 
111                 // Create the streams used for decryption.
112                 using (MemoryStream msDecrypt = new MemoryStream(cipherText))
113                 {
114                     using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
115                     {
116                         using (StreamReader srDecrypt = new StreamReader(csDecrypt))
117                         {
118 
119                             // Read the decrypted bytes from the decrypting stream
120                             // and place them in a string.
121                             plaintext = srDecrypt.ReadToEnd();
122                         }
123                     }
124                 }
125 
126             }
127 
128             return plaintext;
129 
130         }
131     }
132 }

 參考文章:http://stackoverflow.com/questions/1003275/how-to-convert-byte-to-string

There're at least four different ways doing this conversion.

    1. Encoding's GetString
      , but you won't be able to get the original bytes back if those bytes have non-ASCII characters.

    2. BitConverter.ToString
      The output is a "-" delimited string, but there's no .NET built-in method to convert the string back to byte array.

    3. Convert.ToBase64String
      You can easily convert the output string back to byte array by using Convert.FromBase64String.
      Note: The output string could contain '+', '/' and '='. If you want to use the string in a URL, you need to explicitly encode it.

    4. HttpServerUtility.UrlTokenEncode
      You can easily convert the output string back to byte array by using HttpServerUtility.UrlTokenDecode. The output string is already URL friendly! The downside is it needs System.Web assembly if your project is not a web project.

相關文章