Module: Clavis::Security::TokenStorage
- Defined in:
- lib/clavis/security/token_storage.rb
Defined Under Namespace
Classes: Serializer
Class Method Summary collapse
-
.active_record_serializer ⇒ Object
Returns a serializer for use with ActiveRecord::Encryption This allows tokens to be automatically encrypted when stored in the database.
-
.decrypt(encrypted_token) ⇒ String, Hash
Decrypts a token if encryption is enabled in configuration.
-
.encrypt(token) ⇒ String, Hash
Encrypts a token if encryption is enabled in configuration.
Class Method Details
.active_record_serializer ⇒ Object
Returns a serializer for use with ActiveRecord::Encryption This allows tokens to be automatically encrypted when stored in the database
72 73 74 |
# File 'lib/clavis/security/token_storage.rb', line 72 def active_record_serializer Serializer.new end |
.decrypt(encrypted_token) ⇒ String, Hash
Decrypts a token if encryption is enabled in configuration
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/clavis/security/token_storage.rb', line 36 def decrypt(encrypted_token) return encrypted_token unless Clavis.configuration.encrypt_tokens return encrypted_token if encrypted_token.nil? key = Clavis.configuration.effective_encryption_key return encrypted_token if key.nil? begin decoded = Base64.strict_decode64(encrypted_token) iv_b64, data_b64 = decoded.split("--", 2) iv = Base64.strict_decode64(iv_b64) data = Base64.strict_decode64(data_b64) decipher = OpenSSL::Cipher.new("AES-256-CBC") decipher.decrypt decipher.key = normalize_key(key) decipher.iv = iv decrypted = decipher.update(data) + decipher.final # Try to parse as JSON in case it's a hash begin JSON.parse(decrypted, symbolize_names: true) rescue JSON::ParserError decrypted end rescue StandardError => e Clavis.logger.error("Failed to decrypt token: #{e.message}") encrypted_token end end |
.encrypt(token) ⇒ String, Hash
Encrypts a token if encryption is enabled in configuration
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/clavis/security/token_storage.rb', line 14 def encrypt(token) return token unless Clavis.configuration.encrypt_tokens return token if token.nil? key = Clavis.configuration.effective_encryption_key return token if key.nil? # Convert hash to JSON string if token is a hash token_str = token.is_a?(Hash) ? JSON.generate(token) : token.to_s cipher = OpenSSL::Cipher.new("AES-256-CBC") cipher.encrypt cipher.key = normalize_key(key) iv = cipher.random_iv encrypted = cipher.update(token_str) + cipher.final Base64.strict_encode64("#{Base64.strict_encode64(iv)}--#{Base64.strict_encode64(encrypted)}") end |