Payload Validation
When you define an authentication token, Monkey uses it to generate a payload signature hash. This hash is sent in each request in the X-Hub-Signature header
.
Monkey uses HMAC Base64-encoded digest to calculate the hash, and you can use the same mechanism to generate and validate the token.
Examples:
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class XHubHeaderUtils {
public static boolean isValid(String secret, String payload, String xHubSignature)
throws InvalidKeyException, NoSuchAlgorithmException {
String digest = "HmacSHA256";
Mac mac = Mac.getInstance(digest);
mac.init(new SecretKeySpec(secret.getBytes(), digest));
String computedHash = new String(Base64.getEncoder().encode(mac.doFinal(payload.getBytes())));
return MessageDigest.isEqual(computedHash.getBytes(StandardCharsets.UTF_8),
xHubSignature.getBytes(StandardCharsets.UTF_8));
}
}
def isValid(secret, payload, verify):
import hmac
import hashlib
import base64
hashBytes = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()
base64Hash = base64.b64encode(hashBytes)
return hmac.compare_digest(verify, base64Hash)
using System;
using System.Text;
using System.Security.Cryptography;
public static class XHubHeaderUtils {
public static bool isValid(string secret, string payload, string xHubSignature)
{
byte[] bytes = Encoding.UTF8.GetBytes(secret);
HMAC hmac = new HMACSHA256(bytes);
bytes = Encoding.UTF8.GetBytes(payload);
String hash = Convert.ToBase64String(hmac.ComputeHash(bytes));
return CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(hash), Convert.FromBase64String(xHubSignature));
}
}
Updated 7 months ago