测试代码
static void Main(string[] args)
{
//加密前
var str = "wyf1999";
var encryptUtility = new EncryptUtility();
Console.WriteLine("加密前"+str);
var afterstr = encryptUtility.EncodeBase64(str);
Console.WriteLine("加密后" + afterstr);
var oldstr= encryptUtility.DecodeBase64(afterstr);
Console.WriteLine("解密后" + oldstr);
Console.ReadKey();
}
封装类
/// <summary>
/// base64加解密
/// </summary>
public class EncryptUtility
{
#region Base64加解密
/// <summary>
/// Base64加密,采用utf8编码方式加密
/// </summary>
/// <param name="encode">编码方式</param>
/// <param name="source">待加密的明文</param>
/// <returns></returns>
public string EncodeBase64(Encoding encode, string source)
{
var bytes = encode.GetBytes(source);
var stringency = Convert.ToBase64String(bytes);
return stringency;
}
/// <summary>
/// Base64加密,采用utf8编码方式加密
/// </summary>
/// <param name="source">待加密的明文</param>
/// <returns>加密后的字符串</returns>
public string EncodeBase64(string source)
{
return EncodeBase64(Encoding.UTF8, source);
}
/// <summary>
/// Base64解密
/// </summary>
/// <param name="encode">编码方式</param>
/// <param name="result">待解密的密文</param>
/// <returns>解密后的字符串</returns>
public string DecodeBase64(Encoding encode, string result)
{
var bytes = Convert.FromBase64String(result);
var decode = encode.GetString(bytes);
return decode;
}
/// <summary>
/// Base64解密,采用utf8编码方式解密
/// </summary>
/// <param name="result">待解密的密文</param>
/// <returns>解密后的字符串</returns>
public string DecodeBase64(string result)
{
return DecodeBase64(Encoding.UTF8, result);
}
#endregion Base64加解密
}