In network data transmission, encryption is a very important part. MD5 is a widely used encryption algorithm that converts data of any length into a 128-bit hash value. In Java, we can easily use the MD5 algorithm to encrypt data and convert it into a string in hexadecimal form, but if we need to use such an encrypted string in PHP, how to convert it?
First, we need to understand the differences in string encoding between Java and PHP. In Java, strings are encoded in UTF-16 by default, while in PHP, ASCII encoding is used by default. Therefore, when performing string conversion, we need to convert the string encoding first.
In Java, we can use the following code to MD5 encrypt the string and convert it to a hexadecimal string:
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Util { public static String getMD5(String message) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(message.getBytes()); byte[] mdBytes = md.digest(); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < mdBytes.length; i++) { int val = ((int) mdBytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } } }
In PHP, we can use the following code to encrypt the string MD5 encryption and conversion to hexadecimal string:
function stringToMd5Hex($str) { $str = iconv('UTF-8', 'UTF-16LE', $str); $md5 = md5($str); $hex = ''; for ($i = 0; $i < strlen($md5); $i += 2) { $hex .= chr(hexdec($md5[$i] . $md5[$i + 1])); } return bin2hex($hex); }
In this code, we use the iconv function to convert the string from UTF-8 encoding to UTF-16LE encoding. Then use PHP's built-in md5 function for MD5 encryption. Finally, use the chr function to convert the encryption result to a binary string, and use the bin2hex function to convert it to a hexadecimal string.
Through such processing, we can convert the MD5 encryption result in Java into a hexadecimal string usable in PHP to realize encrypted data transmission between Java and PHP.
The above is the detailed content of java md5 hexadecimal to php. For more information, please follow other related articles on the PHP Chinese website!