diff --git a/app/models/aes_crypt.rb b/app/models/aes_crypt.rb new file mode 100644 index 00000000..8eeb6ee1 --- /dev/null +++ b/app/models/aes_crypt.rb @@ -0,0 +1,38 @@ +class AesCrypt + @cipher = "" + + def initialize + @cipher = OpenSSL::Cipher::Cipher.new(ENV["cipher_type"]) + end + + private + def export_key(passphrase) + # We want a 256 bit key symetric key based on passphrase + digest = Digest::SHA256.new + key = digest.update(passphrase) + # key = digest.digest + ENV['aes_key'] = @cipher.key = key # stores the key in key, and also sets the generated key on the @cipher + ENV['aes_iv'] = @cipher.iv = @cipher.random_iv # stores the iv in iv, and also sets the generated iv on the @cipher + return @cipher.key, @cipher.iv + end + + def encrypt(data) + cipher.encrypt + cipher.key = ENV["aes_key"] + cipher.iv = ENV["aes_iv"] + encrypted = cipher.update(data) + cipher.final + encrypted = Base64.encode64(encrypted) + return encrypted + end + + def decrypt(data) + cipher.decrypt + cipher.key = ENV["aes_key"] + cipher.iv = ENV["aes_iv"] + + # Start the decryption + decoded = Base64.decode64(data) + decrypted = cipher.update(decoded) + cipher.final + return decrypted + end +end \ No newline at end of file