w

使用示例

基础示例

文本 MD5 计算

JavaScript 实现

// 使用 Web Crypto API
async function calculateMD5(text) {
  const encoder = new TextEncoder();
  const data = encoder.encode(text);

  // 注意:Web Crypto API 不直接支持 MD5
  // 这里使用第三方库或服务器端计算
  const response = await fetch('/api/md5', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ text }),
  });

  const result = await response.json();
  return result.hash;
}

// 使用示例
const text = 'Hello, World!';
calculateMD5(text).then((hash) => {
  console.log(`MD5: ${hash}`);
  // 输出: MD5: 65a8e27d8879283831b664bd8b7f0ad4
});

Node.js 实现

const crypto = require('crypto');

function calculateMD5(text, encoding = 'utf8') {
  return crypto.createHash('md5').update(text, encoding).digest('hex');
}

// 使用示例
const text = 'Hello, World!';
const hash = calculateMD5(text);
console.log(`MD5: ${hash}`);
// 输出: MD5: 65a8e27d8879283831b664bd8b7f0ad4

// 不同编码格式
const utf8Hash = calculateMD5('你好', 'utf8');
const gbkHash = calculateMD5('你好', 'gbk');
console.log(`UTF-8: ${utf8Hash}`);
console.log(`GBK: ${gbkHash}`);

Python 实现

import hashlib

def calculate_md5(text, encoding='utf-8'):
    """计算文本的 MD5 散列值"""
    return hashlib.md5(text.encode(encoding)).hexdigest()

# 使用示例
text = "Hello, World!"
hash_value = calculate_md5(text)
print(f"MD5: {hash_value}")
# 输出: MD5: 65a8e27d8879283831b664bd8b7f0ad4

# 不同编码格式
utf8_hash = calculate_md5("你好", 'utf-8')
gbk_hash = calculate_md5("你好", 'gbk')
print(f"UTF-8: {utf8_hash}")
print(f"GBK: {gbk_hash}")

# 大写格式
hash_upper = hashlib.md5(text.encode('utf-8')).hexdigest().upper()
print(f"MD5 (大写): {hash_upper}")

文件 MD5 计算

JavaScript 实现

// 浏览器环境
async function calculateFileMD5(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = function (e) {
      const arrayBuffer = e.target.result;
      const uint8Array = new Uint8Array(arrayBuffer);

      // 使用 Web Crypto API 或其他库
      calculateMD5FromArray(uint8Array).then(resolve).catch(reject);
    };

    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
}

// 使用示例
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', async (event) => {
  const file = event.target.files[0];
  if (file) {
    const hash = await calculateFileMD5(file);
    console.log(`文件 MD5: ${hash}`);
  }
});

Node.js 实现

const crypto = require('crypto');
const fs = require('fs');

// 同步读取文件
function calculateFileMD5Sync(filePath) {
  const fileBuffer = fs.readFileSync(filePath);
  return crypto.createHash('md5').update(fileBuffer).digest('hex');
}

// 异步读取文件
function calculateFileMD5Async(filePath) {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash('md5');
    const stream = fs.createReadStream(filePath);

    stream.on('data', (data) => {
      hash.update(data);
    });

    stream.on('end', () => {
      resolve(hash.digest('hex'));
    });

    stream.on('error', reject);
  });
}

// 使用示例
const filePath = './example.txt';

// 同步方式
try {
  const hashSync = calculateFileMD5Sync(filePath);
  console.log(`文件 MD5 (同步): ${hashSync}`);
} catch (error) {
  console.error('同步计算失败:', error);
}

// 异步方式
calculateFileMD5Async(filePath)
  .then((hash) => {
    console.log(`文件 MD5 (异步): ${hash}`);
  })
  .catch((error) => {
    console.error('异步计算失败:', error);
  });

Python 实现

import hashlib

def calculate_file_md5(file_path, chunk_size=8192):
    """计算文件的 MD5 散列值"""
    hash_md5 = hashlib.md5()

    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hash_md5.update(chunk)

    return hash_md5.hexdigest()

# 使用示例
file_path = "example.txt"
hash_value = calculate_file_md5(file_path)
print(f"文件 MD5: {hash_value}")

# 大文件处理
def calculate_large_file_md5(file_path, chunk_size=1024*1024):
    """处理大文件的 MD5 计算"""
    hash_md5 = hashlib.md5()
    file_size = os.path.getsize(file_path)
    processed = 0

    with open(file_path, "rb") as f:
        while True:
            chunk = f.read(chunk_size)
            if not chunk:
                break
            hash_md5.update(chunk)
            processed += len(chunk)

            # 显示进度
            progress = (processed / file_size) * 100
            print(f"进度: {progress:.1f}%")

    return hash_md5.hexdigest()

高级示例

批量处理

JavaScript 批量处理

// 批量计算文本 MD5
async function batchCalculateMD5(texts) {
  const results = [];

  for (let i = 0; i < texts.length; i++) {
    const text = texts[i];
    const hash = await calculateMD5(text);

    results.push({
      index: i,
      text: text,
      hash: hash,
      length: text.length,
    });

    // 显示进度
    const progress = ((i + 1) / texts.length) * 100;
    console.log(`进度: ${progress.toFixed(1)}%`);
  }

  return results;
}

// 使用示例
const texts = ['Hello, World!', '你好,世界!', 'Bonjour le monde!', 'Hola mundo!'];

batchCalculateMD5(texts).then((results) => {
  console.log('批量计算结果:');
  results.forEach((result) => {
    console.log(`${result.index}: ${result.text} -> ${result.hash}`);
  });
});

Python 批量处理

import asyncio
import aiohttp
import hashlib

async def batch_calculate_md5(texts):
    """异步批量计算 MD5"""
    results = []

    async def calculate_single(text, index):
        hash_value = hashlib.md5(text.encode('utf-8')).hexdigest()
        return {
            'index': index,
            'text': text,
            'hash': hash_value,
            'length': len(text)
        }

    # 创建所有任务
    tasks = [calculate_single(text, i) for i, text in enumerate(texts)]

    # 并发执行
    results = await asyncio.gather(*tasks)

    return results

# 使用示例
async def main():
    texts = [
        "Hello, World!",
        "你好,世界!",
        "Bonjour le monde!",
        "Hola mundo!"
    ]

    results = await batch_calculate_md5(texts)

    print("批量计算结果:")
    for result in results:
        print(f"{result['index']}: {result['text']} -> {result['hash']}")

# 运行异步函数
asyncio.run(main())

散列值验证

JavaScript 验证

// 验证文本散列值
async function verifyTextHash(text, expectedHash) {
  const calculatedHash = await calculateMD5(text);
  const isValid = calculatedHash.toLowerCase() === expectedHash.toLowerCase();

  return {
    text: text,
    expectedHash: expectedHash,
    calculatedHash: calculatedHash,
    isValid: isValid,
  };
}

// 验证文件散列值
async function verifyFileHash(file, expectedHash) {
  const calculatedHash = await calculateFileMD5(file);
  const isValid = calculatedHash.toLowerCase() === expectedHash.toLowerCase();

  return {
    filename: file.name,
    size: file.size,
    expectedHash: expectedHash,
    calculatedHash: calculatedHash,
    isValid: isValid,
  };
}

// 使用示例
const text = 'Hello, World!';
const expectedHash = '65a8e27d8879283831b664bd8b7f0ad4';

verifyTextHash(text, expectedHash).then((result) => {
  if (result.isValid) {
    console.log('✅ 散列值验证成功');
  } else {
    console.log('❌ 散列值验证失败');
    console.log(`期望: ${result.expectedHash}`);
    console.log(`实际: ${result.calculatedHash}`);
  }
});

Python 验证

def verify_hash(text, expected_hash):
    """验证散列值"""
    calculated_hash = hashlib.md5(text.encode('utf-8')).hexdigest()
    is_valid = calculated_hash.lower() == expected_hash.lower()

    return {
        'text': text,
        'expected_hash': expected_hash,
        'calculated_hash': calculated_hash,
        'is_valid': is_valid
    }

def verify_file_hash(file_path, expected_hash):
    """验证文件散列值"""
    calculated_hash = calculate_file_md5(file_path)
    is_valid = calculated_hash.lower() == expected_hash.lower()

    return {
        'file_path': file_path,
        'expected_hash': expected_hash,
        'calculated_hash': calculated_hash,
        'is_valid': is_valid
    }

# 使用示例
text = "Hello, World!"
expected_hash = "65a8e27d8879283831b664bd8b7f0ad4"

result = verify_hash(text, expected_hash)
if result['is_valid']:
    print("✅ 散列值验证成功")
else:
    print("❌ 散列值验证失败")
    print(f"期望: {result['expected_hash']}")
    print(f"实际: {result['calculated_hash']}")

性能优化示例

JavaScript 性能优化

// 使用 Web Workers 进行后台计算
class MD5Worker {
  constructor() {
    this.worker = new Worker('/js/md5-worker.js');
    this.callbacks = new Map();
    this.callbackId = 0;

    this.worker.onmessage = (event) => {
      const { id, result, error } = event.data;
      const callback = this.callbacks.get(id);

      if (callback) {
        if (error) {
          callback.reject(error);
        } else {
          callback.resolve(result);
        }
        this.callbacks.delete(id);
      }
    };
  }

  calculateMD5(text) {
    return new Promise((resolve, reject) => {
      const id = ++this.callbackId;
      this.callbacks.set(id, { resolve, reject });

      this.worker.postMessage({
        id,
        type: 'calculate',
        text,
      });
    });
  }

  terminate() {
    this.worker.terminate();
  }
}

// 使用示例
const md5Worker = new MD5Worker();

md5Worker
  .calculateMD5('Hello, World!')
  .then((hash) => {
    console.log(`MD5: ${hash}`);
  })
  .catch((error) => {
    console.error('计算失败:', error);
  });

// 完成后清理
md5Worker.terminate();

Python 性能优化

import multiprocessing
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import hashlib

def calculate_md5_worker(text):
    """工作进程函数"""
    return hashlib.md5(text.encode('utf-8')).hexdigest()

def batch_calculate_md5_parallel(texts, max_workers=None):
    """并行批量计算 MD5"""
    if max_workers is None:
        max_workers = multiprocessing.cpu_count()

    with ProcessPoolExecutor(max_workers=max_workers) as executor:
        results = list(executor.map(calculate_md5_worker, texts))

    return results

def calculate_file_md5_parallel(file_paths, max_workers=None):
    """并行计算多个文件的 MD5"""
    if max_workers is None:
        max_workers = min(len(file_paths), multiprocessing.cpu_count())

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(calculate_file_md5, path): path
                  for path in file_paths}

        results = {}
        for future in futures:
            path = futures[future]
            try:
                hash_value = future.result()
                results[path] = hash_value
            except Exception as e:
                results[path] = f"错误: {e}"

    return results

# 使用示例
texts = [f"文本{i}" for i in range(1000)]
file_paths = ["file1.txt", "file2.txt", "file3.txt"]

# 并行计算文本
text_hashes = batch_calculate_md5_parallel(texts)
print(f"计算了 {len(text_hashes)} 个文本的 MD5")

# 并行计算文件
file_hashes = calculate_file_md5_parallel(file_paths)
for path, hash_value in file_hashes.items():
    print(f"{path}: {hash_value}")

实际应用示例

文件完整性检查

import os
import json
import hashlib

class FileIntegrityChecker:
    def __init__(self, checksum_file="checksums.json"):
        self.checksum_file = checksum_file
        self.checksums = self.load_checksums()

    def load_checksums(self):
        """加载校验和文件"""
        if os.path.exists(self.checksum_file):
            with open(self.checksum_file, 'r') as f:
                return json.load(f)
        return {}

    def save_checksums(self):
        """保存校验和文件"""
        with open(self.checksum_file, 'w') as f:
            json.dump(self.checksums, f, indent=2)

    def add_file(self, file_path):
        """添加文件到校验列表"""
        if os.path.exists(file_path):
            hash_value = calculate_file_md5(file_path)
            self.checksums[file_path] = hash_value
            self.save_checksums()
            return hash_value
        else:
            raise FileNotFoundError(f"文件不存在: {file_path}")

    def verify_file(self, file_path):
        """验证文件完整性"""
        if file_path not in self.checksums:
            return False, "文件不在校验列表中"

        expected_hash = self.checksums[file_path]
        actual_hash = calculate_file_md5(file_path)

        is_valid = expected_hash == actual_hash
        return is_valid, {
            'expected': expected_hash,
            'actual': actual_hash
        }

    def verify_all(self):
        """验证所有文件"""
        results = {}
        for file_path in self.checksums:
            is_valid, details = self.verify_file(file_path)
            results[file_path] = {
                'valid': is_valid,
                'details': details
            }
        return results

# 使用示例
checker = FileIntegrityChecker()

# 添加文件到校验列表
checker.add_file("important_document.pdf")
checker.add_file("configuration.json")

# 验证单个文件
is_valid, details = checker.verify_file("important_document.pdf")
if is_valid:
    print("✅ 文件完整性验证通过")
else:
    print("❌ 文件完整性验证失败")
    print(f"期望: {details['expected']}")
    print(f"实际: {details['actual']}")

# 验证所有文件
all_results = checker.verify_all()
for file_path, result in all_results.items():
    status = "✅" if result['valid'] else "❌"
    print(f"{status} {file_path}")

密码散列示例

import hashlib
import os
import secrets

class PasswordHasher:
    def __init__(self, salt_length=16):
        self.salt_length = salt_length

    def generate_salt(self):
        """生成随机盐值"""
        return secrets.token_hex(self.salt_length)

    def hash_password(self, password, salt=None):
        """散列密码"""
        if salt is None:
            salt = self.generate_salt()

        # 注意:实际应用中应使用 bcrypt 或 Argon2
        # 这里仅作演示
        salted_password = password + salt
        hash_value = hashlib.md5(salted_password.encode('utf-8')).hexdigest()

        return {
            'hash': hash_value,
            'salt': salt
        }

    def verify_password(self, password, stored_hash, salt):
        """验证密码"""
        result = self.hash_password(password, salt)
        return result['hash'] == stored_hash

# 使用示例
hasher = PasswordHasher()

# 注册用户
password = "mySecurePassword123"
hash_result = hasher.hash_password(password)

print(f"密码散列: {hash_result['hash']}")
print(f"盐值: {hash_result['salt']}")

# 验证密码
is_valid = hasher.verify_password(password, hash_result['hash'], hash_result['salt'])
print(f"密码验证: {'✅ 成功' if is_valid else '❌ 失败'}")

# 错误密码验证
wrong_password = "wrongPassword"
is_valid = hasher.verify_password(wrong_password, hash_result['hash'], hash_result['salt'])
print(f"错误密码验证: {'✅ 成功' if is_valid else '❌ 失败'}")

最后更新时间:2024年1月20日

Was this page helpful?