一、計算文本哈希值:ide
public static string ComputeHash(string password) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(password); SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); byte[] hash = sha.ComputeHash(buffer); StringBuilder passwordbullder = new StringBuilder(32); foreach (byte hashByte in hash) { passwordbullder.Append(hashByte.ToString("x2")); } return passwordbullder.ToString(); }
二、計算文件的哈希值、MD5:ui
FileStream fs = new FileStream(this.fileFullName, FileMode.Open, FileAccess.Read); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); Byte[] fileHashes_SHA1 = sha1.ComputeHash(fs); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); Byte[] fileHashes_MD5 = md5.ComputeHash(fs); //this.fileSize = fs.Length; //this.sendSize = 0; fs.Close(); fs.Dispose();
三、解密字符串this
/// <summary> /// 解密字符串。 /// </summary> /// <param name="sourceString">要解密的字符串。</param> /// <param name="encryptionKey">密鑰。</param> /// <returns>解密後的字符串。</returns> private String DecryptString(String sourceString, String encryptionKey) { try { Byte[] rgbKey = Encoding.UTF8.GetBytes(encryptionKey.Substring(0, 8)); Byte[] rgbIV = this.iv; //默認初始化密鑰向量{ 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; Byte[] inputByteArray = Convert.FromBase64String(sourceString); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.UTF8.GetString(ms.ToArray()); } catch { return String.Empty; } }
獲取MD5密文:blog
public static string GetMd5Hash(string input) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); }