Class: Itamae::Secrets::Encryptor
- Inherits:
-
Object
- Object
- Itamae::Secrets::Encryptor
- Defined in:
- lib/itamae/secrets/encryptor.rb
Constant Summary collapse
- ALGORITHM =
'aes-256-gcm'
Instance Attribute Summary collapse
-
#key ⇒ Object
Returns the value of attribute key.
-
#plaintext ⇒ Object
readonly
Returns the value of attribute plaintext.
Instance Method Summary collapse
- #algorithm ⇒ Object
- #auth_tag ⇒ Object
- #cipher ⇒ Object
- #ciphertext ⇒ Object
-
#initialize(plaintext, key = nil, iv = nil) ⇒ Encryptor
constructor
A new instance of Encryptor.
- #iv ⇒ Object
- #to_s ⇒ Object (also: #data)
- #version ⇒ Object
Constructor Details
#initialize(plaintext, key = nil, iv = nil) ⇒ Encryptor
Returns a new instance of Encryptor.
8 9 10 11 12 13 |
# File 'lib/itamae/secrets/encryptor.rb', line 8 def initialize(plaintext, key = nil, iv = nil) ensure_algorithm_key_compatiblity!(key) if key @key = key @iv = iv @plaintext = plaintext end |
Instance Attribute Details
#key ⇒ Object
Returns the value of attribute key.
15 16 17 |
# File 'lib/itamae/secrets/encryptor.rb', line 15 def key @key end |
#plaintext ⇒ Object (readonly)
Returns the value of attribute plaintext.
15 16 17 |
# File 'lib/itamae/secrets/encryptor.rb', line 15 def plaintext @plaintext end |
Instance Method Details
#algorithm ⇒ Object
61 62 63 |
# File 'lib/itamae/secrets/encryptor.rb', line 61 def algorithm ALGORITHM end |
#auth_tag ⇒ Object
49 50 51 52 53 54 55 |
# File 'lib/itamae/secrets/encryptor.rb', line 49 def auth_tag if @auth_tag [@auth_tag].pack('m*') else raise '[BUG] auth_tag not exists' end end |
#cipher ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/itamae/secrets/encryptor.rb', line 65 def cipher @cipher ||= OpenSSL::Cipher.new(algorithm).tap do |c| raise 'key is required to proceed' unless key c.encrypt c.key = key.to_s # XXX: avoid generate IV here, but consider if extract to a method like #iv, it have to know Cipher#iv_len... @iv ||= c.random_iv c.iv = @iv c.auth_data = '' end end |
#ciphertext ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/itamae/secrets/encryptor.rb', line 36 def ciphertext @ciphertext ||= begin data = cipher.update(plaintext) data << cipher.final @auth_tag = cipher.auth_tag [data].pack('m*') end end |
#iv ⇒ Object
45 46 47 |
# File 'lib/itamae/secrets/encryptor.rb', line 45 def iv @iv && [@iv].pack('m*') end |
#to_s ⇒ Object Also known as: data
23 24 25 26 27 28 29 30 31 32 |
# File 'lib/itamae/secrets/encryptor.rb', line 23 def to_s { version: version, algorithm: algorithm, key_name: key.name, ciphertext: ciphertext, iv: iv, auth_tag: auth_tag, }.to_json end |
#version ⇒ Object
57 58 59 |
# File 'lib/itamae/secrets/encryptor.rb', line 57 def version 1 end |