/* Copyright 2020 The FedLearn Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.jdt.fedlearn.core.util;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HashUtil {
    private static final Logger logger = LoggerFactory.getLogger(HashUtil.class);

    public static String sha1(String data) {
        //加盐   更安全一些
        data += "lyz";
        try {
            //信息摘要器                                算法名称
            MessageDigest md = null;

            md = MessageDigest.getInstance("SHA1");

            //把字符串转为字节数组
            byte[] b = data.getBytes(StandardCharsets.UTF_8);
            //使用指定的字节来更新我们的摘要
            md.update(b);
            //获取密文  （完成摘要计算）
            byte[] b2 = md.digest();
            //获取计算的长度
            int len = b2.length;
            //16进制字符串
            String str = "0123456789abcdef";
            //把字符串转为字符串数组
            char[] ch = str.toCharArray();

            //创建一个40位长度的字节数组
            char[] chs = new char[len * 2];
            //循环20次
            for (int i = 0, k = 0; i < len; i++) {
                byte b3 = b2[i];//获取摘要计算后的字节数组中的每个字节
                // >>>:无符号右移
                // &:按位与
                //0xf:0-15的数字
                chs[k++] = ch[b3 >>> 4 & 0xf];
                chs[k++] = ch[b3 & 0xf];
            }
            return new String(chs);
        } catch (NoSuchAlgorithmException e) {
            logger.error("MessageDigest.getInstance error", e);
            return data + "9031";
        }
        //字符数组转为字符串

    }

    //decision d-h
    public static String ddh(String input) {
        return input;
    }

    public static BigInteger md5(String singleUid) {
        byte[] b2 = singleUid.getBytes(StandardCharsets.UTF_8);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            b2 = md.digest(singleUid.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException e) {
            logger.error("md5 error", e);
        }
        //获取密文  （完成摘要计算）

        BigInteger y = new BigInteger(b2);
        return y;
    }
}
