標籤:io cti ar res c text c# 字串
using System;
using System.Collections.Generic;
using System.Text;
namespace StringEncry
{
class EncodeAndDecode
{
/// <summary>
/// Base64加密
/// </summary>
/// <param name="codeName">加密採用的編碼方式</param>
/// <param name="source">待加密的明文</param>
/// <returns></returns>
public static string EncodeBase64(Encoding encode, string source)
{
string enstring = "";
byte[] bytes = encode.GetBytes(source);
try
{
enstring = Convert.ToBase64String(bytes);
}
catch
{
enstring = source;
}
return enstring;
}
/// <summary>
/// Base64加密,採用utf8編碼方式加密
/// </summary>
/// <param name="source">待加密的明文</param>
/// <returns>加密後的字串</returns>
public static string EncodeBase64(string source)
{
return EncodeBase64(Encoding.UTF8, source);
}
/// <summary>
/// Base64解密
/// </summary>
/// <param name="codeName">解密採用的編碼方式,注意和加密時採用的方式一致</param>
/// <param name="result">待解密的密文</param>
/// <returns>解密後的字串</returns>
public static string DecodeBase64(Encoding encode, string result)
{
string decode = "";
byte[] bytes = Convert.FromBase64String(result);
try
{
decode = encode.GetString(bytes);
}
catch
{
decode = result;
}
return decode;
}
/// <summary>
/// Base64解密,採用utf8編碼方式解密
/// </summary>
/// <param name="result">待解密的密文</param>
/// <returns>解密後的字串</returns>
public static string DecodeBase64(string result)
{
return DecodeBase64(Encoding.UTF8, result);
}
}
}