MD5得到字节流再进行Base64编码(Java、PHP)
2021-11-25 16:53:58
待签名数据以UTF-8的格式转字节流,对字节流进行MD5算法得到的签名字节流,再经过Base64转换为字符串。
Java代码
```
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;
}
}
```
如果你的项目是PHP,对应代码如下
```
<?php
$res = base64_encode(pack('H*', md5($str)));
```
下面是某通物流对接文档中的算法截图:
![中通物流签名.png](https://static.daimaku.net/post/202111/25/3e9561b8e185f35c44a9c6af61a65b54.png)