某些情況下java md5 base64_encode 與 php md5 base64_encode的簽名
阿新 • • 發佈:2018-12-12
要求:待簽名資料以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");