SHA-256简介及各种语言使用SHA-256计算

SHA-256简介及各种语言使用SHA-256计算

SHA-256简介

SHA-2,名称来自于安全散列算法2(英语:Secure Hash Algorithm 2)的缩写,一种密码散列函数算法标准,由美国国家安全局研发,由美国国家标准与技术研究院(NIST)在2001年发布。属于SHA算法之一,是SHA-1的后继者。其下又可再分为六个不同的算法标准,包括了:SHA-224、SHA-256、SHA-384、SHA-512、SHA-512/224、SHA-512/256。

哈希函数,又称散列算法,是一种从任何一种数据中创建小的数字“指纹”的方法。散列函数把消息或数据压缩成摘要,使得数据量变小,将数据的格式固定下来。该函数将数据打乱混合,重新创建一个叫做散列值(或哈希值)的指纹。散列值通常用一个短的随机字母和数字组成的字符串来代表。

对于任意长度的消息,SHA256都会产生一个256bit长的哈希值,称作消息摘要。

这个摘要相当于是个长度为32个字节的数组,通常用一个长度为64的十六进制字符串来表示

如对字符串123456计算sha-256结果为:8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

各种语言使用SHA-256计算

Javascript使用SHA-256计算

const text ="123456";

async function digestMessage(message) {
  const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8); // hash the message
  const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  const hashHex = hashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join(""); // convert bytes to hex string
  return hashHex;
}

digestMessage(text).then((digestHex) => console.log(digestHex));

Python使用SHA-256计算

from hashlib import sha256

data = '123456'
print(sha256(data.encode('utf-8')).hexdigest())

Java使用SHA-256计算

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

String text = "123456";

MessageDigest messageDigest = null;

try {
		messageDigest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
    	e.printStackTrace();
}
byte[] hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
System.out.println(String.format("%064x", new BigInteger(1, hash)));

Golang使用SHA-256计算

package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func main() {

	s := "123456"
	h := sha256.New()
	h.Write([]byte(s))
	sha1_hash := hex.EncodeToString(h.Sum(nil))

	fmt.Println(s, sha1_hash)
}

Rust使用SHA-256计算

use sha256::{digest, try_digest};

//sha256 digest String
let input = String::from("123456");
let val = digest(input);

println!("{}", val);

Linux Shell使用SHA-256计算

echo -n 123456 |sha256sum

Windows cmd 使用SHA-256计算

Windows certutil只支持文件,创建data.txt内容为123456

certutil -hashfile data.txt SHA256

SHA-256在线工具

SHA-256文本计算

SHA-256文件计算

参考来源:SHA-256简介及各种语言使用SHA-256计算

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值