- 两者使用相同SHA256加密,从而得到的hash值相同,
- 从而可以加密密码储存数据库,只要用户输入的密码加密后的hash值对的上就行
JAVA
package com.example.utils;
import java.security.MessageDigest;
/**
* artist: hemaolin
* date: 2024/3/17 20:09
*/
public class SHA256Utils {
public static String encrypt(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(input.getBytes());
// 将加密后的字节数组转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : encodedhash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (
Exception e) {
e.printStackTrace();
return null;
}
}
}
使用方法
/**
* SHA256将用户输入的密码加密 从而和数据库存储的一样
*/
String encryptPwd = SHA256Utils.encrypt(account.getPassword());
System.out.println("Encrypted password: " + encryptPwd);
JS
npm install crypto-js
// 在你的main.js文件中引入crypto-js库
import SHA256 from 'crypto-js/sha256';
//使用方法
var hash = SHA256('要哈希的文本');
console.log('SHA-256哈希:', hash.toString());