← 返回工具首页

什么是SHA-256?

SHA-256(Secure Hash Algorithm 256-bit)是SHA-2家族中最常用的成员,由美国国家安全局(NSA)设计。它把任意长度的数据"压缩"成一个固定64个十六进制字符的摘要。特点:

一、JavaScript中使用SHA-256

现代浏览器内置了Web Crypto API,无需任何库:

async function sha256(message) {
  const msgBuffer = new TextEncoder().encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  return hashHex;
}

sha256('hello world').then(console.log);
// 输出: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

二、Node.js中使用SHA-256

const crypto = require('crypto');

const hash = crypto.createHash('sha256')
  .update('hello world')
  .digest('hex');

console.log(hash);
// 输出: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

注意:Node.js 18+ 也支持 Web Crypto API:node:crypto.subtle

三、Python中使用SHA-256

import hashlib

result = hashlib.sha256('hello world'.encode('utf-8')).hexdigest()
print(result)
# 输出: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

四、SHA-256的常见使用场景

五、密码存储的正确方式(加盐)

光用SHA-256存密码还不够,需要加盐防止彩虹表攻击:

// 生成随机盐并存储
const salt = crypto.randomBytes(16).toString('hex'); // 32字符随机盐
const hash = crypto.createHash('sha256')
  .update(salt + password)  // 盐 + 密码一起哈希
  .digest('hex');
// 存储: { salt, hash }

生产环境推荐用专门的密码哈希库(如 bcrypt、Argon2),不要手写。

六、工具推荐

💡 遇到同类问题?用工具快速解决

试试这些配套工具,无需注册,打开即用

SHA加密

常见问题

Q: 如何使用 sha256加密怎么用 相关工具?
A: 这类工具一般有明确的输入框和输出框,按提示输入内容,点击对应按钮即可得到结果。建议先用简单示例测试功能是否正常,再处理实际数据。
Q: sha256加密怎么用 适合在什么场景使用?
A: 根据具体工具类型决定。格式转换工具适合处理第三方数据,编码工具适合加密传输,压缩工具适合文件上传前处理。多积累工具使用经验,遇到问题时能快速判断用哪个工具解决。
Q: 有没有更好的替代工具?
A: 不同工具有不同侧重,重点是理解原理。可以同时安装多个类似工具,实际使用中对比效果,选择最顺手的一个。随着使用经验增加,你也能判断工具的好坏。