encrypted_source_url.rb 827 B

12345678910111213141516171819202122232425
  1. require "openssl"
  2. require "base64"
  3. key = ["1eb5b0e971ad7f45324c1bb15c947cb207c43152fa5c6c7f35c4f36e0c18e0f1"].pack("H*")
  4. url = "http://img.example.com/pretty/image.jpg"
  5. # The key is 32 bytes long, so we use AES-256-CBC
  6. cipher = OpenSSL::Cipher::AES.new(256, :CBC)
  7. cipher.encrypt
  8. # We use a random iv generation, but you'll probably want to use some
  9. # deterministic method
  10. iv = cipher.random_iv
  11. cipher.key = key
  12. cipher.iv = iv
  13. encrypted_url = Base64.urlsafe_encode64(iv + cipher.update(url) + cipher.final).tr("=", "")
  14. # We don't sign the URL in this example but it is highly recommended to sign
  15. # imgproxy URLs when imgproxy is being used in production.
  16. # Signing URLs is especially important when using encrypted source URLs to
  17. # prevent a padding oracle attack
  18. path = "/unsafe/rs:fit:300:300/enc/#{encrypted_url}.jpg"