skill-assessment-app/app/services/crypt_serializer.rb
Mark Moser 4bbd93ded1 rubocop noise: fixes FrozenStringLiteralComment
Adding the .ruby-verison file triggered previously un-run cops, specifically:

  This cop is designed to help upgrade to Ruby 3.0. It will add the
  comment `# frozen_string_literal: true` to the top of files to enable
  frozen string literals. Frozen string literals will be default in Ruby
  3.0. The comment will be added below a shebang and encoding comment. The
  frozen string literal comment is only valid in Ruby 2.3+.

More info on rubocop [Automatic-Corrections](https://github.com/bbatsov/rubocop/wiki/Automatic-Corrections)
2016-09-08 10:30:13 -05:00

48 lines
976 B
Ruby

# frozen_string_literal: true
require 'openssl'
require 'base64'
class CryptSerializer
attr_reader :cipher
class << self
# pulling from DB - return plain value
def load value
new.decrypt value
end
# saving to DB - return encrypted value
def dump value
new.encrypt value
end
end
def initialize
@cipher = OpenSSL::Cipher::AES.new(128, :CBC)
end
def encrypt(value)
unless value.is_a?(String)
raise "Attribute was supposed to be a `String`, but was instead a `#{value.class}`"
end
return value if value.nil?
cipher.encrypt
parts = [cipher.random_key, cipher.random_iv, cipher.update(value) + cipher.final]
Base64.urlsafe_encode64 Marshal.dump(parts)
end
def decrypt(value)
return value if value.nil?
parts = Marshal.load Base64.urlsafe_decode64(value)
cipher.decrypt
cipher.key = parts[0]
cipher.iv = parts[1]
cipher.update(parts[2]) + cipher.final
end
end