Class: Crypto::Keys::KeyUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/crypto/keys/key_utils.rb

Class Method Summary collapse

Class Method Details

.create_new_keypairObject



17
18
19
20
21
22
23
24
25
# File 'lib/crypto/keys/key_utils.rb', line 17

def self.create_new_keypair
    signing_key = Ed25519::SigningKey.generate
    private_key = signing_key.keypair.unpack("H*").first[0..63]
    public_key = signing_key.keypair.unpack("H*").first[64..-1]
    {
        hex_private_key: private_key,
        hex_public_key: public_key
    }
end

.from_wif(wif) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/crypto/keys/key_utils.rb', line 52

def self.from_wif(wif)
    decoded_wif = Base64.strict_decode64(wif.as_hex)
    network_prefix = decoded_wif[0..1]
    network = network_prefix == "M0" ? MAINNET : TESTNET
    private_key_hex = decoded_wif[2..-7]
    private_key = PrivateKey.from_hex(private_key_hex)
    {private_key: private_key, network: network}
end

.get_address_from_public_key(public_key) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/crypto/keys/key_utils.rb', line 35

def self.get_address_from_public_key(public_key)
    hashed_address = Crypto::Hashes.ripemd160(Crypto::Hashes.sha256(public_key.as_hex))
    network_address = public_key.network[:prefix] + hashed_address
    hashed_address_again = Crypto::Hashes.sha256(Crypto::Hashes.sha256(network_address))
    checksum = hashed_address_again[0..5]
    Base64.strict_encode64(network_address + checksum)
end

.sign(hex_private_key, message) ⇒ Object



12
13
14
15
# File 'lib/crypto/keys/key_utils.rb', line 12

def self.sign(hex_private_key, message)
    signing_key = Ed25519::SigningKey.new([hex_private_key].pack("H*"))
    signing_key.sign(message).unpack("H*").first
end

.to_bytes(hex) ⇒ Object



31
32
33
# File 'lib/crypto/keys/key_utils.rb', line 31

def self.to_bytes(hex)
    [hex].pack('H*').bytes.to_a
end

.to_hex(bytes) ⇒ Object



27
28
29
# File 'lib/crypto/keys/key_utils.rb', line 27

def self.to_hex(bytes)
    bytes.pack("c*").unpack("H*").first
end

.to_wif(key, network) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/crypto/keys/key_utils.rb', line 43

def self.to_wif(key, network)
    private_key = key.as_hex
    network_key = network[:prefix] + private_key
    hashed_key = Crypto::Hashes.sha256(Crypto::Hashes.sha256(network_key))
    checksum = hashed_key[0..5]
    encoded_key = Base64.strict_encode64(network_key + checksum)
    Wif.new(encoded_key)
end

.verify_signature(message, signature_hex, hex_public_key) ⇒ Object



3
4
5
6
7
8
9
10
# File 'lib/crypto/keys/key_utils.rb', line 3

def self.verify_signature(message, signature_hex, hex_public_key)
    begin
    verify_key = Ed25519::VerifyKey.new([hex_public_key].pack("H*"))
    verify_key.verify([signature_hex].pack("H*"), message)
    rescue => e
        raise AxentroError, "Verify fail: #{e.message}"
    end
end