Class: Nostr::Keygen

Inherits:
Object
  • Object
show all
Defined in:
lib/nostr/keygen.rb

Overview

Generates private keys, public keys and key pairs.

Instance Method Summary collapse

Constructor Details

#initializeKeygen

Instantiates a new keygen

Examples:

keygen = Nostr::Keygen.new


16
17
18
# File 'lib/nostr/keygen.rb', line 16

def initialize
  @group = ECDSA::Group::Secp256k1
end

Instance Method Details

#extract_public_key(private_key) ⇒ PublicKey

Extracts a public key from a private key

Examples:

private_key = keygen.generate_private_key
public_key = keygen.extract_public_key(private_key)
public_key # => '2d7661527d573cc8e84f665fa971dd969ba51e2526df00c149ff8e40a58f9558'

Parameters:

  • private_key (PrivateKey)

    A 32-bytes hex-encoded private key.

Returns:

  • (PublicKey)

    A 32-bytes hex-encoded public key.

Raises:

  • (ArgumentError)

    if the private key is not an instance of PrivateKey



69
70
71
72
73
# File 'lib/nostr/keygen.rb', line 69

def extract_public_key(private_key)
  validate_private_key(private_key)
  hex_value = group.generator.multiply_by_scalar(private_key.to_i(16)).x.to_s(16).rjust(64, '0')
  PublicKey.new(hex_value)
end

#generate_key_pairKeyPair

Generates a pair of private and public keys

Examples:

keypair = keygen.generate_key_pair
keypair # #<Nostr::KeyPair:0x0000000107bd3550
 @private_key="893c4cc8088924796b41dc788f7e2f746734497010b1a9f005c1faad7074b900",
 @public_key="2d7661527d573cc8e84f665fa971dd969ba51e2526df00c149ff8e40a58f9558">

Returns:

  • (KeyPair)

    An object containing a private key and a public key.



32
33
34
35
36
37
# File 'lib/nostr/keygen.rb', line 32

def generate_key_pair
  private_key = generate_private_key
  public_key  = extract_public_key(private_key)

  KeyPair.new(private_key:, public_key:)
end

#generate_private_keyPrivateKey

Generates a private key

Examples:

private_key = keygen.generate_private_key
private_key # => '893c4cc8088924796b41dc788f7e2f746734497010b1a9f005c1faad7074b900'

Returns:

  • (PrivateKey)

    A 32-bytes hex-encoded private key.



49
50
51
52
# File 'lib/nostr/keygen.rb', line 49

def generate_private_key
  hex_value = (SecureRandom.random_number(group.order - 1) + 1).to_s(16).rjust(64, '0')
  PrivateKey.new(hex_value)
end

#get_key_pair_from_private_key(private_key) ⇒ Nostr::KeyPair

Builds a key pair from an existing private key

Examples:

private_key = Nostr::PrivateKey.new('893c4cc8088924796b41dc788f7e2f746734497010b1a9f005c1faad7074b900')
keygen.get_key_pair_from_private_key(private_key)

Parameters:

  • private_key (PrivateKey)

    32-bytes hex-encoded private key.

Returns:

Raises:

  • (ArgumentError)

    if the private key is not an instance of PrivateKey



89
90
91
92
93
# File 'lib/nostr/keygen.rb', line 89

def get_key_pair_from_private_key(private_key)
  validate_private_key(private_key)
  public_key = extract_public_key(private_key)
  KeyPair.new(private_key:, public_key:)
end