Apache base64 codec encode / decode - not getting expected result

I made a POC using apache codec base64 library where I encrypted the string using SHA. (This can be ignored.)

Step 1 - I have printed a byte array for this string.

Step 2 - Encoded byte array and printed its value.

Step 3 - Decode the encoded value and print it.

public static void main(String[] args)
{
    MessageDigest messageDigest = null;
    String ALGORITHM = "SHA";
    try
    {
        messageDigest = MessageDigest.getInstance(ALGORITHM);

        byte[] arr = "admin1!".getBytes();
        byte[] arr2 = messageDigest.digest(arr);

        System.out.println(arr2);
        String encoded = Base64.encodeBase64String(arr2);

        System.out.println(encoded);
        byte[] decoded = Base64.decodeBase64(encoded);

        System.out.println(decoded);
    }
    catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
}

      

Expected Result: Step 1 and Step 3 should give the same result. But I donโ€™t get it.

Output:

[B @ 5ca801b0

90HMfRqqpfwRJge0anZat98BTdI =

[B @ 68d448a1

+3


source to share


1 answer


Your program is nice and wonderful. Only one mistake.

System.out.println(byteArray);

prints the hashCode of the byte array object. ( Note: Arrays are objects in Java, not a primitive type)

You should use instead System.out.println(Arrays.toString(byteArray));

and you will get the same value for both steps 1 and 3.

By javadocs Arrays.toString(byte[] a)

returns a string representation of the contents of the specified array.

Your code after the changes will be:



public static void main(String[] args)
{
MessageDigest messageDigest = null;
String ALGORITHM = "SHA";
try
    {
    messageDigest = MessageDigest.getInstance(ALGORITHM);

    byte[] arr = "admin1!".getBytes();
    byte[] arr2 = messageDigest.digest(arr);

    System.out.println(Arrays.toString(arr2));
    String encoded = Base64.encodeBase64String(arr2);

    System.out.println(encoded);
    byte[] decoded = Base64.decodeBase64(encoded);

    System.out.println(Arrays.toString(decoded));
    }
    catch (NoSuchAlgorithmException e)
    {
    e.printStackTrace();
    }
}

      

and the output will be:

[- 9, 65, -52, 125, 26, -86, -91, -4, 17, 38, 7, -76, 106, 118, 90, -73, -33, 1, 77, -46]

90HMfRqqpfwRJge0anZat98BTdI =

[- 9, 65, -52, 125, 26, -86, -91, -4, 17, 38, 7, -76, 106, 118, 90, -73, -33, 1, 77, -46]

Note the meaning of the byte array is the same.

+1


source







All Articles