SHA256加密算法
非对称算法SHA256,使用场景如密码加密等,现记录如下
package com.example.utils; import lombok.extern.slf4j.Slf4j; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @Slf4j public class SHA256Utils { /** * sha256加密 * * @param str 要加密的字符串 * @return 加密后的字符串 */ public static String getSha256Str(String str) { MessageDigest messageDigest; String encodeStr = ""; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(str.getBytes(StandardCharsets.UTF_8)); encodeStr = byte2Hex(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encodeStr; } /** * sha256加密 * * @param str 要加密的字符串 * @return 加密后的byte数组 */ public static byte[] getSha256(String str) { MessageDigest messageDigest; byte[] encodeStr = null; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(str.getBytes(StandardCharsets.UTF_8)); encodeStr = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encodeStr; } /** * sha256加密 将byte转为16进制 * * @param bytes 字节码 * @return 加密后的字符串 */ private static String byte2Hex(byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(); String temp; for (byte aByte : bytes) { temp = Integer.toHexString(aByte & 0xFF); if (temp.length() == 1) { //1得到一位的进行补0操作 stringBuilder.append("0"); } stringBuilder.append(temp); } return stringBuilder.toString(); } public static void main(String[] args) { String encodeStr = getSha256Str("123456"); // 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92 System.out.println(encodeStr); } }