MD5,SHA1及SHA256等哈希加密方法实现:Java,C#,Golang,Python

  哈希算法又称散列算法,它可以从任何数据中快速的创建一个凭证,而这个凭证很难被推倒出来,因为一丁点的变化会导致凭证的差别恨到,也就是说哈希算法具有不可逆性,因此它在密码数据校验方面用的很广,比如我们常用的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
", 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
", encryptType, err.Error())
        } else {
            fmt.Printf("【%s】经过【%s】加密后:%s
", 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)

  执行结果:

  

一个专注于.NetCore的技术小白
原文地址:https://www.cnblogs.com/shanfeng1000/p/14804496.html