You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package net.educoder.util ;
import org.springframework.util.DigestUtils ;
import java.io.UnsupportedEncodingException ;
import java.util.Arrays ;
import java.util.Map ;
/**
* @Author: youys
* @Date: 2022/4/20
* @Description:
*/
public class SignatureUtil {
/**
* 按字典排序签名.
*
* @param secretKey
* @param params
* @return
* @throws UnsupportedEncodingException
*/
public static String genSignature ( String secretKey , Map < String , Object > params ) {
if ( secretKey = = null | | params = = null | | params . size ( ) = = 0 ) {
return "" ;
}
// 1. 参数名按照ASCII码表升序排序
String [ ] keys = params . keySet ( ) . toArray ( new String [ 0 ] ) ;
Arrays . sort ( keys ) ;
// 2. 按照排序拼接参数名与参数值
StringBuffer paramBuffer = new StringBuffer ( ) ;
for ( String key : keys ) {
paramBuffer . append ( "&" + key ) . append ( params . get ( key ) = = null ? "" : "=" + params . get ( key ) ) ;
}
// 3. 将secretKey拼接到最后
paramBuffer = paramBuffer . append ( "&sk=" + secretKey ) ;
String pa = paramBuffer . substring ( 1 ) ;
// 4. MD5是128位长度的摘要算法, 用16进制表示, 一个十六进制的字符能表示4个位, 所以签名后的字符串长度固定为32个十六进制字符。
try {
return DigestUtils . md5DigestAsHex ( pa . getBytes ( "UTF-8" ) ) . toUpperCase ( ) ;
} catch ( UnsupportedEncodingException e ) {
return "" ;
}
}
}