Problem using javax.crypto pacakges

K

K Viltersten

I've composed a small application that makes
use of MAC class but even though i get a mac
value, it's not correct, according to the
control values.

I wonder if i've missed anything. As far as
i've been googling, it's supposed to be
correct but it's possible that something has
slipped my eye.

String str = "1234567890ABCDEF1234567890ABCDEF";
byte[] keys = str.getBytes();
Key key = new SecretKeySpec(keys, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
byte[] results = mac.doFinal("00000000".getBytes());
StringBuilder stringBuilder = new StringBuilder();
for (byte result : results)
stringBuilder.append(
String.format("%02x", result));
String output = stringBuilder.toString();

Any ideas are welcome. Thanks in advance.
 
A

alexandre_paterson

...
byte[] results = mac.doFinal("00000000".getBytes());
...

Do you really want to compute the cryptographic hash of
the string "00000000" encoded in a byte array using
your platform's default encoding? (which is what
the String class's getBytes() method does give you).

If your platform's default encoding is UTF-8 (or ASCII)
then that line is equivalent to:

final byte[] results = mac.doFinal( new byte[] {48, 48, 48, 48, 48,
48, 48, 48} );

Is this really what you want to compute?
 
K

K Viltersten

...
byte[] results = mac.doFinal("00000000".getBytes());
...

Do you really want to compute the cryptographic hash of
the string "00000000" encoded in a byte array using
your platform's default encoding? (which is what
the String class's getBytes() method does give you).

If your platform's default encoding is UTF-8 (or ASCII)
then that line is equivalent to:

final byte[] results = mac.doFinal( new byte[]
{48, 48, 48, 48, 48, 48, 48, 48} );

Is this really what you want to compute?

I see the reason for your scepticism but in this
particular case, yes, that's what i wish to do.
For starters, anyway.

I've found what was the error. The key, 12345678,
i interpreted as:
0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08
but should have interpret it as follows.
0x12 0x34 0x56 0x78

That was the problem. No wonder i could go in
circles for several hours...

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top