signature.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 url = "http://img.example.com/pretty/image.jpg";
  13. String resize = "fill";
  14. int width = 300;
  15. int height = 300;
  16. String gravity = "no";
  17. int enlarge = 1;
  18. String extension = "png";
  19. String urlWithHash = generateSignedUrlForImgProxy(key, salt, url, resize, width, height, gravity, enlarge, extension);
  20. assertEquals("/_PQ4ytCQMMp-1w1m_vP6g8Qb-Q7yF9mwghf6PddqxLw/fill/300/300/no/1/aHR0cDovL2ltZy5leGFtcGxlLmNvbS9wcmV0dHkvaW1hZ2UuanBn.png", urlWithHash);
  21. }
  22. public static String generateSignedUrlForImgProxy(byte[] key, byte[] salt, String url, String resize, int width, int height, String gravity, int enlarge, String extension) throws Exception {
  23. final String HMACSHA256 = "HmacSHA256";
  24. String encodedUrl = Base64.getUrlEncoder().withoutPadding().encodeToString(url.getBytes());
  25. String path = "/rs:" + resize + ":" + width + ":" + height + ":" + enlarge + "/g:" + gravity + "/" + encodedUrl + "." + extension;
  26. Mac sha256HMAC = Mac.getInstance(HMACSHA256);
  27. SecretKeySpec secretKey = new SecretKeySpec(key, HMACSHA256);
  28. sha256HMAC.init(secretKey);
  29. sha256HMAC.update(salt);
  30. String hash = Base64.getUrlEncoder().withoutPadding().encodeToString(sha256HMAC.doFinal(path.getBytes()));
  31. return "/" + hash + path;
  32. }
  33. private static byte[] hexStringToByteArray(String hex){
  34. if (hex.length() % 2 != 0)
  35. throw new IllegalArgumentException("Even-length string required");
  36. byte[] res = new byte[hex.length() / 2];
  37. for (int i = 0; i < res.length; i++) {
  38. res[i]=(byte)((Character.digit(hex.charAt(i * 2), 16) << 4) | (Character.digit(hex.charAt(i * 2 + 1), 16)));
  39. }
  40. return res;
  41. }
  42. }