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. Unity手游之路手游代码更新策略探讨

    版权声明: https://blog.csdn.net/janeky/article/details/25923151 这几个月公司项目非常忙.加上家里事情也多,所以blog更新一直搁置了. 近期在项 ...

  2. 转://Linux MultiPath多路径软件实施说明

    Multipath的工作原理 当multipath启动的时候,它通过系统命令scsi_id -eg -s /block/sdX得到proc/partitions 里面所有块设备的 UUID(unive ...

  3. Mashmokh and Numbers CodeForces - 415C

    题意:就是n个数和k,每次按顺序那两个数,最大公约数的和为k. 思路:注意:当n=1,k>0时一定不存在,还有n=1,k=0时为1即可. 然后再正常情况下,第一组的最大公约数为k-n/2+1即可 ...

  4. 对JavaScript垃圾回收机制的理解?

    (1)标记清除(Mark and sweep) 这是JavaScript最常见的垃圾回收方式,当变量进入执行环境的时候,比如函数中声明一个变量,垃圾回收器将其标记为”进入环境”,当变量离开环境的时候( ...

  5. 2017-2018-2 20155314《网络对抗技术》Exp9 Web安全基础

    2017-2018-2 20155314<网络对抗技术>Exp9 Web安全基础 目录 实验目标 实验内容 实验环境 基础问题回答 预备知识 实验步骤--WebGoat实践 0x10 We ...

  6. sh脚本文件的运行

    sh脚本文件的运行mac终端下运行shell脚本 1.写好自己的 脚本,比如test-bash.sh 2.打开终端 执行,方法一: 输入命令 ./test-bash.sh , 方法二:直接把 aa.s ...

  7. JavaScript高级程序设计学习(四)之引用类型(续)

    一.Date类型 其实引用类型和相关的操作方法,远远不止昨天的所说的那些,还有一部分今天继续补充. 在java中日期Date,它所属的包有sql包,也有util包.我个人比较喜欢用util包的.理由, ...

  8. Nginx完美解决前后端分离端口号不同导致的跨域问题

    笔者在做前后端分离系统时,出现了很多坑,比如前后端的url域名相同,但是端口号不同.例如前端页面为:http://127.0.0.1/ , 后端api根路径为 http://127.0.0.1:888 ...

  9. struts2中ajax的使用

    前面写过原生js实现ajax的博客,但是用起来不是太方便,jquery对原生的js进行了很好的封装,使用起来也更简单:但是在项目中使用了struts2,处理ajax却又不同,花了几天时间研究,终于解决 ...

  10. Kafka笔记--常用指令(新建、删除topic)

    新建topic ./kafka-topics.sh --zookeeper 192.168.1.160:2181 --create --topic kafkatestsmall2 --partitio ...