signature.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package imgproxytest;
  2. import org.junit.jupiter.api.Test;
  3. import java.util.Base64;
  4. import javax.crypto.Mac;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import static org.junit.jupiter.api.Assertions.*;
  7. public class ImgProxy{
  8. @Test
  9. public void testWithJavaHmacApacheBase64ImgProxyTest() throws Exception {
  10. byte[] key = hexStringToByteArray("943b421c9eb07c830af81030552c86009268de4e532ba2ee2eab8247c6da0881");
  11. byte[] salt = hexStringToByteArray("520f986b998545b4785e0defbc4f3c1203f22de2374a3d53cb7a7fe9fea309c5");
  12. String path = "/rs:fit:300:300/plain/http://img.example.com/pretty/image.jpg";
  13. String pathWithHash = signPath(key, salt, path);
  14. assertEquals("/m3k5QADfcKPDj-SDI2AIogZbC3FlAXszuwhtWXYqavc/rs:fit:300:300/plain/http://img.example.com/pretty/image.jp", pathWithHash);
  15. }
  16. public static String signPath(byte[] key, byte[] salt, String path) throws Exception {
  17. final String HMACSHA256 = "HmacSHA256";
  18. Mac sha256HMAC = Mac.getInstance(HMACSHA256);
  19. SecretKeySpec secretKey = new SecretKeySpec(key, HMACSHA256);
  20. sha256HMAC.init(secretKey);
  21. sha256HMAC.update(salt);
  22. String hash = Base64.getUrlEncoder().withoutPadding().encodeToString(sha256HMAC.doFinal(path.getBytes()));
  23. return "/" + hash + path;
  24. }
  25. private static byte[] hexStringToByteArray(String hex){
  26. if (hex.length() % 2 != 0)
  27. throw new IllegalArgumentException("Even-length string required");
  28. byte[] res = new byte[hex.length() / 2];
  29. for (int i = 0; i < res.length; i++) {
  30. res[i]=(byte)((Character.digit(hex.charAt(i * 2), 16) << 4) | (Character.digit(hex.charAt(i * 2 + 1), 16)));
  31. }
  32. return res;
  33. }
  34. }