package com.jwipc.util;/*
 * The Hefei Ceshi RDC(Research and Development Centre) Group.
 * __________________
 *
 *    Copyright 2015-$today.yea
 *    All Rights Reserved.
 *
 *    NOTICE:  All information contained herein is, and remains
 *    the property of Ceshi Company and its suppliers,
 *    if any.
 */


import cn.hutool.core.util.HexUtil;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * <p> 密码工具 </p>
 *
 * @author sog
 * @version 1.0
 * @since JDK 1.7
 */
@SuppressWarnings("unused")
public class PasswordUtilSHA256 {

    /**
     * sha-算法名称
     */
    public static final String HASH_ALGORITHM = "SHA-256";
    /**
     * 计算次数
     */
    public static final int HASH_INTERATIONS = 1;
    /**
     * 长度
     */
    private static final int SALT_SIZE = 8;
    private static final SecureRandom random = new SecureRandom();



    /**
     * 生成密码
     *
     * @param salt     盐值
     * @param password 明文密码
     * @return 混淆后的密码
     */
    public static String password(byte[] salt, String password) {
        final byte[] passwordBytes = PasswordUtilSHA256.sha1(password.getBytes(), salt);
        final String saltPassword = HexUtil.encodeHexStr(passwordBytes);
        return saltPassword.toUpperCase();
    }


    public static byte[] sha1(byte[] input, byte[] salt) {
        return digest(input, salt, HASH_INTERATIONS);
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
            if (salt != null) {
                digest.update(salt);
            }
            byte[] result = digest.digest(input);
            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            throw new AssertionError(e);
        }
    }



//    public static void main(String[] args) {
//
//        final String password = "123456";
//        String userPass = PasswordUtilSHA256.password(null, password);
//        System.out.println(userPass);
//    }
}
