/*
 * @Author: Kane
 * @Date: 2023-05-25 19:36:27
 * @LastEditors: Kane
 * @FilePath: /NewCitizenQueryResult/src/main/java/com/cpic/xim/utils/security/sign/SignUtils.java
 * @Description: 
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */
package com.cpic.xim.utils.security.sign;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import java.util.Base64;
import java.util.Base64.Encoder;

public class SignUtils
{
    public SignUtils()
    {}

    private static byte[] md5( byte[] bytes ) throws Exception
    {
        MessageDigest md = MessageDigest.getInstance( "MD5" );

        md.update( bytes );

        return md.digest();
    }

    private static byte[] md5( String msg ) throws Exception
    {
        return StringUtils.isBlank( msg ) ? null : md5( msg.getBytes() );
    }

    private static String md5Encrypt( String msg ) throws Exception
    {
        Encoder encoder = Base64.getEncoder();
        String encode = encoder.encodeToString(md5(msg));

        return StringUtils.isBlank( msg ) ? null : encode;
    }

    public static String sign( Map<String, String> param ) throws Exception
    {
        try
        {
            Set<String> paramKey = param.keySet();
            String[] strs =
                    (String[]) (new ArrayList( paramKey )).toArray( new String[paramKey.size()] );
            Arrays.sort( strs );
            StringBuilder sb = new StringBuilder();
            String[] var4 = strs;
            int var5 = strs.length;

            for ( int var6 = 0; var6 < var5; ++var6 )
            {
                String str = var4[var6];
                
                sb.append( str ).append( "=" ).append( (String) param.get( str ) ).append( "&" );
            }

            String result = sb.toString();

            if ( StringUtils.isNotBlank( result ) && result.endsWith( "&" ) )
            {
                return md5Encrypt( result.substring( 0, result.length() - 1 ) );
            } else
            {
                throw new Exception( "未收到用于签名的参数，签名失败！" );
            }
        }
        catch ( Exception var8 )
        {
            throw new Exception( "签名失败！" );
        }
    }
}
