转换的类
class Base64Converter
{
public static string ConverBase64(string sourceString, int encode = 3)
{
string res = string.Empty;
if (sourceString.Trim().Length == 0)
{
res = "源字符串不能为空";
}
try
{
string[] encodeList = new string[] { "ASCII", "Unicode", "UTF-8", "GBK" };
Encoding encoding = Encoding.GetEncoding(encodeList[encode]);
byte[] buffer = encoding.GetBytes(sourceString.Trim());
res = Convert.ToBase64String(buffer, Base64FormattingOptions.None);
}
catch (Exception ex)
{
res = $"转换为Base64时出错:【{ex.Message}】";
}
return res;
}
public static string FromBase64string(string sourceString, int encode = 3)
{
string res = string.Empty;
if (sourceString.Trim().Length == 0)
{
res = "Base64字符串不能为空";
}
try
{
string[] encodeList = new string[] { "ASCII", "Unicode", "UTF-8", "GBK" };
Encoding encoding = Encoding.GetEncoding(encodeList[encode]);
byte[] buffer = Convert.FromBase64String(sourceString);
res = encoding.GetString(buffer);
}
catch (Exception ex)
{
res = $"还原字符串时出错:【{ex.Message}】";
}
return res;
}
}
转换测试
using System.Collections.Generic;
using Newtonsoft.Json;
private void Base64Do()
{
/*模拟云渲染传过来的参数*/
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("userName", "user011");
data.Add("accessToken", "asdasdlklklliuoijklj123zxc");
/*模拟云渲染传过来的参数*/
string dataJson = JsonConvert.SerializeObject(data);
string base64Str = Base64Converter.ConverBase64(dataJson);
Console.WriteLine("转成的base64:" + base64Str);
/*模拟base64解密*/
string res = Base64Converter.FromBase64string(base64Str);
/*模拟base64解密*/
Dictionary<string, string> resDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
foreach (var item in resDic)
{
Console.WriteLine("转回字典:" + item.Key + " " + item.Value);
}
}