Class: Nuckle::Box

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

Overview

Public-key authenticated encryption: Curve25519-XSalsa20-Poly1305.

Compatible with NaCl crypto_box / libsodium crypto_box_curve25519xsalsa20poly1305.

Constant Summary collapse

NONCEBYTES =
24
PUBLICKEYBYTES =
32
PRIVATEKEYBYTES =
32
BEFORENMBYTES =
32
MACBYTES =
16

Instance Method Summary collapse

Constructor Details

#initialize(public_key, private_key) ⇒ Box

Returns a new instance of Box.

Parameters:

  • public_key (PublicKey, String)

    peer’s 32-byte public key

  • private_key (PrivateKey, String)

    own 32-byte private key



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/nuckle/box.rb', line 18

def initialize(public_key, private_key)
  pk = extract_bytes(public_key, PUBLICKEYBYTES, "public key")
  sk = extract_bytes(private_key, PRIVATEKEYBYTES, "private key")

  # Compute shared secret via Curve25519 DH
  shared = Internals::Curve25519.scalarmult(sk, pk)

  # Derive symmetric key via HSalsa20 (the "beforenm" step)
  key = Internals::Salsa20.hsalsa20(shared, "\x00" * 16)

  @secret_box = SecretBox.new(key)
end

Instance Method Details

#decrypt(nonce, ciphertext) ⇒ Object Also known as: open

Decrypt ciphertext with 24-byte nonce.



42
43
44
# File 'lib/nuckle/box.rb', line 42

def decrypt(nonce, ciphertext)
  @secret_box.decrypt(nonce, ciphertext)
end

#encrypt(nonce, plaintext) ⇒ Object Also known as: box

Encrypt plaintext with 24-byte nonce.



36
37
38
# File 'lib/nuckle/box.rb', line 36

def encrypt(nonce, plaintext)
  @secret_box.encrypt(nonce, plaintext)
end

#nonce_bytesInteger

Returns required nonce length in bytes.

Returns:

  • (Integer)

    required nonce length in bytes



33
# File 'lib/nuckle/box.rb', line 33

def nonce_bytes = NONCEBYTES