encrypted_source_url.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. const crypto = require('crypto');
  2. const KEY = Buffer.from(
  3. '1eb5b0e971ad7f45324c1bb15c947cb207c43152fa5c6c7f35c4f36e0c18e0f1',
  4. 'hex',
  5. )
  6. const encrypt = (target, key) => {
  7. const data = Buffer.from(target).toString('binary');
  8. // We use a random iv generation, but you'll probably want to use some
  9. // deterministic method
  10. const iv = crypto.randomBytes(16)
  11. const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  12. let encrypted = Buffer.from(
  13. cipher.update(data, 'utf8', 'binary') + cipher.final('binary'),
  14. 'binary',
  15. );
  16. return Buffer.concat([iv, encrypted]).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
  17. }
  18. const url = 'http://img.example.com/pretty/image.jpg'
  19. const encrypted_url = encrypt(url, KEY)
  20. // We don't sign the URL in this example but it is highly recommended to sign
  21. // imgproxy URLs when imgproxy is being used in production.
  22. // Signing URLs is especially important when using encrypted source URLs to
  23. // prevent a padding oracle attack
  24. const path = `/unsafe/rs:fit:300:300/enc/${encrypted_url}.jpg`
  25. console.log(path)