要求:待签名数据以UTF-8的格式转字节流,对字节流进行MD5算法得到的签名字节流,再经过Base64转换为字符串,即生成了数字签名。
所有编码都是 UTF-8 编码
字符串:A12345
值:hySqdYwvZi15lShw70hupg==
JAVA
foxwho.风
package com.example.demo;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;
public class DemoApplication {
public static void main(String[] args) {
// SpringApplication.run(DemoApplication.class, args);
System.out.println("=================");
System.out.println(makeSign("A12345", ""));
System.out.println("=================");
}
protected static String ENCODE = "UTF-8";
public static String makeSign(String bizData, String pwd) {
String data = bizData + pwd;
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(data.getBytes(ENCODE));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
byte[] b = md.digest();
return Base64.encodeBase64String(b);
}
}
PHP
/**
* @param $str
* @return string
*/
function md5Base64ByJava($str)
{
return base64_encode(Bytes::toStr(unpack("c*", md5($str, true))));
}
// Bytes 类
class Bytes
{
/**
* 转换一个String字符串为byte数组
* @param $str 需要转换的字符串
* @param $bytes 目标byte数组
* @author Zikie
*/
public static function getBytes($str)
{
$len = strlen($str);
$bytes = [];
for ($i = 0; $i < $len; $i++) {
if (ord($str[$i]) >= 128) {
$byte = ord($str[$i]) - 256;
} else {
$byte = ord($str[$i]);
}
$bytes[] = $byte;
}
return $bytes;
}
/**
* 将字节数组转化为String类型的数据
* @param $bytes 字节数组
* @param $str 目标字符串
* @return 一个String类型的数据
*/
public static function toStr($bytes)
{
$str = '';
foreach ($bytes as $ch) {
$str .= chr($ch);
}
return $str;
}
/**
* 转换一个int为byte数组
* @param $byt 目标byte数组
* @param $val 需要转换的字符串
* @author Zikie
*/
public static function integerToBytes($val)
{
$byt = [];
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff);
$byt[2] = ($val >> 16 & 0xff);
$byt[3] = ($val >> 24 & 0xff);
return $byt;
}
/**
* 从字节数组中指定的位置读取一个Integer类型的数据
* @param $bytes 字节数组
* @param $position 指定的开始位置
* @return 一个Integer类型的数据
*/
public static function bytesToInteger($bytes, $position)
{
$val = 0;
$val = $bytes[$position + 3] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 2] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 1] & 0xff;
$val <<= 8;
$val |= $bytes[$position] & 0xff;
return $val;
}
/**
* 转换一个shor字符串为byte数组
* @param $byt 目标byte数组
* @param $val 需要转换的字符串
* @author Zikie
*/
public static function shortToBytes($val)
{
$byt = [];
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff);
return $byt;
}
/**
* 从字节数组中指定的位置读取一个Short类型的数据。
* @param $bytes 字节数组
* @param $position 指定的开始位置
* @return 一个Short类型的数据
*/
public static function bytesToShort($bytes, $position)
{
$val = 0;
$val = $bytes[$position + 1] & 0xFF;
$val = $val << 8;
$val |= $bytes[$position] & 0xFF;
return $val;
}
}
使用方式
md5Base64ByJava("A12345");