ASP.NET(C#)实现Base64的编码\解码

发布时间:2010年05月31日      浏览次数:356 次
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
namespace WBIS.Base.Fun
{
/// <summary>
/// MyBase64 的摘要描述
/// </summary>
public class MyBase64
{
public MyBase64()
{
//
// TODO: 在此加入建構函式的程式碼
//
}
/// <summary>
/// 編碼
/// </summary>
/// <param name="data">字符串</param>
/// <returns></returns>
public static string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception e)
{
return "Error in base64Encode" + e.Message;
}
}
/// <summary>
/// 編碼
/// </summary>
/// <param name="bytes">位</param>
/// <returns></returns>
public static string base64Encode(byte[] bytes)
{
try
{
byte[] encData_byte = bytes;
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception e)
{
return "Error in base64Encode" + e.Message;
}
}
/// <summary>
/// 解碼
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch (Exception e)
{
return "Error in base64Encode" + e.Message;
}
}
/// <summary>
/// 解碼
/// </summary>
/// <param name="data">位</param>
/// <returns></returns>
public static string base64Decode(byte[] data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
//byte[] todecode_byte = Convert.FromBase64String(data);
char[] cdata = new char[data.Length];
utf8Decode.GetChars(data, 0, data.Length, cdata, 0);
byte[] todecode_byte = Convert.FromBase64CharArray(cdata, 0, data.Length);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch (Exception e)
{
return "Error in base64Encode" + e.Message;
}
}
}
}
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!