signature.js 1010 B

12345678910111213141516171819202122232425262728293031
  1. const crypto = require('crypto')
  2. const KEY = '943b421c9eb07c830af81030552c86009268de4e532ba2ee2eab8247c6da0881'
  3. const SALT = '520f986b998545b4785e0defbc4f3c1203f22de2374a3d53cb7a7fe9fea309c5'
  4. const urlSafeBase64 = (string) => {
  5. return new Buffer(string).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
  6. }
  7. const hexDecode = (hex) => Buffer.from(hex, 'hex')
  8. const sign = (salt, target, secret) => {
  9. const hmac = crypto.createHmac('sha256', hexDecode(secret))
  10. hmac.update(hexDecode(salt))
  11. hmac.update(target)
  12. return urlSafeBase64(hmac.digest())
  13. }
  14. const url = 'http://img.example.com/pretty/image.jpg'
  15. const resizing_type = 'fill'
  16. const width = 300
  17. const height = 300
  18. const gravity = 'no'
  19. const enlarge = 1
  20. const extension = 'png'
  21. const encoded_url = urlSafeBase64(url)
  22. const path = `/${resizing_type}/${width}/${height}/${gravity}/${enlarge}/${encoded_url}.${extension}`
  23. const signature = sign(SALT, path, KEY)
  24. const result = `/${signature}${path}`
  25. console.log(result)