C#中byte[] 与string相互转化问题

 using System;
using System.IO;
using System.Security.Cryptography; namespace ShareX.UploadersLib.OtherServices
{
class TripleDESManagedExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!"; // Create a new instance of the TripleDESCryptoServiceProvider
// class. This generates a new key and initialization
// vector (IV).
using (TripleDESCryptoServiceProvider myTripleDES = new TripleDESCryptoServiceProvider())
{
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myTripleDES.Key, myTripleDES.IV); string str0 = System.Text.Encoding.Default.GetString(encrypted);
byte[] bt0 = System.Text.Encoding.Default.GetBytes(str0); string str1 = Convert.ToBase64String(encrypted);
byte[] bt1 = Convert.FromBase64String(str1); // Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, myTripleDES.Key, myTripleDES.IV);
string roundtrip1 = DecryptStringFromBytes(bt1, myTripleDES.Key, myTripleDES.IV); //Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
Console.WriteLine("Round Trip 1: {0}", roundtrip1);
} }
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= )
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= )
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= )
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an TripleDESCryptoServiceProvider object
// with the specified key and IV.
using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
{
tdsAlg.Key = Key;
tdsAlg.IV = IV; // Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = tdsAlg.CreateEncryptor(tdsAlg.Key, tdsAlg.IV); // Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{ //Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
} // Return the encrypted bytes from the memory stream.
return encrypted; } static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= )
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= )
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= )
throw new ArgumentNullException("Key"); // Declare the string used to hold
// the decrypted text.
string plaintext = null; // Create an TripleDESCryptoServiceProvider object
// with the specified key and IV.
using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
{
tdsAlg.Key = Key;
tdsAlg.IV = IV; // Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = tdsAlg.CreateDecryptor(tdsAlg.Key, tdsAlg.IV); // Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
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();
}
}
} } return plaintext; }
}
}

参考文章:http://*.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.

上一篇:rsync传输性能测试总结 转


下一篇:power desinger 学习笔记<八>