.NET ez 2012-06-20
使用Base64可以做到基礎的加密,可以將文字轉換為一串亂碼,並且也可以將亂碼轉回文字。
但是因為沒有金鎖,所以大家都可以解密,只能用在一般用途。
using System; using System.Text; namespace Test { class Program { static void Main(string[] args) { //將文字轉換為Base64 byte[] bytes = Encoding.Default.GetBytes("中文字"); string Base64 = Convert.ToBase64String(bytes); Console.WriteLine(Base64); //將base64轉為byte bytes = Convert.FromBase64String(Base64); string str = Encoding.Default.GetString(bytes); Console.WriteLine(str); Console.ReadLine(); } } }
將他寫為function
/// <summary> /// 編碼 /// </summary> /// <param name="code_type">編碼方式</param> /// <param name="Str">字串</param> /// <returns>回傳加密結果</returns> public string Encrypt(string code_type, string Str) { string encode = string.Empty; byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(Str); try { encode = Convert.ToBase64String(bytes); } catch { encode = Str; } return encode; } /// <summary> /// 解密 /// </summary> /// <param name="code_type">編碼方式</param> /// <param name="Str">字串</param> /// <returns>回傳解密結果</returns> public string Decrypt(string code_type, string Str) { string decode = string.Empty; byte[] bytes = Convert.FromBase64String(Str); try { decode = Encoding.GetEncoding(code_type).GetString(bytes); } catch { decode = "N/A"; } return decode; }
標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-Base64-Encrypt-Decrypt
https://www.ez2o.com/Blog/Post/63
https://www.ez2o.com/Blog/Post/csharp-Base64-Encrypt-Decrypt
https://www.ez2o.com/Blog/Post/63