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?

Mario Stoilov
  • 3,411
  • 5
  • 31
  • 51

1 Answers1

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.

Community
  • 1
  • 1
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334