package com.fzm.mall.server.admin.util;

import lombok.extern.slf4j.Slf4j;

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

/**
 * @author wangpeng
 * @description SHA-256加密
 * @date 2020/07/14 18:09:06
 */
@Slf4j
public class Sha256Util {

    /**
     * java原生sha256加密
     *
     * @param data 待加密字符串
     * @return 加密后字符串
     */
    public static String encode(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] digest = messageDigest.digest();
            StringBuilder strHexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    strHexString.append('0');
                }
                strHexString.append(hex);
            }
            return strHexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.info("SHA256加密出错");
        }
        return null;
    }

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