Class: Synthra::Types::Crypto::PrivateKey

Inherits:
Base
  • Object
show all
Defined in:
lib/synthra/types/crypto/crypto.rb

Overview

PrivateKey type

Constant Summary collapse

BASE58_CHARS =

Base58 characters for WIF format

"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".freeze

Instance Method Summary collapse

Instance Method Details

#generate_base58_string(rng, length) ⇒ Object (private)



115
116
117
# File 'lib/synthra/types/crypto/crypto.rb', line 115

def generate_base58_string(rng, length)
  length.times.map { rng.sample(BASE58_CHARS.chars) }.join
end

#generate_base64_string(rng, length) ⇒ Object (private)



119
120
121
122
# File 'lib/synthra/types/crypto/crypto.rb', line 119

def generate_base64_string(rng, length)
  chars = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['+', '/', '=']
  length.times.map { rng.sample(chars) }.join
end

#generate_edge(rng, context, args) ⇒ Object



105
106
107
# File 'lib/synthra/types/crypto/crypto.rb', line 105

def generate_edge(rng, context, args)
  ["0" * 64, "f" * 64].sample(random: rng.instance_variable_get(:@random))
end

#generate_invalid(rng, context, args) ⇒ Object



109
110
111
# File 'lib/synthra/types/crypto/crypto.rb', line 109

def generate_invalid(rng, context, args)
  [nil, "not a key", "invalid", [], {}].sample(random: rng.instance_variable_get(:@random))
end

#generate_random(rng, context, args) ⇒ String

Generate random private key

Parameters:

Options Hash (args):

  • :format (Symbol)

    key format (:hex, :wif, :pem)

  • :length (Integer)

    key length in bytes (default: 32)

Returns:

  • (String)

    generated private key



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/synthra/types/crypto/crypto.rb', line 87

def generate_random(rng, context, args)
  format_type = args[:format] || :hex
  length = args[:length] || 32

  case format_type
  when :wif
    # WIF (Wallet Import Format) for Bitcoin: Base58 encoded
    "5" + generate_base58_string(rng, 51)
  when :pem
    # PEM format (simplified)
    "-----BEGIN PRIVATE KEY-----\n" + generate_base64_string(rng, length * 2) + "\n-----END PRIVATE KEY-----"
  else # :hex
    # Hex format: 64 hex characters (32 bytes)
    hex_chars = ("0".."9").to_a + ("a".."f").to_a
    (length * 2).times.map { rng.sample(hex_chars) }.join
  end
end