class Culqi::Encryptor

Public Class Methods

new() click to toggle source
# File lib/culqi/encryptor.rb, line 6
def initialize
  raise 'Invalid Culqi Key' unless resembles_base64(ENV['CULQI_KEY'])
  @key = Base64.urlsafe_decode64(ENV['CULQI_KEY'])
end

Public Instance Methods

decrypt(encrypted) click to toggle source
# File lib/culqi/encryptor.rb, line 19
def decrypt(encrypted)
  decoded     = Base64.urlsafe_decode64(encrypted)
  decipher    = build_cipher(:decrypt)
  decipher.iv = decoded.slice!(0, 16)

  decrypted_text = decipher.update(decoded) + decipher.final
  decrypted_text.force_encoding('utf-8')
end
encrypt(plaintext) click to toggle source
# File lib/culqi/encryptor.rb, line 11
def encrypt(plaintext)
  cipher    = build_cipher(:encrypt)
  cipher.iv = iv = cipher.random_iv
  decoded   = iv + cipher.update(plaintext) + cipher.final

  Base64.urlsafe_encode64(decoded)
end

Private Instance Methods

build_cipher(type) click to toggle source
# File lib/culqi/encryptor.rb, line 30
def build_cipher(type)
  cipher = OpenSSL::Cipher::AES.new(256, :CBC)
  cipher.send(type)
  cipher.key = @key
  cipher
end
resembles_base64(mystring) click to toggle source
# File lib/culqi/encryptor.rb, line 37
def resembles_base64(mystring)
  mystring.length % 4 == 0 && mystring =~ /^[A-Za-z0-9+\/=]+\Z/
end