Total Lines | 58 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | package crypto |
||
2 | |||
3 | import ( |
||
4 | "crypto/rand" |
||
5 | "io" |
||
6 | "sync" |
||
7 | |||
8 | "github.com/pkg/errors" |
||
9 | "golang.org/x/crypto/ed25519" |
||
10 | ) |
||
11 | |||
12 | type KeyManager struct { |
||
13 | seed io.Reader |
||
14 | privateKey ed25519.PrivateKey |
||
15 | publicKey ed25519.PublicKey |
||
16 | } |
||
17 | |||
18 | var ( |
||
19 | keyManagerInstance *KeyManager //nolint:gochecknoglobals //Singleton |
||
20 | keyManagerOnce sync.Once //nolint:gochecknoglobals //Singleton |
||
21 | ) |
||
22 | |||
23 | func GetKeyManagerInstance() *KeyManager { |
||
24 | keyManagerOnce.Do(func() { |
||
25 | keyManagerInstance = &KeyManager{ |
||
26 | seed: rand.Reader, |
||
27 | } |
||
28 | }) |
||
29 | return keyManagerInstance |
||
30 | } |
||
31 | |||
32 | func (k *KeyManager) GetPrivateKey() ed25519.PrivateKey { |
||
33 | return k.privateKey |
||
34 | } |
||
35 | |||
36 | func (k *KeyManager) GetPublicKey() ed25519.PublicKey { |
||
37 | return k.publicKey |
||
38 | } |
||
39 | |||
40 | func (k *KeyManager) ParseEd25519Key() error { |
||
41 | publicKey, privateKey, err := GenerateKeyPair() |
||
42 | if err != nil { |
||
43 | return err |
||
44 | } |
||
45 | |||
46 | k.privateKey = privateKey |
||
47 | k.publicKey = publicKey |
||
48 | |||
49 | return nil |
||
50 | } |
||
51 | |||
52 | func GenerateKeyPair() (ed25519.PublicKey, ed25519.PrivateKey, error) { |
||
53 | publicKey, privateKey, err := ed25519.GenerateKey(GetKeyManagerInstance().seed) |
||
54 | if err != nil { |
||
55 | return nil, nil, errors.Wrap(err, "Error generating keys") |
||
56 | } |
||
57 | |||
58 | return publicKey, privateKey, nil |
||
59 | } |
||
60 |