Skip to content

Instantly share code, notes, and snippets.

@dzmitry-savitski
Last active June 24, 2025 17:35
Show Gist options
  • Save dzmitry-savitski/0c9c7f54ad8c1c87fad44fa9b28924a7 to your computer and use it in GitHub Desktop.
Save dzmitry-savitski/0c9c7f54ad8c1c87fad44fa9b28924a7 to your computer and use it in GitHub Desktop.
ig
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.UUID
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import org.forgerock.util.encode.Base64
def SECRET = "my-super-secret-key" // 🔐 Replace with real shared secret
String computeSignature(String method, String path, String timestamp, String nonce, String body, String secret) {
String data = "${method.toUpperCase()}\n${path}\n${timestamp}\n${nonce}\n${body}"
SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")
Mac mac = Mac.getInstance("HmacSHA256")
mac.init(keySpec)
byte[] hmacBytes = mac.doFinal(data.getBytes("UTF-8"))
return Base64.encode(hmacBytes)
}
def timestamp = DateTimeFormatter.ISO_INSTANT.format(Instant.now())
def nonce = UUID.randomUUID().toString()
def method = request.method
def path = request.uri.path
def body = request.entity?.string ?: ""
// Calculate signature
def signature = computeSignature(method, path, timestamp, nonce, body, SECRET)
// Add headers
request.headers.add("X-Timestamp", timestamp)
request.headers.add("X-Nonce", nonce)
request.headers.add("X-API-Key", "your-key-id") // or use env/config
request.headers.add("X-Signature", signature)
logger.info("HMAC Signature Added: ${signature}")
return next.handle(context, request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment