应用场景:待签名数据以UTF-8的格式转字节流,对字节流进行MD5算法得到的签名字节流,再经过Base64转换为字符串,即生成签名。
import java.security.MessageDigest;
/**
* 需要引入的共同jar包
* apache-commons-codec-1.4.jar
*/
import org.apache.commons.codec.binary.Base64;
import java.util.Date;
/**
* 方式二,需要引入的jar包
* sun.misc.BASE64Encoder.jar
*/
import sun.misc.BASE64Encoder;
/**
* 文件名称: Md5.java
* 功能说明:对字节流进行MD5算法处理,然后base64编码
*/
public class Md5{
public static void main(String[] args) throws Exception {
//String timestamp = String.valueOf(new Date().getTime());//获取当前13位时间戳
String timestamp="1566869002135";//模拟当前13位时间戳
String charset="utf-8";//编码
String secretKey="123456789";//模拟秘钥
String Sign = doSin(timestamp, charset, secretKey);
System.out.println(Sign);
String Source = getSign(timestamp, charset, secretKey);
System.out.println(Source);
}
/**
* Base64.encodeBase64模式
* @param timestamp
* @param charset
* @param secretKey
* @return String 'DFZ16dpGQ3MQDttv2LHOmw=='
* @throws Exception
*/
public static String doSin(String timestamp, String charset, String secretKey) throws Exception{
String sign ="";
String content = timestamp+secretKey;
try {
MessageDigest md = MessageDigest.getInstance( "MD5");
md.update(content.getBytes(charset));
sign = new String(Base64.encodeBase64(md.digest()),charset);
} catch (Exception e) {
throw new RuntimeException(e);
}
return sign;
}
/**
* BASE64Encoder模式
* @param timestamp
* @param charset
* @param secretKey
* @return String 'DFZ16dpGQ3MQDttv2LHOmw=='
* @throws Exception
*/
public static String getSign(String timestamp, String charset, String secretKey) throws Exception{
String sign = "";
String content = timestamp+secretKey;
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] bts = digest.digest(content.getBytes(charset));
BASE64Encoder encoder = new BASE64Encoder();
sign = encoder.encode(bts);
return sign;
}
}
所需jar包下载地址:https://download.csdn.net/download/netuser1937/11618341
JAVA与PHP相同加密结果
参考PHP版:https://blog.csdn.net/netuser1937/article/details/100097964