package shop.alien.util.encryption;

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

/**
 * SHA256加密
 *
 * @author ssk
 * @version 1.0
 * @date 2020/1/17 11:50
 */
public class Sha256Util {

    /**
     * 利用java原生的类实现SHA256加密
     *
     * @param str 需要加密的字符串
     * @return String
     */
    public static String getSha256(String str) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < messageDigest.digest().length; i++) {
                String temp;
                temp = Integer.toHexString(messageDigest.digest()[i] & 0xFF);
                if (temp.length() == 1) {
                    //1得到一位的进行补0操作
                    stringBuilder.append("0");
                }
                stringBuilder.append(temp);
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA256加密出错！！+" + e);
        }
    }

    public static void main(String[] args) {
        System.out.println(getSha256("123456"));
    }
}
