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://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.

C#中byte[] 与string相互转化问题的更多相关文章

  1. C#中byte[]与string的转换

    1.        System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();        byte[] i ...

  2. java中byte转string的方法有哪些?

    1.第一种 byte b = 1; String valueOf = String.valueOf(b) 2.第二种 byte b = 1; String st = Byte.toString(b); ...

  3. C#图像处理:Stream 与 byte[] 相互转换,byte[]与string,Stream 与 File 相互转换等

    C# Stream 和 byte[] 之间的转换 一. 二进制转换成图片 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Ima ...

  4. 【转】java中byte, int的转换, byte String转换

    原文网址:http://freewind886.blog.163.com/blog/static/661924642011810236100/ 最近在做些与编解码相关的事情,又遇到了byte和int的 ...

  5. dotnet中Stream、string及byte[]的相关操作

    string与byte[](UTF-8) //string to byte[] string str = "abc中文"; //0x61 0x62 0x63 0xE4 0xB8 0 ...

  6. Python3中内置类型bytes和str用法及byte和string之间各种编码转换,python--列表,元组,字符串互相转换

    Python3中内置类型bytes和str用法及byte和string之间各种编码转换 python--列表,元组,字符串互相转换 列表,元组和字符串python中有三个内建函数:,他们之间的互相转换 ...

  7. C#中的Byte,String,Int,Hex之间的转换函数。

    /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary> ...

  8. C#中char[]与string之间的转换;byte[]与string之间的转化

    目录 1.char[]与string之间的转换 2.byte[]与string之间的转化 1.char[]与string之间的转换 //string 转换成 Char[] string str=&qu ...

  9. Android Drawable 和String 相互转化

    在我们经常应用开发中,经常用到将drawable和string相互转化.注意这情况最好用于小图片入icon等. public synchronized Drawable byteToDrawable( ...

随机推荐

  1. Tribonacci UVA - 12470 (简单的斐波拉契数列)(矩阵快速幂)

    题意:a1=0;a2=1;a3=2; a(n)=a(n-1)+a(n-2)+a(n-3);  求a(n) 思路:矩阵快速幂 #include<cstdio> #include<cst ...

  2. jquery clone

    clone([Even[,deepEven]]) 概述 克隆匹配的DOM元素并且选中这些克隆的副本. 在想把DOM文档中元素的副本添加到其他位置时这个函数非常有用. 参数 EventsBooleanV ...

  3. Arduino 433 + 串口

    http://www.freebuf.com/articles/wireless/105398.html /*本作品使用的例程中包含RCSwitch库文件用于信号的解码和编码发送*/ #include ...

  4. 深入浅出的webpack4构建工具--webpack4+vue+vuex+mock模拟后台数据(十九)

    mock的官网文档 mock官网 关于mockjs的优点,官网这样描述它:1)可以前后端分离.2)增加单元测试的真实性(通过随机数据,模拟各种场景).3)开发无侵入(不需要修改既有代码,就可以拦截 A ...

  5. 工具 Sublime日志染色

    工欲善其事,必先利其器. Preferences -> Browse Packages...

  6. 什么是Mixin模式:带实现的协议

    Mixin(织入)模式并不是GOF的<设计模式>归纳中的一种,但是在各种语言以及框架都会发现该模式(或者思想)的一些应用.简单来说,Mixin是带有全部实现或者部分实现的接口,其主要作用是 ...

  7. Linux安装RabbitMq-Centos7版本

    一.Linux系统中安装RabbitMQ 由于RabbitMQ依赖于Erlang,所以先要在机器上安装Erlang环境 单机版 1.安装GCC GCC-C++ Openssl等模块 yum -y in ...

  8. java中的异常区分

    在上图中,粉红色的部分为受检查的异常,其必须被try{}catch语句块所捕获,或者在方法中向外抛出异常 绿色的异常为运行时异常,需要程序员自行分辨是否要解决异常或者抛出异常,例空指针数组下标越界等等 ...

  9. CentOS7.2调整Mysql数据库最大连接数

    mysql数据库最大连接数=max_connections+11:root连接,用于管理员连接数据库进行维护操作查看最大连接数:show variables like 'max_connections ...

  10. LiveCharts文档-3开始-5序列Series

    原文:LiveCharts文档-3开始-5序列Series LiveCharts文档-3开始-5序列Series Strokes和Fills 笔触和填充 所有的Series都有笔触和填充属来处理颜色, ...