計算MD5()加密值 (C#, PHP, JS, Go, Java, Java, Python)

各種程式語言多少都會用到MD5()加密
紀錄一下比較常用的語言MD5()加密

C#

/// <summary>
/// 字串轉MD5
/// </summary>
/// <param name="encodeStr">欲加密字串</param>
/// <returns></returns>
public string ToMD5(string encodeStr)
{
    using (var cryptoMD5 = System.Security.Cryptography.MD5.Create())
    {
        var bytes = Encoding.UTF8.GetBytes(encodeStr);
        var hash = cryptoMD5.ComputeHash(bytes);
        var md5 = BitConverter.ToString(hash)
            .Replace("-", String.Empty);

        return md5;
    }
}

 

PHP

function ToMD5($str){
    return md5($str);
}

 

JavaScript

// npm install md5

var md5 = require('md5');
 
function ToMD5 (str) {
    return md5(str);
}

 

Golang

func ToMD5(str string) string  {
    h := md5.New()
    h.Write([]byte(str))
    return hex.EncodeToString(h.Sum(nil))
}

 

Java

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public static String ToMD5(String str) {
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(str.getBytes());
        byte messageDigest[] = digest.digest();

        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest) {
            hexString.append(Integer.toHexString(0xFF & b));
        }
        return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

 

Python

import hashlib

def ToMD5(str):
    m = hashlib.md5()
    m.update(str)
    h = m.hexdigest()
    return h

 

留言

Top