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( ...
随机推荐
- 【Lucene4.8教程之中的一个】使用Lucene4.8进行索引及搜索的基本操作
版权声明:本文为博主原创文章.转载请注明来自http://blog.csdn.net/jediael_lu/ https://blog.csdn.net/jediael_lu/article/deta ...
- go标准库的学习-strings-字符串操作
参考https://studygolang.com/pkgdoc 导入方式: import "strings" strings包实现了用于操作字符的简单函数. 常用的几个函数: f ...
- 通过JSP网页连接MySQL数据库,从MySQL数据库中读出一张表并显示在JSP网页中
1.安装所需软件 ①安装java和tomcat,建立JSP网页最基础的软件②安装MySQL数据库(下载地址:https://www.mysql.com/)③安装Navicat Premium来查看数据 ...
- Visual studio 附加进程调试
建一个WebApplication项目,并新增Default.aspx页面 新增一个IIS网站 打开页面,任务管理器启动了进程:w3wp.exe 附加进程,方式:VS-调试-附加进程 浏览器打开页面D ...
- 使用proxy来简单的实现一个观察者
var obv = (function() { var cache = new Map(); var observe = function (proxy, fn) { if (!cache.has(p ...
- timeout可以实现当一个命令在规定时间内不返回就强制返回的功能 + 杀毒安装ClamAV nmap 速度 比Telnet 快
[root@xiaowei ~]# cat telnetport.sh #!/bin/bash Port=25223 timeout 2 ssh root@127.0.0.1 "telnet ...
- Skyline 二次实现单体化模型选择查询示例代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or ...
- img图片加载出错处理(转载)
为了美观当网页图片不存在时不显示叉叉图片当在页面显示的时候,万一图片被移动了位置或者丢失的话,将会在页面显示一个带X的图片,很是影响用户的体验.即使使用alt属性给出了”图片XX”的提示信息,也起不了 ...
- HTML5 读取上传文件(转载)
另参考 http://www.jianshu.com/p/46e6e03a0d53 1 filelist对象与file对象: <input type="file" id=&q ...
- 如何下载google play商店里面的app?
如何不FQ的下载这国际版的app呢? 方法如下: https://androidappsapk.co/category/apps/ 你可以直接登入这个网站,下载你所需要的国际版的软件. 就像是踏入一个 ...