Class: Lockbox::Box

Inherits:
Object
  • Object
show all
Defined in:
lib/lockbox/box.rb

Instance Method Summary collapse

Constructor Details

#initialize(key, algorithm: nil) ⇒ Box

Returns a new instance of Box.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/lockbox/box.rb', line 3

def initialize(key, algorithm: nil)
  # decode hex key
  if key.encoding != Encoding::BINARY && key =~ /\A[0-9a-f]{64}\z/i
    key = [key].pack("H*")
  end

  algorithm ||= "aes-gcm"

  case algorithm
  when "aes-gcm"
    require "lockbox/aes_gcm"
    @box = AES_GCM.new(key)
  when "xchacha20"
    require "rbnacl"
    @box = RbNaCl::AEAD::XChaCha20Poly1305IETF.new(key)
  else
    raise ArgumentError, "Unknown algorithm: #{algorithm}"
  end
end

Instance Method Details

#decrypt(ciphertext, associated_data: nil) ⇒ Object



29
30
31
32
# File 'lib/lockbox/box.rb', line 29

def decrypt(ciphertext, associated_data: nil)
  nonce, ciphertext = extract_nonce(ciphertext)
  @box.decrypt(nonce, ciphertext, associated_data)
end

#encrypt(message, associated_data: nil) ⇒ Object



23
24
25
26
27
# File 'lib/lockbox/box.rb', line 23

def encrypt(message, associated_data: nil)
  nonce = generate_nonce
  ciphertext = @box.encrypt(nonce, message, associated_data)
  nonce + ciphertext
end

#inspectObject

protect key for xchacha20



35
36
37
# File 'lib/lockbox/box.rb', line 35

def inspect
  to_s
end