Class: ED25519

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

Class Method Summary collapse

Class Method Details

.get_public_key_from_seed(seed) ⇒ String

Get ED25519 public key

Examples:

seed = "0xfac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e"
public_key = ED25519.get_public_key_from_seed(seed)

Parameters:

  • seed (String)

    private key

Returns:

  • (String)

    public key


72
73
74
75
# File 'lib/ed25519_lib.rb', line 72

def self.get_public_key_from_seed(seed)
  signing_key = self.keypair_from_seed(seed)
  return signing_key.verify_key.to_bytes.unpack1('H*')
end

.keypair_from_seed(seed) ⇒ Class

Generate ED25519 keypair

Examples:

seed = "0xfac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e"
keypair = ED25519.keypair_from_seed(seed)

Parameters:

  • seed (String)

    private key

Returns:

  • (Class)

    ED25519 keypair


55
56
57
58
59
60
61
62
# File 'lib/ed25519_lib.rb', line 55

def self.keypair_from_seed(seed)
  if seed.start_with?("0x")
    seed = seed.sub(/0x/, "")
  end
  seed = "".tap { |binary| seed.scan(/../) { |hn| binary << hn.to_i(16).chr } }
  signing_key = Ed25519::SigningKey.new(seed)
  return signing_key
end

.sign(message, key_pair) ⇒ String

Sign the given message

Examples:

message = "Hello world"
seed = "0xfac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e"
keypair = ED25519.keypair_from_seed(seed)
signature_result = ED25519.sign(message, keypair)

Parameters:

  • message (String)

    the message

  • key_pair (Class)

    ED25519 keypair

Returns:

  • (String)

    sign result as a hex string


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

def self.sign(message, key_pair)
  "0x" + key_pair.sign(message).unpack1("H*")
end

.verify(address, message, signature_result) ⇒ String

Verify the sign result

Examples:

message = "Hello world"
seed = "0xfac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e"
public_key = ED25519.get_public_key_from_seed(seed)
address = Address.encode(public_key)
keypair = ED25519.keypair_from_seed(seed)
signature_result = ED25519.sign(message, keypair)
verify_result = ED25519.verify(address, message, signature_result)

Parameters:

  • message (String)

    the message

  • key_pair (Class)

    ED25519 keypair

Returns:

  • (String)

    sign result as a hex string


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

def self.verify(address, message, signature_result)
  if signature_result.start_with?("0x")
    signature_result = signature_result.sub(/0x/, "")
  end
  signature = [signature_result].pack("H*")
  public_key = Address.decode(address)
  verify_key_bytes = [public_key].pack("H*")
  verify_key  = Ed25519::VerifyKey.new(verify_key_bytes)
  begin
    verify_key.verify(signature, message)
  rescue
    return false
  end
end