package com.cyksj.common.util.corp;

import com.cyksj.common.exception.AesException;
import com.cyksj.common.util.Codec;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @author chan
 * @date 2022-03-14 上午10:31
 */
public class SHA1 {

  /**
   * 用&串接arr参数，生成sha1 digest.
   */
  public static String genWithAmple(String... arr) throws Exception {
    Arrays.sort(arr);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < arr.length; i++) {
      String a = arr[i];
      sb.append(a);
      if (i != arr.length - 1) {
        sb.append('&');
      }
    }
    return Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.SHA1).setStringData(sb.toString()).toHexString();
  }


  /**
   * 用SHA1算法生成安全签名
   */
  public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {
    try {
      String[] array = new String[] { token, timestamp, nonce, encrypt };
      StringBuffer sb = new StringBuffer();
      // 字符串排序
      Arrays.sort(array);
      for (int i = 0; i < 4; i++) {
        sb.append(array[i]);
      }
      String str = sb.toString();
      // SHA1签名生成
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      md.update(str.getBytes());
      byte[] digest = md.digest();

      StringBuffer hexstr = new StringBuffer();
      String shaHex = "";
      for (int i = 0; i < digest.length; i++) {
        shaHex = Integer.toHexString(digest[i] & 0xFF);
        if (shaHex.length() < 2) {
          hexstr.append(0);
        }
        hexstr.append(shaHex);
      }
      return hexstr.toString();
    } catch (Exception e) {
      throw new AesException(AesException.ComputeSignatureError);
    }
  }
}
