Java SHA256 encryption tool class

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

public class test {
    public static void main(String[] args) {
        String sha256Str = getSha256Str("123");
        System.out.println(sha256Str);
    }

    /**
     * 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加密 将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();
    }
}

Java code implements sha256 encryption_cainiao fox's blog-CSDN blog_java sha256 encryption The sha256 algorithm is asymmetric encryption and is irreversible, but it can also be brute force cracked. Generally, the password encryption of the user table of the system is encrypted, and then the encrypted characters are compared Are the strings equal? ​​The online encrypted URL http://www.ttmd5.com/hash.php?type=9 code is as follows public static void main(String[] args) { String str = "123456"; String sha256Str = getSHA256Str(str) ; System.out.println https://blog.csdn.net/lh155136/article/details/119325554

Guess you like

Origin blog.csdn.net/weixin_42078172/article/details/127446031