package ee.tuleva.onboarding.notification.payment.validator;

import ee.tuleva.onboarding.notification.payment.IncomingPayment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
@Slf4j
public class MacCodeValidator implements ConstraintValidator<ValidMacCode, IncomingPayment> {

  @Value("${maksekeskus.secret}")
  private String secret;

  @Override
  public boolean isValid(IncomingPayment incomingPayment, ConstraintValidatorContext context) {
    String json = incomingPayment.getJson();
    String mac = incomingPayment.getMac();
    String calculatedHash = sha512(json + secret);

    return calculatedHash.equalsIgnoreCase(mac);
  }

  @Override
  public void initialize(ValidMacCode constraintAnnotation) {
  }

  private static String sha512(String string) {
    MessageDigest messageDigest = sha512MessageDigest();
    messageDigest.update(string.getBytes());
    byte hash[] = messageDigest.digest();

    StringBuilder hex = new StringBuilder();
    for (byte b : hash) {
      hex.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
    }
    return hex.toString();
  }

  private static MessageDigest sha512MessageDigest() {
    try {
      return MessageDigest.getInstance("SHA-512");
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }
}

@@ -445,16 +445,72 @@
 ption;%0A%0A
+import static java.nio.charset.StandardCharsets.UTF_8;%0A%0A
 @Compone
@@ -866,24 +866,60 @@
 t.getMac();%0A
+    String payload = json + secret;%0A
     String c
@@ -941,29 +941,23 @@
  sha512(
-json + secret
+payload
 );%0A%0A    
@@ -1123,22 +1123,23 @@
 (String 
-string
+payload
 ) %7B%0A    
@@ -1216,22 +1216,23 @@
 .update(
-string
+payload
 .getByte
@@ -1233,16 +1233,21 @@
 etBytes(
+UTF_8
 ));%0A    
@@ -1254,15 +1254,15 @@
 byte
+%5B%5D
  hash
-%5B%5D
  = m

Fix failing test under Windows