Jeroen
Jeroen

Reputation: 161

Passing a Base64 encoded String into sha512 function gives different result than when hard coded

I'm coding in Android Studio and I'm trying to create base64 encoded and sha512 hashed String.

The functions are:

private String getBase64(String data){

    try{

        byte[] enc = data.getBytes("UTF-8");
        return Base64.encodeToString(enc, Base64.DEFAULT);

    }catch (Exception e){
        e.printStackTrace();
        return null;
    }

}

private String getSHA(String data){

    try {

        MessageDigest mda = MessageDigest.getInstance("SHA-512");
        byte[] digesta = mda.digest(data.getBytes("UTF-8"));

        return convertByteToHex(digesta);

    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
}


public String convertByteToHex(byte data[]) {
    StringBuilder hexData = new StringBuilder();
    for (byte aData : data)
        hexData.append(String.format("%02x", aData));
    return hexData.toString();
}

Then calling them:

    // line below prints VGVzdDox as it should
    Log.d("GO", "Working Base64: " + getBase64("Test:1"));

        // line below prints: 3553AF9EDC389314B0F7354B51FEA7EB089C039EA77A0FD7BD61798A8DD14B1292B353B9E00789B2698B072AF5B05417DDDAA1870ADF9E1DE9C1F96D9465DF56
    // as it should
    Log.d("GO", "Working SHA: " + getSHA("VGVzdDox"));


    String b = getBase64("Test:1");

    // line below prints VGVzdDox again, as it should
    Log.d("Base64", b);

    String s = getSHA(b);

    // Now this line prints a7d1bdc5d6497d787b35ce52774365150a2e21084958ffc14570367f3764b938fc1191d06006f1908084518c9697cbff3f2830a1ac003ef8ace36a0667dce92d
    // Not sure why?
    Log.d("SHA", s);

So that last output is wrong. However the getBase64 is right and the getSHA also when hard coding the base64 encoded String. And I have no idea why. This is just the main activity, no other code is executed.

Upvotes: 0

Views: 1358

Answers (2)

Hani
Hani

Reputation: 104

it seems like your String

b

have a new line at the end, i tested it with an online sha 512 generator with the String:

"VGVzdDox" and

"VGVzdDox

"

output of the first one is:

3553AF9EDC389314B0F7354B51FEA7EB089C039EA77A0FD7BD61798A8DD14B1292B353B9E00789B2698B072AF5B05417DDDAA1870ADF9E1DE9C1F96D9465DF56

the out put for the second is:

A7D1BDC5D6497D787B35CE52774365150A2E21084958FFC14570367F3764B938FC1191D06006F1908084518C9697CBFF3F2830A1AC003EF8ACE36A0667DCE92D

so get rid of the line seperator maybe with the method Stirng.trim(), but i didn't tested it

Upvotes: 1

Jeroen
Jeroen

Reputation: 161

Found it, had to change:

return Base64.encodeToString(enc, Base64.DEFAULT);

to

return Base64.encodeToString(enc, Base64.NO_WRAP);

Upvotes: 0

Related Questions