內建MD5、DSA、RSA加密,需要引入 using System.Security.Cryptography;
// 32位MD5函數 public static string Md532(string str) { string cl = str; string pwd = ""; MD5 md5 = MD5.Create(); byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); for (int i = 0; i < s.Length; i++) { pwd = pwd + s[i].ToString("x"); } return pwd; } // 16位MD5函數 public static string Md516(string ConvertString) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); t2 = t2.Replace("-", ""); t2 = t2.ToLower(); return t2; } public static string DSAEncrypt(string str) { byte[] bytes = Encoding.ASCII.GetBytes(str); //選擇簽名方式,有RSA和DSA DSACryptoServiceProvider dsac = new DSACryptoServiceProvider(); byte[] sign = dsac.SignData(bytes); string strResult = Convert.ToString(sign); return strResult; }
DES加密
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Security.Cryptography;using System.IO;namespace DESHelper{ class DESJob { public static string encryptKey = "Oyea"; //定義密鑰 #region 加密字串 /// <summary> /// 加密字串 /// </summary> /// <param name="str">要加密的字串</param> /// <returns>加密後的字串</returns> public static string Encrypt(string str) { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //執行個體化加/解密類對象 byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定義位元組數組,用來儲存體金鑰 byte[] data = Encoding.Unicode.GetBytes(str);//定義位元組數組,用來儲存要加密的字串 MemoryStream MStream = new MemoryStream(); //執行個體化記憶體流對象 //使用記憶體流執行個體化加密流對象 CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write); CStream.Write(data, 0, data.Length); //向加密流中寫入資料 CStream.FlushFinalBlock(); //釋放加密流 return Convert.ToBase64String(MStream.ToArray());//返回加密後的字串 } #endregion #region 解密字串 /// <summary> /// 解密字串 /// </summary> /// <param name="str">要解密的字串</param> /// <returns>解密後的字串</returns> public static string Decrypt(string str) { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //執行個體化加/解密類對象 byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定義位元組數組,用來儲存體金鑰 byte[] data = Convert.FromBase64String(str);//定義位元組數組,用來儲存要解密的字串 MemoryStream MStream = new MemoryStream(); //執行個體化記憶體流對象 //使用記憶體流執行個體化解密流對象 CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write); CStream.Write(data, 0, data.Length); //向解密流中寫入資料 CStream.FlushFinalBlock(); //釋放解密流 return Encoding.Unicode.GetString(MStream.ToArray()); //返回解密後的字串 } #endregion }}