哈希算法又稱散列算法,它可以從任何數據中快速的創建一個憑證,而這個憑證很難被推倒出來,因為一丁點的變化會導致憑證的差別恨到,也就是說哈希算法具有不可逆性,因此它在密碼數據校驗方面用的很廣,比如我們常用的MD5、SHA1、SHA256、SHA384、SHA512等等
本文主要從應用的角度使用各語言去應用各種哈希加密算法:
Java
Java實現注入MD5等哈希算法的加密方式可以通過java.security.MessageDigest類來實現:
import java.nio.charset.Charset; import java.security.MessageDigest; public class HashMain { public static void main(String[] args) { String text = "上山打老虎"; String[] encryptTypes = new String[] { "md5", "sha-1", "sha-256", "sha-384", "sha-512" }; for (String encryptType : encryptTypes) { try { String encryptText = encrypt(text, encryptType); System.out.printf("【%s】經過【%s】加密后:%s\n", text, encryptType, encryptText); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static String encrypt(String value, String algorithmName) throws Exception { if (value == null || value.length() == 0) return ""; MessageDigest messageDigest = MessageDigest.getInstance(algorithmName); byte[] buffer = value.getBytes(Charset.forName("utf-8")); buffer = messageDigest.digest(buffer); // 使用hex格式數據輸出 StringBuffer result = new StringBuffer(); for (int i = 0; i < buffer.length; i++) { result.append(String.format("%02x", buffer[i])); } return result.toString(); } }
執行結果:

C#
C#實現各種哈希加密算法通過System.Security.Cryptography.HashAlgorithm來實現:
using System; using System.Security.Cryptography; using System.Text; namespace ConsoleApp { class Program { static void Main(string[] args) { string text = "上山打老虎"; string[] encryptTypes = new[] { "md5", "sha1", "sha256", "sha384", "sha512" }; foreach (string encryptType in encryptTypes) { string encryptText = Encrypt(text, encryptType); Console.WriteLine($"【{text}】經過【{encryptType}】加密后:{encryptText}"); } } /// <summary> /// 加密 /// </summary> /// <param name="value">加密字符串</param> /// <param name="encryptType">加密方式</param> /// <returns></returns> public static string Encrypt(string value, string encryptType) { if (string.IsNullOrEmpty(value)) return value; using (var hashAlgorithm = HashAlgorithm.Create(encryptType)) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(value); buffer = hashAlgorithm.ComputeHash(buffer); hashAlgorithm.Clear(); //使用hex格式數據輸出 StringBuilder result = new StringBuilder(); foreach (byte b in buffer) { result.AppendFormat("{0:x2}", b); } return result.ToString(); //或者使用下面的輸出 //return BitConverter.ToString(buffer).Replace("-", "").ToLower(); } } } }
執行結果:

Golang
Golang實現各種哈希加密算法的結構體在crypto包中,但是需要導入對應的包,如:
package main import ( "crypto" //導入 _ "crypto/md5" _ "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" "fmt" "io" ) func main() { text := "上山打老虎" encryptTypes := []crypto.Hash{crypto.MD5, crypto.SHA1, crypto.SHA256, crypto.SHA384, crypto.SHA512} for _, encryptType := range encryptTypes { encryptText, err := Encrypt(text, encryptType) if err != nil { fmt.Printf("【%s】加密錯誤:%s\n", encryptType, err.Error()) } else { fmt.Printf("【%s】經過【%s】加密后:%s\n", text, encryptType, encryptText) } } } func Encrypt(value string, hash crypto.Hash) (string, error) { if value == "" { return value, nil } var _hash = hash.New() if _, err := io.WriteString(_hash, value); err != nil { return "", err } result := fmt.Sprintf("%x", _hash.Sum(nil)) return result, nil }
執行結果:

Python
Python實現各種哈希加密算法的就很簡單了,而且有多種方式,比如:
方式一:使用hashlib
import hashlib text = "上山打老虎" buffer = text.encode(encoding='UTF-8') encryptTypes = ["md5", "sha1", "sha256", "sha384", "sha512"] for encryptType in encryptTypes: encryptText = hashlib.new(encryptType, buffer).hexdigest() print("【", text, "】經過", encryptType, "加密后:", encryptText)
執行結果:

方式二:使用Crypto.Hash,注意,需要安裝pycrypto,可以使用pip安裝:pip install pycryptodome(如果安裝不了,先卸載舊版本再安裝:pip uninstall pycrypto)
# 需要安裝pycrypto,可以使用pip安裝:pip install pycryptodome
from Crypto.Hash import MD5, SHA1, SHA256, SHA384, SHA512 text = "上山打老虎" buffer = text.encode(encoding='UTF-8') encryptTypes = [MD5, SHA1, SHA256, SHA384, SHA512] for encryptType in encryptTypes: hash = encryptType.new(buffer) encryptText = hash.hexdigest() print("【", text, "】經過", encryptType.__name__, "加密后:", encryptText)
執行結果:

