Class: Sodium::SecretBox

Inherits:
Object
  • Object
show all
Includes:
Delegate
Defined in:
lib/sodium/secret_box.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Delegate

class_methods, included, #primitive

Constructor Details

#initialize(key) ⇒ SecretBox

Returns a new instance of SecretBox.



10
11
12
# File 'lib/sodium/secret_box.rb', line 10

def initialize(key)
  @key = self.class._key(key)
end

Class Method Details

.keyObject



6
7
8
# File 'lib/sodium/secret_box.rb', line 6

def self.key
  Sodium::Buffer.key self.implementation[:KEYBYTES]
end

Instance Method Details

#nonceObject



14
15
16
# File 'lib/sodium/secret_box.rb', line 14

def nonce
  Sodium::Buffer.nonce self.implementation[:NONCEBYTES]
end

#open(ciphertext, nonce) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/sodium/secret_box.rb', line 33

def open(ciphertext, nonce)
  ciphertext = self.class._ciphertext(ciphertext)
  nonce      = self.class._nonce(nonce)

  Sodium::Buffer.empty(ciphertext.bytesize) do |message|
    self.implementation.nacl_open(
      message    .to_ptr,
      ciphertext .to_ptr,
      ciphertext .bytesize,
      nonce      .to_ptr,
      @key       .to_ptr
    ) or raise Sodium::CryptoError, 'failed to open the secret box'
  end.ldrop self.implementation[:ZEROBYTES]
end

#secret_box(message, nonce) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/sodium/secret_box.rb', line 18

def secret_box(message, nonce)
  message = self.class._message(message)
  nonce   = self.class._nonce(nonce)

  Sodium::Buffer.empty(message.bytesize) do |ciphertext|
    self.implementation.nacl(
      ciphertext .to_ptr,
      message    .to_ptr,
      message    .bytesize,
      nonce      .to_ptr,
      @key       .to_ptr
    ) or raise Sodium::CryptoError, 'failed to close the secret box'
  end.ldrop self.implementation[:BOXZEROBYTES]
end