说明:
1:直接贴码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MD5_Base64 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } //加密MD5 private void btnMD5_Click(object sender, EventArgs e) { string str = txtString.Text; lblMD5Result.Text = UserMd5(str); } //加密Base64 private void btnBase64_Click(object sender, EventArgs e) { lblBase64Result.Text = Base64(lblMD5Result.Text, true); } //解密Base64 private void btnDecrypt_Click(object sender, EventArgs e) { lblDecryptResult.Text = Base64(txtEncode.Text,false); } #region 01MD5加密 public static string UserMd5(string str) { string cl = str; string pwd = ""; MD5 md5 = MD5.Create();//实例化一个md5对像 // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得 for (int i = 0; i < s.Length; i++) { // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 pwd = pwd + s[i].ToString("x2"); } return pwd; } #endregion #region 02Base64加密 static public string Base64(string s, bool c) { if (c) { //加密 return System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(s)); } else { try { //解密 return System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(s)); } catch (Exception exp) { return exp.Message; } } } #endregion #region 03Base64解密 /// <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); } #endregion } }
运行效果:
时间: 2024-11-05 13:30:39