-
Notifications
You must be signed in to change notification settings - Fork 199
/
cryptoSigningParams.go
99 lines (81 loc) · 2.49 KB
/
cryptoSigningParams.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package factory
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/ElrondNetwork/elrond-go/core"
"github.com/ElrondNetwork/elrond-go/core/check"
"github.com/ElrondNetwork/elrond-go/crypto"
"github.com/ElrondNetwork/elrond-go/crypto/signing"
)
// TODO: merge this with Crypto Components
type cryptoSigningParamsLoader struct {
pubkeyConverter core.PubkeyConverter
skIndex int
skPemFileName string
suite crypto.Suite
skPkProviderHandler func() ([]byte, []byte, error)
}
// NewCryptoSigningParamsLoader returns a new instance of cryptoSigningParamsLoader
func NewCryptoSigningParamsLoader(
pubkeyConverter core.PubkeyConverter,
skIndex int,
skPemFileName string,
suite crypto.Suite,
) (*cryptoSigningParamsLoader, error) {
if check.IfNil(pubkeyConverter) {
return nil, ErrNilPubKeyConverter
}
if check.IfNil(suite) {
return nil, ErrNilSuite
}
cspf := &cryptoSigningParamsLoader{
pubkeyConverter: pubkeyConverter,
skIndex: skIndex,
skPemFileName: skPemFileName,
suite: suite,
}
cspf.skPkProviderHandler = cspf.getSkPk
return cspf, nil
}
// Get returns a key generator, a private key, and a public key
func (cspf *cryptoSigningParamsLoader) Get() (*CryptoParams, error) {
cryptoParams := &CryptoParams{}
sk, readPk, err := cspf.skPkProviderHandler()
if err != nil {
return nil, err
}
cryptoParams.KeyGenerator = signing.NewKeyGenerator(cspf.suite)
cryptoParams.PrivateKey, err = cryptoParams.KeyGenerator.PrivateKeyFromByteArray(sk)
if err != nil {
return nil, err
}
cryptoParams.PublicKey = cryptoParams.PrivateKey.GeneratePublic()
if len(readPk) > 0 {
cryptoParams.PublicKeyBytes, err = cryptoParams.PublicKey.ToByteArray()
if err != nil {
return nil, err
}
if !bytes.Equal(cryptoParams.PublicKeyBytes, readPk) {
return nil, ErrPublicKeyMismatch
}
}
cryptoParams.PublicKeyString = cspf.pubkeyConverter.Encode(cryptoParams.PublicKeyBytes)
return cryptoParams, nil
}
func (cspf *cryptoSigningParamsLoader) getSkPk() ([]byte, []byte, error) {
skIndex := cspf.skIndex
encodedSk, pkString, err := core.LoadSkPkFromPemFile(cspf.skPemFileName, skIndex)
if err != nil {
return nil, nil, err
}
skBytes, err := hex.DecodeString(string(encodedSk))
if err != nil {
return nil, nil, fmt.Errorf("%w for encoded secret key", err)
}
pkBytes, err := cspf.pubkeyConverter.Decode(pkString)
if err != nil {
return nil, nil, fmt.Errorf("%w for encoded public key %s", err, pkString)
}
return skBytes, pkBytes, nil
}