一.选择在自己的工程中增加Base64Helper.cs类,下面是类的内容。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Base64Helpertest.CentreWin
{
class Base64Helper
{
///
/// Base64加密,采用utf8编码方式加密
///
/// 待加密的明文
/// 加密后的字符串
public string Base64Encode(string source)
{
return Base64Encode(Encoding.UTF8, source);
}
/// <summary>
/// Base64加密
/// </summary>
/// <param name="encodeType">加密采用的编码方式</param>
/// <param name="source">待加密的明文</param>
/// <returns></returns>
public static string Base64Encode(Encoding encodeType, string source)
{
string encode = string.Empty;
byte[] bytes = encodeType.GetBytes(source);
try
{
encode = Convert.ToBase64String(bytes);
}
catch
{
encode = source;
}
return encode;
}
/// <summary>
/// Base64解密,采用utf8编码方式解密
/// </summary>
/// <param name="result">待解密的密文</param>
/// <returns>解密后的字符串</returns>
public string Base64Decode(string result)
{
return Base64Decode(Encoding.UTF8, result);
}
/// <summary>
/// Base64解密
/// </summary>
/// <param name="encodeType">解密采用的编码方式,注意和加密时采用的方式一致</param>
/// <param name="result">待解密的密文</param>
/// <returns>解密后的字符串</returns>
public static string Base64Decode(Encoding encodeType, string result)
{
string decode = string.Empty;
byte[] bytes = Convert.FromBase64String(result);
try
{
decode = encodeType.GetString(bytes);
}
catch
{
decode = result;
}
return decode;
}
}
}
二.应用的时候只需在定义一下。就可以用了。如下面。
string in_Base64;
string out_Base64;
Base64Helper Base64_pw = new Base64Helper();
in_Base64 = “123456”;
out_Base64 = Base64_pw.Base64Encode(richTextBox3.Text);
Console.WriteLine(out_Base64 );