Module: Kidsmin::Encryption
- Defined in:
- lib/kidsmin/encryption.rb
Constant Summary collapse
- ALGORITHM =
"aes-256-gcm"- IV_LENGTH =
12- TAG_LENGTH =
16
Class Method Summary collapse
Class Method Details
.decrypt(encoded) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/kidsmin/encryption.rb', line 26 def self.decrypt(encoded) return nil if encoded.nil? raw = Base64.strict_decode64(encoded) iv = raw[0, IV_LENGTH] tag = raw[IV_LENGTH, TAG_LENGTH] ciphertext = raw[(IV_LENGTH + TAG_LENGTH)..] cipher = OpenSSL::Cipher.new(ALGORITHM) cipher.decrypt cipher.key = key_bytes cipher.iv = iv cipher.auth_tag = tag cipher.update(ciphertext) + cipher.final rescue OpenSSL::Cipher::CipherError nil end |
.encrypt(plaintext) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/kidsmin/encryption.rb', line 10 def self.encrypt(plaintext) return nil if plaintext.nil? key = key_bytes iv = OpenSSL::Random.random_bytes(IV_LENGTH) cipher = OpenSSL::Cipher.new(ALGORITHM) cipher.encrypt cipher.key = key cipher.iv = iv ciphertext = cipher.update(plaintext) + cipher.final tag = cipher.auth_tag(TAG_LENGTH) Base64.strict_encode64(iv + tag + ciphertext) end |