Skip to content

Instantly share code, notes, and snippets.

@bruschill
Last active September 15, 2015 06:33
Show Gist options
  • Save bruschill/ea020f902fbf77297251 to your computer and use it in GitHub Desktop.
Save bruschill/ea020f902fbf77297251 to your computer and use it in GitHub Desktop.
Dwolla pin encryption in Ruby
module Dwolla
class Pin
def self.decrypt(pin, iv)
return nil unless pin.present? && iv.present?
decipher = OpenSSL::Cipher::AES256.new(:CBC)
decipher.decrypt
decipher.key = Rails.application.secrets.secret_key_base
# convert iv from utf-8 back to ascii-8bit
utf8_iv = iv
decipher.iv = Base64.decode64(utf8_iv.encode('ascii-8bit'))
# convert pin from utf-8 back to ascii-8bit
utf8_pin = pin
ascii_pin = Base64.decode64(utf8_pin.encode('ascii-8bit'))
return decipher.update(ascii_pin) + decipher.final
end
def self.encrypt(pin)
return nil unless self.is_correct_format?(pin)
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt
cipher.key = Rails.application.secrets.secret_key_base
# create iv and convert to utf-8
iv = cipher.random_iv
utf8_iv = Base64.encode64(iv).encode('utf-8')
# encrypt pin and convert to utf8
encrypted_pin = cipher.update(pin) + cipher.final
utf8_pin = Base64.encode64(encrypted_pin).encode('utf-8')
return [utf8_pin, utf8_iv]
end
def self.has_changed?(old_encrypted_pin, old_pin_iv, new_pin)
self.decrypt(old_encrypted_pin, old_pin_iv) != new_pin
end
def self.is_correct_format?(pin)
pin.match(/^\d{4}/) && pin.length == 4
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment