Created
July 30, 2018 17:59
-
-
Save egorsmkv/c20fab5cbd04c40d640ae492ff2cef01 to your computer and use it in GitHub Desktop.
Generate a signature for imgproxy. The official python script is there https://github.com/DarthSim/imgproxy/blob/de21b937db3e469e8cfcc2850f49ba9eb1eaa55d/examples/signature.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hmac | |
import hashlib | |
import base64 | |
class ImgProxy: | |
""" | |
The class generates a signature for the imgproxy (https://github.com/DarthSim/imgproxy). | |
Author: Yehor Smoliakov (https://github.com/egorsmkv) | |
""" | |
def __init__(self, key, salt): | |
self._key = bytes.fromhex(key) | |
self._salt = bytes.fromhex(salt) | |
def generate(self, url, resize, width, height, gravity, enlarge, extension): | |
b64_url = base64.urlsafe_b64encode(str.encode(url)).rstrip(b'=').decode() | |
path = f'/{resize}/{width}/{height}/{gravity}/{enlarge}/{b64_url}.{extension}' | |
sha256_hmac = hmac.new(self._key, self._salt + str.encode(path), digestmod=hashlib.sha256) | |
protection = base64.urlsafe_b64encode(sha256_hmac.digest()).rstrip(b'=').decode() | |
return f'/{protection}{path}' | |
if __name__ == '__main__': | |
test_key = 'ed7688b54dfaefecddcad524334cdf429983a11c728016f8032bb6ae033c790de5b547f819e23a2abd37fb3971e4c1323855503545a0e6b783db820c2ac18826' | |
test_salt = '5217a47ea8ad2b2e74695e8e4b344514d631e6882575f376ee59393dbd31757fe41adb2919a1e4fffd3fec9d410d34ccada8df6ac3e3d4e6b07bf73f2f2a0cad' | |
test_url = 'https://avatars3.githubusercontent.com/u/41049275?s=460&v=4' | |
test_resize = 'fill' | |
test_width = 10 | |
test_height = 10 | |
test_gravity = 'no' | |
test_enlarge = 1 | |
test_extension = 'png' | |
imp = ImgProxy(test_key, test_salt) | |
img_path = imp.generate(test_url, test_resize, test_width, test_height, test_gravity, test_enlarge, test_extension) | |
print(img_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment