HMAC256MacValidator implements MacValidator { @Override public boolean validateResponse(final String orderKey, final String worldpayMac, final String paymentAmount, final String paymentCurrency, final AuthorisedStatus paymentStatus, final String macSecret) throws WorldpayMacValidationException { if (StringUtils.isBlank(worldpayMac) || StringUtils.isBlank(macSecret)) { throw new WorldpayMacValidationException("No mac found in the response url provided by Worldpay"); } final String hashString = StringUtils.join(asList(orderKey, paymentAmount, paymentCurrency, paymentStatus.name()), ":"); try { Mac hmacSHA256 = Mac.getInstance(HMAC_SHA_256); SecretKeySpec secretKeySpec = new SecretKeySpec(macSecret.getBytes(StandardCharsets.UTF_8.name()), HMAC_SHA_256); hmacSHA256.init(secretKeySpec); final byte[] hashValue = hmacSHA256.doFinal(hashString.getBytes(StandardCharsets.UTF_8.name())); return worldpayMac.equalsIgnoreCase(Hex.encodeHexString(hashValue)); } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) { throw new WorldpayMacValidationException("Unable to validate mac as hash algorithm incorrectly specified", e); } }  @Override boolean validateResponse(final String orderKey, final String worldpayMac, final String paymentAmount,
                                    final String paymentCurrency, final AuthorisedStatus paymentStatus, final String macSecret);  }
@Test public void testSha256Valid() throws WorldpayMacValidationException { final boolean result = testObj.validateResponse("MYADMINCODE^MYMERCHANT^T0211010", "856ff737b2987f21513b91992818d983ce9fed97847b15756c56493a23090415", "1400", "GBP", AuthorisedStatus.AUTHORISED, "@p-p1epie"); assertTrue("Mac validation code correct", result); }
@Test public void testSha256Invalid() throws WorldpayMacValidationException { final boolean result = testObj.validateResponse("MYADMINCODE^MYMERCHANT^T0211010", "856ff737b2987f21513b91992818d983ce9fed97847b15756c56493a23090416", "1400", "GBP", AuthorisedStatus.AUTHORISED, "@p-p1epie"); assertFalse("Mac validation code incorrect", result); }
@Test public void testValidateResponseInvalidNulls() throws WorldpayMacValidationException { thrown.expect(WorldpayMacValidationException.class); testObj.validateResponse(null, null, null, null, null, null); fail("Mac validation should fail with caught exception"); }
@Test public void testValidateResponseInvalidPartialNulls() throws WorldpayMacValidationException { thrown.expect(WorldpayMacValidationException.class); boolean result = testObj.validateResponse(null, "25eefe952a6bbd09fe1c2c09bca4fa08", null, null, null, null); assertFalse("Mac validation code correct", result); }