Validação do Payload
Quando você define um token de autenticação, a Monkey faz uso dele para a geração de um hash de assinatura do payload. Esse hash é enviado em cada requisição no header X-Hub-Signature
.
A Monkey utiliza HMAC Base64-encoded digest para calcular o hash, você pode utilizar o mesmo mecanismo para gerar e validar o token.
Ex:
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 about 1 year ago