Tuesday, June 12, 2012

Java HMAC-SHA256

While MD5 or SHA256 can be used to verify the integrity of a transmitted file, it doesn't guarantee that the file came from an authorized source. One way to do it is to use HMAC-SHA256 to create a signed hash. It uses a symmetric key approach where both sides are in possession of an identical key.

To verify that the file is signed by the same key, just sign the payload with the HMAC-SHA256 algorithm and the key, and then verify that the outputs are the same.

Java provides this functionality out-of-the-box in the javax.crypto package.

Code Sample:

byte[] payload = <the payload to sign>;
byte[] signatureBytes = <the sent signature>;
String key = "XXXXXXXXXXXXXX";
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] keyBytes = key.getBytes("US-ASCII");
SecretKey secretKey = new SecretKeySpec(keyBytes,hmacSha256.getAlgorithm());

hmacSha256.init(secretKey);
hmacSha256.update(payload);

byte[] signedPayload = hmacSha256.doFinal();

boolean result = Arrays.equals(signedPayload, signatureBytes);

No comments:

Post a Comment