一、遇到问题
java md5的输出结果和php md5的输出结果不一致。
二、解决代码
java
import java.security.MessageDigest;
public class md5Test {
/**
* @param input 输入
* @return 返回16个字节
* @throws Exception
*/
public static byte[] originMD5(byte[] input) throws Exception {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] out = md5.digest(input);
return out;
}
/**
* @param input 输入
* @return 返回16个字节
* @throws Exception
*/
public static byte[] MD5(byte[] input) throws Exception {
String str = new String(input, 0, input.length);
//创建MD5加密对象
MessageDigest md5 = MessageDigest.getInstance("MD5");
// 进行加密
md5.update(str.getBytes());
//获取加密后的字节数组
byte[] md5Bytes = md5.digest();
String res = "";
for (int i = 0; i < md5Bytes.length; i++) {
int temp = md5Bytes[i] & 0xFF;
// 转化成十六进制不够两位,前面加零
if (temp <= 0XF) {
res += "0";
}
res += Integer.toHexString(temp);
}
return res.getBytes();
}
public static void main(String[] args) throws Exception {
byte[] data = {0x4C, 0x2B, 0x3E, 0x5A, 0x26, 0x3A, 0x3C, 0x18};
byte[] md5Data = MD5(data);
String strMd5Key = new String(md5Data, 0, md5Data.length);
System.out.println(strMd5Key);
}
}
php
<?php
/**
* Created by PhpStorm.
* User: xianbin
* Date: 2018/11/20
* Time: 18:52
*/
class testhexstring
{
public function arr2Form($arr){
$tempStr = "";
foreach ($arr as $key=>$value){
$tempStr .=$key."=".$value."&";
}
return substr($tempStr, 0, strlen($tempStr) -1);
}
public function form2Arr($str){
$arr = array();
$array=explode('&', $str);
foreach ($array as $key){
$tempInfo=explode('=', $key);
$arr[$tempInfo[0]] = $tempInfo[1];
}
return $arr;
}
/**
* 将字节数组转化为String类型的数据
* @param $bytes 字节数组
* @param $str 目标字符串
* @return 一个String类型的数据
*/
public function toStr($bytes) {
$str = '';
foreach($bytes as $ch) {
$str .= chr($ch);
}
return $str;
}
/**
* 转换一个string字符串为byte数组
* @param $str 需要转换的字符串
* @param $bytes 目标byte数组
*/
public function getbytes($str) {
$len = strlen($str);
$bytes = array();
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;
}
}
$test = new testhexstring();
$data = array(0x4C, 0x2B, 0x3E, 0x5A, 0x26, 0x3A, 0x3C, 0x18);
$strData = $test->toStr($data);
$md5Data = md5($strData);
echo 'md5 origin is: ',$md5Data,PHP_EOL;
?>
结果:
更多推荐
解决java md5和php md5 结果不一致问题
发布评论