# 各种语言MD5计算方法
# Python
import hashlib
# 字符串
s = "hello".encode("utf-8")
print(hashlib.md5(s).hexdigest())
# 文件
def md5_file(path, bufsize=8192):
h = hashlib.md5()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(bufsize), b""):
h.update(chunk)
return h.hexdigest()
# print(md5_file("path/to/file"))
# Node.js (运行时)
const crypto = require('crypto');
// 字符串
const s = 'hello';
console.log(crypto.createHash('md5').update(s, 'utf8').digest('hex'));
// 文件
const fs = require('fs');
function md5File(path) {
const hash = crypto.createHash('md5');
return new Promise((resolve, reject) => {
fs.createReadStream(path)
.on('data', d => hash.update(d))
.on('end', () => resolve(hash.digest('hex')))
.on('error', reject);
});
}
// md5File('path/to/file').then(console.log);
浏览器端:Web Crypto 不支持 MD5。需用第三方库(如 SparkMD5)。
<script src="https://cdn.jsdelivr.net/npm/spark-md5@3/dist/spark-md5.min.js"></script>
<script>
console.log(SparkMD5.hash('hello')); // 字符串
</script>
# Java (JDK)
import java.security.*;
import java.nio.file.*;
import java.io.*;
public class MD5Demo {
static String toHex(byte[] b){ StringBuilder sb=new StringBuilder(); for(byte x:b) sb.append(String.format("%02x", x)); return sb.toString(); }
public static void main(String[] args) throws Exception {
// 字符串
MessageDigest md = MessageDigest.getInstance("MD5");
md.update("hello".getBytes("UTF-8"));
System.out.println(toHex(md.digest()));
// 文件
System.out.println(md5File(Paths.get("path/to/file")));
}
static String md5File(Path p) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(p)) {
byte[] buf = new byte[8192];
int n;
while ((n = is.read(buf)) > 0) md.update(buf, 0, n);
}
return toHex(md.digest());
}
}
# C# (.NET)
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class Program {
static void Main() {
// 字符串
using var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.UTF8.GetBytes("hello"));
Console.WriteLine(Convert.ToHexString(hash).ToLower());
// 文件
// Console.WriteLine(MD5File("path/to/file"));
}
static string MD5File(string path){
using var md5 = MD5.Create();
using var fs = File.OpenRead(path);
return Convert.ToHexString(md5.ComputeHash(fs)).ToLower();
}
}
# Go
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"os"
)
func main() {
// 字符串
sum := md5.Sum([]byte("hello"))
fmt.Println(hex.EncodeToString(sum[:]))
// 文件
// fmt.Println(md5File("path/to/file"))
}
func md5File(path string) (string, error) {
f, err := os.Open(path)
if err != nil { return "", err }
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil { return "", err }
return hex.EncodeToString(h.Sum(nil)), nil
}
# PHP
<?php
// 字符串
echo md5("hello"), PHP_EOL;
// 文件
// echo md5_file("path/to/file"), PHP_EOL;
# Ruby
require 'digest'
# 字符串
puts Digest::MD5.hexdigest("hello")
# 文件
# puts Digest::MD5.file("path/to/file").hexdigest
# Kotlin (JVM)
import java.security.MessageDigest
import java.io.FileInputStream
fun ByteArray.toHex() = joinToString("") { "%02x".format(it) }
fun main() {
val md = MessageDigest.getInstance("MD5")
println(md.digest("hello".toByteArray()).toHex())
// 文件
// println(md5File("path/to/file"))
}
fun md5File(path: String): String {
val md = MessageDigest.getInstance("MD5")
FileInputStream(path).use { fis ->
val buf = ByteArray(8192)
while (true) {
val n = fis.read(buf)
if (n < 0) break
md.update(buf, 0, n)
}
}
return md.digest().toHex()
}
# Swift (Apple 平台,CommonCrypto)
注意:Swift 的 CryptoKit 不支持 MD5;用 CommonCrypto。
import Foundation
import CommonCrypto
func md5(_ s: String) -> String {
let data = Data(s.utf8)
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
data.withUnsafeBytes { CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) }
return digest.map { String(format: "%02x", $0) }.joined()
}
print(md5("hello"))
// 文件
func md5File(url: URL) throws -> String {
let bufSize = 8192
var ctx = CC_MD5_CTX()
CC_MD5_Init(&ctx)
let fh = try FileHandle(forReadingFrom: url)
while autoreleasepool(invoking: {
let data = fh.readData(ofLength: bufSize)
if data.count > 0 {
data.withUnsafeBytes { _ = CC_MD5_Update(&ctx, $0.baseAddress, CC_LONG(data.count)) }
return true
} else { return false }
}) {}
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5_Final(&digest, &ctx)
return digest.map { String(format: "%02x", $0) }.joined()
}
# Rust
// Cargo.toml 添加: md5 = "0.7"
fn main() {
let digest = md5::compute("hello");
println!("{:x}", digest);
}
// 文件
use std::fs::File;
use std::io::{self, Read};
fn md5_file(path: &str) -> io::Result<String> {
let mut file = File::open(path)?;
let mut ctx = md5::Context::new();
let mut buf = [0u8; 8192];
loop {
let n = file.read(&mut buf)?;
if n == 0 { break; }
ctx.consume(&buf[..n]);
}
Ok(format!("{:x}", ctx.compute()))
}
# C(基于 OpenSSL)
#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>
void to_hex(const unsigned char* d, unsigned int len){
for(unsigned int i=0;i<len;i++) printf("%02x", d[i]);
printf("\n");
}
int main(){
const char* s = "hello";
unsigned char out[MD5_DIGEST_LENGTH];
MD5((const unsigned char*)s, strlen(s), out);
to_hex(out, MD5_DIGEST_LENGTH);
return 0;
}
# C++(基于 OpenSSL)
#include <iostream>
#include <iomanip>
#include <openssl/md5.h>
#include <string>
int main() {
std::string s = "hello";
unsigned char out[MD5_DIGEST_LENGTH];
MD5(reinterpret_cast<const unsigned char*>(s.data()), s.size(), out);
std::ios::fmtflags f(std::cout.flags());
for (int i=0;i<MD5_DIGEST_LENGTH;i++)
std::cout << std::hex << std::setfill('0') << std::setw(2) << (int)out[i];
std::cout << std::endl;
std::cout.flags(f);
return 0;
}
# Bash / Shell
# GNU/Linux
echo -n "hello" | md5sum | awk '{print $1}'
# macOS
echo -n "hello" | md5
# OpenSSL 通用
echo -n "hello" | openssl md5 | awk '{print $2}'
# 文件
# md5sum path/to/file # Linux
# md5 path/to/file # macOS
# openssl md5 path/to/file # 通用
# 统一校验
所有示例对字符串 "hello"
的 MD5 都应输出:
5d41402abc4b2a76b9719d911017c592
← linux centos 7.9更新源 →