MD5MacValidator implements MacValidator { @Override public boolean validateResponse(final String orderKey, final String worldpayMac, final String paymentAmount, final String currency, final AuthorisedStatus status, final String macSecret) throws WorldpayMacValidationException { if (isBlank(worldpayMac)) { throw new WorldpayMacValidationException("No mac found in the response url provided by Worldpay"); } try { final String hashString = StringUtils.join(asList(orderKey, paymentAmount, currency, status != null ? status.name() : null, macSecret), ""); final MessageDigest digester = MessageDigest.getInstance("MD5"); byte[] digestedMac = digester.digest(hashString.getBytes(StandardCharsets.UTF_8.name())); return worldpayMac.equalsIgnoreCase(Hex.encodeHexString(digestedMac)); } catch (final NoSuchAlgorithmException | UnsupportedEncodingException 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 currency, final AuthorisedStatus status, final String macSecret);  }
@Test public void testValidateResponse() throws WorldpayMacValidationException { boolean result = testObj.validateResponse("MYADMINCODE^MYMERCHANT^T0211010", "25eefe952a6bbd09fe1c2c09bca4fa09", "1400", "GBP", AuthorisedStatus.AUTHORISED, "@p-plepie"); assertTrue("Mac validation code correct", result); }
@Test public void testValidateResponseInvalid() throws WorldpayMacValidationException { boolean result = testObj.validateResponse("MYADMINCODE^MYMERCHANT^T0211010", "25eefe952a6bbd09fe1c2c09bca4fa08", "1400", "GBP", AuthorisedStatus.AUTHORISED, "@p-plepie"); 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 { boolean result = testObj.validateResponse(null, "25eefe952a6bbd09fe1c2c09bca4fa08", null, null, null, null); assertFalse("Mac validation code correct", result); }