0

I have this code:

SecretKeySpec keySpec = new SecretKeySpec(
        "CnZ3QvfIjYLL0FWDQeY9L+1XLQKv0jtufAqUcXYP9krzAjhYJvOuiAdBZqt9Ogw7".getBytes(),
        "HmacSha1");

Mac mac = Mac.getInstance("HmacSha1");
mac.init(keySpec);
byte[] result = mac.doFinal("pesho".getBytes());

String decoded = new String(result);
System.out.println(decoded);
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(result));

which outputs:

ё|zЅ!)fЮпFгЅ$‰ж<Т.
Grh8Dnq9ISlm3u9G470kieY80i4=

when it should be outputting:

1ab87c0e7abd212966deef46e3bd2489e63cd22e
MWFiODdjMGU3YWJkMjEyOTY2ZGVlZjQ2ZTNiZDI0ODllNjNjZDIyZQ==

Why is this happening?

1 Answer 1

1

It works correctly. It just returns the byte[] array and you convert it to String, but what you really need is to get the hex representation of this byte array. You can convert byte array to hex string using the bytesToHex method from this answer:

SecretKeySpec keySpec = new SecretKeySpec(
        "CnZ3QvfIjYLL0FWDQeY9L+1XLQKv0jtufAqUcXYP9krzAjhYJvOuiAdBZqt9Ogw7".getBytes(),
        "HmacSha1");

Mac mac = Mac.getInstance("HmacSha1");
mac.init(keySpec);
byte[] result = mac.doFinal("pesho".getBytes());

String decoded = bytesToHex(result).toLowerCase();
System.out.println(decoded);
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(decoded.getBytes(StandardCharsets.ISO_8859_1)));

This produces exactly what you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.