Sha256: 6d8e4098e79d4df560d72938ae16fd035681484d38df0d4d6300c0595b1942fb

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

require 'active_support/message_encryptor'
require 'active_support/message_verifier'
require 'active_support/key_generator'

module Vinz
  class Crypto
    def initialize(key)
      _key = ActiveSupport::KeyGenerator.new(key).generate_key(key, 32)
      @crypt = ActiveSupport::MessageEncryptor.new(_key)
    end

    def encrypt(message)
      @crypt.encrypt_and_sign(message)
    end

    def decrypt(message)
      @crypt.decrypt_and_verify(message)
    rescue ActiveSupport::MessageVerifier::InvalidSignature => ignore
      raise Vinz::Error.new('invalid signature')
    rescue ActiveSupport::MessageEncryptor::InvalidMessage => ignore
      raise Vinz::Error.new('invalid message')
    end

    def encode(message)
      encrypted = encrypt(message)
      Base64.urlsafe_encode64(encrypted)
    end

    def decode(message)
      decoded64 = Base64.urlsafe_decode64(message)
      decrypt(decoded64)
    rescue ArgumentError => ignore
      raise Vinz::Error.new('invalid encoding')
    rescue NoMethodError => ignore
      raise Vinz::Error.new('invalid message')
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
vinz-1.1.7 lib/vinz/crypto.rb