Sha256: db9a1b04516f5c37a09637a6ddac02463a05b78b4e9f7a526694fac188a64152

Contents?: true

Size: 918 Bytes

Versions: 1

Compression:

Stored size: 918 Bytes

Contents

require 'openssl'
require 'digest/sha2'
require 'base64'

module ActiveUrl
  module Crypto
    PADDING = { 2 => "==", 3 => "=" }
 
    def self.encrypt(clear)
      crypto = start(:encrypt)
      cipher = crypto.update(clear)
      cipher << crypto.final
      Base64.encode64(cipher).gsub(/[\s=]+/, "").gsub("+", "-").gsub("/", "_")
    end
 
    def self.decrypt(b64)
      cipher = Base64.decode64("#{b64.gsub("-", "+").gsub("_", "/")}#{PADDING[b64.length % 4]}")
      crypto = start(:decrypt)
      clear = crypto.update(cipher)
      clear << crypto.final
    end
 
    private
 
    def self.start(mode)
      raise ::ArgumentError.new("Set a secret key using ActiveUrl.config.secret = 'your-secret'") if ActiveUrl.config.secret.blank?
      crypto = OpenSSL::Cipher::Cipher.new('aes-256-ecb').send(mode)
      crypto.key = Digest::SHA256.hexdigest(ActiveUrl.config.secret)
      return crypto
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mholling-active_url-0.1.1 lib/active_url/crypto.rb