Skip to content
This repository has been archived by the owner on Apr 7, 2021. It is now read-only.

Generating Signed Image URLs

Vamsi Krishna B edited this page Oct 8, 2015 · 5 revisions

Ruby Example

You might like the camo gem, or you might like adding something like the following class directly to your application.

require "openssl"

# Rewrites image URLs to a camo proxy endpoint but only if CAMO_HOST and
# CAMO_KEY environment variables are configured and only if the source URL is
# non-SSL.
#
# Example:
#
#     ENV["CAMO_HOST"] #=> "https://camo.example.com"
#     ENV["CAMO_KEY"]  #=> "0x24FEEDFACEDEADBEEFCAFE"
#
#     Camo.new("http://example.com/octocat.jpg").rewrite # Note http
#     # => "https://camo.example.com/b9f45c9f94e3b15fecae2bf9a8b497fc7280fd29/687474703a2f2f6578616d706c652e636f6d2f6f63746f6361742e6a7067"
#
#     Camo.new("https://example.com/octocat.jpg").rewrite # Note https
#     # => "https://example.com/octocat.jpg"
class Camo
  def initialize(link)
    @link = link
  end

  def rewrite
    if configured? && !ssl_link?
      "#{host}/#{hex_digest}/#{hex_encode}"
    else
      @link
    end
  end

  def configured?
    host.present? && key.present?
  end

  private

  def host
    ENV["CAMO_HOST"]
  end

  def key
    ENV["CAMO_KEY"]
  end

  def ssl_link?
    @link =~ /^https/
  end

  def hex_digest
    OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"), key, @link)
  end

  def hex_encode
    @link.to_enum(:each_byte).map { |byte| "%02x" % byte }.join
  end
end

PHP Example

<?php
class Camo 
{
	private $url;
	private $key;
	private $host;

	public function __construct($url,$key = '2a0953c62678888',$host='https://examplecamo.herokuapp.com')
	{
		$this->url = $url;
		$this->key = $key;
		$this->host = $host;
	}

	private function proxy_url()
	{
		$digest = hash_hmac('sha1', $this->url, $this->key);
		$hex_url = bin2hex($this->url);
		return $this->host.'/'.$digest.'/'."$hex_url";
	}

	public function __toString()
	{
		return $this->proxy_url();
	}
}

$camo = new Camo('http://i.imgur.com/eQ5fvKW.png');
echo $camo;
Clone this wiki locally