Class: Nuckle::PrivateKey

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

Overview

An X25519 (Curve25519) private key for Diffie-Hellman key agreement.

Constant Summary collapse

BYTES =

Key length in bytes.

32

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ PrivateKey

Returns a new instance of PrivateKey.

Parameters:

  • key (String)

    32-byte raw private key (binary)

Raises:

  • (ArgumentError)


19
20
21
22
23
24
25
# File 'lib/nuckle/private_key.rb', line 19

def initialize(key)
  key = key.to_s if key.respond_to?(:to_s) && !key.is_a?(String)
  key = key.b
  raise ArgumentError, "private key must be #{BYTES} bytes (got #{key.bytesize})" unless key.bytesize == BYTES

  @key = key
end

Class Method Details

.generatePrivateKey

Generates a new random private key.

Returns:



13
14
15
# File 'lib/nuckle/private_key.rb', line 13

def self.generate
  new(Random.random_bytes(BYTES))
end

Instance Method Details

#diffie_hellman(peer_public_key) ⇒ String

Raw X25519 Diffie-Hellman: scalar multiply this secret key by a peer’s public key to produce a 32-byte shared secret.

Unlike Box, this returns the raw DH output without further key derivation (no HSalsa20). Callers are responsible for deriving symmetric keys from the result (e.g. via HKDF or BLAKE3-derive-key).

Parameters:

  • peer_public_key (PublicKey, String)

    peer’s 32-byte public key

Returns:

  • (String)

    32-byte shared secret (binary)

Raises:

  • (ArgumentError)


45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/nuckle/private_key.rb', line 45

def diffie_hellman(peer_public_key)
  pk = case peer_public_key
       when PublicKey
         peer_public_key.to_s
       when String
         peer_public_key.b
       else
         raise ArgumentError, "peer_public_key must be a PublicKey or String"
       end
  raise ArgumentError, "peer public key must be 32 bytes" unless pk.bytesize == BYTES

  Internals::Curve25519.scalarmult(@key, pk)
end

#public_keyPublicKey

Derives the corresponding public key via Curve25519 scalar base multiplication.

Returns:



31
32
33
# File 'lib/nuckle/private_key.rb', line 31

def public_key
  PublicKey.new(Internals::Curve25519.scalarmult_base(@key))
end

#to_bytesString

Returns raw 32-byte key (binary).

Returns:

  • (String)

    raw 32-byte key (binary)



61
62
# File 'lib/nuckle/private_key.rb', line 61

def to_bytes = @key
# @return [String] raw 32-byte key (binary)

#to_sString

Returns raw 32-byte key (binary).

Returns:

  • (String)

    raw 32-byte key (binary)



63
# File 'lib/nuckle/private_key.rb', line 63

def to_s     = @key