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://stackoverflow.com/questions/1003275/how-to-convert-byte-to-string
There're at least four different ways doing this conversion.
Encoding's GetString
, but you won't be able to get the original bytes back if those bytes have non-ASCII characters.BitConverter.ToString
The output is a "-" delimited string, but there's no .NET built-in method to convert the string back to byte array.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.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相互转化问题的更多相关文章
- C#中byte[]与string的转换
1. System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding(); byte[] i ...
- java中byte转string的方法有哪些?
1.第一种 byte b = 1; String valueOf = String.valueOf(b) 2.第二种 byte b = 1; String st = Byte.toString(b); ...
- C#图像处理:Stream 与 byte[] 相互转换,byte[]与string,Stream 与 File 相互转换等
C# Stream 和 byte[] 之间的转换 一. 二进制转换成图片 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Ima ...
- 【转】java中byte, int的转换, byte String转换
原文网址:http://freewind886.blog.163.com/blog/static/661924642011810236100/ 最近在做些与编解码相关的事情,又遇到了byte和int的 ...
- dotnet中Stream、string及byte[]的相关操作
string与byte[](UTF-8) //string to byte[] string str = "abc中文"; //0x61 0x62 0x63 0xE4 0xB8 0 ...
- Python3中内置类型bytes和str用法及byte和string之间各种编码转换,python--列表,元组,字符串互相转换
Python3中内置类型bytes和str用法及byte和string之间各种编码转换 python--列表,元组,字符串互相转换 列表,元组和字符串python中有三个内建函数:,他们之间的互相转换 ...
- C#中的Byte,String,Int,Hex之间的转换函数。
/// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary> ...
- C#中char[]与string之间的转换;byte[]与string之间的转化
目录 1.char[]与string之间的转换 2.byte[]与string之间的转化 1.char[]与string之间的转换 //string 转换成 Char[] string str=&qu ...
- Android Drawable 和String 相互转化
在我们经常应用开发中,经常用到将drawable和string相互转化.注意这情况最好用于小图片入icon等. public synchronized Drawable byteToDrawable( ...
随机推荐
- BZOJ1041:[HAOI2008]圆上的整点(数论)
Description 求一个给定的圆(x^2+y^2=r^2),在圆周上有多少个点的坐标是整数. Input 只有一个正整数n,n<=2000 000 000 Output 整点个数 Samp ...
- Centos 6.5 pptpd服务端搭建过程
首先检测有没有启用ppp和tun cat /dev/ppp cat /dev/net/tun 如果显示是这样的 cat: /dev/ppp: No such device or address cat ...
- Linux系统学习之软件安装
一.源码包编译安装 由于计算机无法直接执行用高级语言编写的源程序,因此想要运行程序,就需要一种机制来让计算机识别,这样程序才可能运行起来.一般来说,计算机中存在解释型和编译型两种语言. 所谓解释型语言 ...
- 关于nodejs
#!/bin/bashcd /home/software/wget https://nodejs.org/dist/v9.8.0/node-v9.8.0-linux-x64.tar.xztar -xv ...
- stm32cubemx学习要点记录
如果有些外设的HAL库函数找不到的话,你可以到IAR工程的文件夹显示栏中找如下图所示:
- Javascript 对象复制
如果对象只是一个数据集,可采用json化再反json化的方式克隆一个对象,这个过程会丢失对象的方法.效率比较低. 可以采用如下递归的方式复制一个对象. function clone(target) { ...
- mqtt 客户端 基于Python
这几天一直在搞安全通信,微信小程序,反向代理等等,为了能让自己对整个系统做到把控,主要是需要了解每一个细节的地方,所以今天花了3个小时的时间学习了Python,因为我要用它来做Http和WebSock ...
- sublime text3作为php开发IDE
phpstorm开发有时候太占内存,会发生卡顿.虽然还是更喜欢用这个IDE哈哈. 一个也很强大的编辑器sublime text3,作为偶尔的替代也很给力.这个内存占用会小不少. 官网下载sublime ...
- IIS导入.pfx证书时报错:"A specified logon session does not exist. It may already have been terminated."
在IIS中可以直接导入.pfx文件来给站点绑定https协议: 如果在导入.pfx文件时,不选择"Allow this certificate to be exported"的话 ...
- BusyBox下tftp命令的使用
一.简介 BusyBox下的tftp是一款应用于嵌入式开发系统上的一款小巧tftp工具,为开发者提供一个tftp服务的使用平台. 通常是,PC开发主机作为服务器(Server),开发系统(板)作为客户 ...