/
ed25519.go
52 lines (40 loc) · 1.03 KB
/
ed25519.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package crypto
import (
"bytes"
"crypto/ed25519"
"fmt"
)
const (
ED25519_PRIVATE_KEY_PREFIX = 0xED
)
var (
ED25519_SEED_PREFIX = []byte{0x01, 0xe1, 0x4b}
)
func GenerateSeedEd25519(entropy []byte) (string, error) {
if entropy == nil {
var err error
entropy, err = GenerateEntropy()
if err != nil {
return "", err
}
}
encoded := append(ED25519_SEED_PREFIX, entropy...)
return Base58Encode(encoded, ALPHABET), nil
}
func DeriveKeypairEd25519(entropy []byte) ([]byte, []byte, error) {
if entropy == nil {
return nil, nil, fmt.Errorf("entropy is nil")
}
if len(entropy) != ENTROPY_LENGTH {
return nil, nil, fmt.Errorf("entropy length is not correct")
}
r := bytes.NewReader(Sha512Half(entropy))
// publicKey is the same as privateKey[32:]
publicKey, privateKey, err := ed25519.GenerateKey(r)
if err != nil {
return nil, nil, err
}
publicKey = append([]byte{ED25519_PRIVATE_KEY_PREFIX}, publicKey...)
privateKey = append([]byte{ED25519_PRIVATE_KEY_PREFIX}, privateKey[:32]...)
return publicKey, privateKey, nil
}