반응형
일. 문제에 봉착하다
자바 md5의 출력 결과와 phpmd5 의 출력 결과가 일치하지 않는다.
2.해결코드
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;
//16진법으로는 두 분 모자라지만, 앞에는 0을 더한다
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;
?>
결과:
반응형
'개발 꿀팁 > PHP' 카테고리의 다른 글
php는 데몬을 구현하는 두 가지 방식이다 (0) | 2022.07.13 |
---|---|
PHP 파일 형식 판단 (0) | 2022.07.13 |
도커 원클릭 Nginx+PHP 환경 구축 (자동 배치 명령 포함) (0) | 2022.07.13 |
PHP가 HTTP 요청을 보내는 6가지 방법 (0) | 2022.07.13 |
php+mysql 구현 페이지: 이전 페이지, 다음 페이지 (0) | 2022.07.13 |