Class: Slosilo::Symmetric
- Inherits:
-
Object
- Object
- Slosilo::Symmetric
- Defined in:
- lib/slosilo/symmetric.rb
Constant Summary collapse
- VERSION_MAGIC =
'G'
- TAG_LENGTH =
16
Instance Method Summary collapse
-
#cipher_name ⇒ Object
This lets us do a final sanity check in migrations from older encryption versions.
- #decrypt(ciphertext, opts = {}) ⇒ Object
- #encrypt(plaintext, opts = {}) ⇒ Object
-
#initialize ⇒ Symmetric
constructor
A new instance of Symmetric.
- #random_iv ⇒ Object
- #random_key ⇒ Object
Constructor Details
#initialize ⇒ Symmetric
Returns a new instance of Symmetric.
6 7 8 |
# File 'lib/slosilo/symmetric.rb', line 6 def initialize @cipher = OpenSSL::Cipher.new 'aes-256-gcm' # NB: has to be lower case for whatever reason. end |
Instance Method Details
#cipher_name ⇒ Object
This lets us do a final sanity check in migrations from older encryption versions
11 12 13 |
# File 'lib/slosilo/symmetric.rb', line 11 def cipher_name @cipher.name end |
#decrypt(ciphertext, opts = {}) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/slosilo/symmetric.rb', line 26 def decrypt ciphertext, opts = {} version, tag, iv, ctext = unpack ciphertext raise "Invalid version magic: expected #{VERSION_MAGIC} but was #{version}" unless version == VERSION_MAGIC @cipher.reset @cipher.decrypt @cipher.key = opts[:key] @cipher.iv = iv @cipher.auth_tag = tag @cipher.auth_data = opts[:aad] || "" @cipher.update(ctext) + @cipher.final end |
#encrypt(plaintext, opts = {}) ⇒ Object
15 16 17 18 19 20 21 22 23 24 |
# File 'lib/slosilo/symmetric.rb', line 15 def encrypt plaintext, opts = {} @cipher.reset @cipher.encrypt @cipher.key = (opts[:key] or raise("missing :key option")) @cipher.iv = iv = random_iv @cipher.auth_data = opts[:aad] || "" # Nothing good happens if you set this to nil, or don't set it at all ctext = @cipher.update(plaintext) + @cipher.final tag = @cipher.auth_tag(TAG_LENGTH) "#{VERSION_MAGIC}#{tag}#{iv}#{ctext}" end |
#random_iv ⇒ Object
40 41 42 |
# File 'lib/slosilo/symmetric.rb', line 40 def random_iv @cipher.random_iv end |
#random_key ⇒ Object
44 45 46 |
# File 'lib/slosilo/symmetric.rb', line 44 def random_key @cipher.random_key end |