|
| 1 | +package com.twilio.security; |
| 2 | + |
| 3 | +import org.apache.commons.codec.binary.Base64; |
| 4 | + |
| 5 | +import javax.crypto.Mac; |
| 6 | +import javax.crypto.spec.SecretKeySpec; |
| 7 | +import java.nio.charset.StandardCharsets; |
| 8 | +import java.util.ArrayList; |
| 9 | +import java.util.Collections; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Map; |
| 12 | + |
| 13 | +public class RequestValidator { |
| 14 | + |
| 15 | + private static final String HMAC = "HmacSHA1"; |
| 16 | + |
| 17 | + private final SecretKeySpec signingKey; |
| 18 | + |
| 19 | + public RequestValidator(String authToken) { |
| 20 | + this.signingKey = new SecretKeySpec(authToken.getBytes(), HMAC); |
| 21 | + } |
| 22 | + |
| 23 | + public boolean validate(String url, Map<String, String> params, String expectedSignature) { |
| 24 | + String signature = getValidationSignature(url, params); |
| 25 | + return secureCompare(signature, expectedSignature); |
| 26 | + } |
| 27 | + |
| 28 | + private String getValidationSignature(String url, Map<String, String> params) { |
| 29 | + try { |
| 30 | + |
| 31 | + StringBuilder builder = new StringBuilder(url); |
| 32 | + if (params != null) { |
| 33 | + List<String> sortedKeys = new ArrayList<>(params.keySet()); |
| 34 | + Collections.sort(sortedKeys); |
| 35 | + |
| 36 | + for (String s : sortedKeys) { |
| 37 | + builder.append(s); |
| 38 | + |
| 39 | + String v = params.get(s); |
| 40 | + builder.append(v == null ? "" : v); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + Mac mac = Mac.getInstance(HMAC); |
| 45 | + mac.init(signingKey); |
| 46 | + |
| 47 | + byte[] rawHmac = mac.doFinal(builder.toString().getBytes(StandardCharsets.UTF_8)); |
| 48 | + return new String(Base64.encodeBase64(rawHmac)); |
| 49 | + |
| 50 | + } catch (Exception e) { |
| 51 | + return null; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private boolean secureCompare(String a, String b) { |
| 56 | + if (a == null || b == null) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + int n = a.length(); |
| 61 | + if (n != b.length()) { |
| 62 | + return false; |
| 63 | + } |
| 64 | + |
| 65 | + int mismatch = 0; |
| 66 | + for (int i = 0; i < n; ++i) { |
| 67 | + mismatch |= a.charAt(i) ^ b.charAt(i); |
| 68 | + } |
| 69 | + return mismatch == 0; |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments