Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MD5 hash is different

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 :)

like image 341
fran Avatar asked Nov 29 '10 13:11

fran


People also ask

Are MD5 hashes always the same?

Since a single character represents eight bits (to form a byte), the total bit count of an MD5 hash is 128 bits. Two hexadecimal characters form a byte, so 32 hexadecimal characters equal 16 bytes. The MD5 length will always be the same: a 128-bit hash.

Is an MD5 hash unique?

Commonly referred to as a "digital fingerprint," a hash value is a special encryption code that is associated with each computer file. Hash values provide digital files with a unique identifier that corresponds to its contents.

What causes MD5 hash to change?

MD5 Checksum is used to verify the integrity of files, as virtually any change to a file will cause its MD5 hash to change. Most commonly, md5sum is used to verify that a file has not changed as a result of a faulty file transfer, a disk error or non-malicious modification.

How many different MD5 hashes are there?

For example, the MD5 hash is always 128 bits long (commonly represented as 16 hexadecimal bytes). Thus, there are 2^128 possible MD5 hashes.


1 Answers

Can't you use seq20 directly without converting it so string? I would do it this way:

md.update( seq20 ); 
byte[] md5sum = md.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
output = bigInt.toString(16);
while ( output.length() < 32 ) {
    output = "0"+output;
}
like image 66
stacker Avatar answered Oct 05 '22 12:10

stacker