I don't know how to realize these few lines from php to java..
$varInHex = "\x22\x33\xAd\xB5\x2b\xE6\x22\x33\x12\x36\x22\x31\xCA\x22\x11\x41\x62\x21\x22\x01\x55\x22\x71\x42\x10\x36";<br/><br/>
$result = md5($varInHex);
echo $result;
Well, I tried to convert it but I'm getting a different result!
byte[] seq20 = new byte[]{(byte)0x22,(byte)...etc...};
String str = seq20.toString();
String result = md5(str);
System.out.println(result);
public static String md5(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes("UTF-8"));
return getString(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String getString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
String hex = Integer.toHexString((int) 0x00FF & b);
if (hex.length() == 1) {
sb.append("0");
}
sb.append(hex);
}
return sb.toString();
}
result in java is different from result in php..
Can you help me please?? Thank you in advance :)
Neither of the other two answers are affirmatively wrong, but from an elegance standpoint, consider the following
edit: The use of
String...
varargs is totally optional, but it makes the function a little easier, as it avoids the overhead of string concatenation in the calling function.Can't you use seq20 directly without converting it so string? I would do it this way:
My guess is PHP is evaluating the above as a string, not hex. And Java is doing it as you expect it.
The accepted solution:
contains an implemention that will fail 1/256 times because the output of md5sum can have more than one leading zero. An example md5 input that will elicit this error is: "15446:68106" (without quotes).
I recommend using the apache commons DigestUtils.md5Hex if you need a md5 that matches the php implementation.