-
Notifications
You must be signed in to change notification settings - Fork 38
/
shared_secret_service.go
71 lines (58 loc) · 2.04 KB
/
shared_secret_service.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
package crypto
import (
"fmt"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
gethlog "github.com/ethereum/go-ethereum/log"
"github.com/ten-protocol/go-ten/go/common"
"github.com/ten-protocol/go-ten/go/common/log"
)
const (
sharedSecretLenInBytes = 32
)
// SharedEnclaveSecret - the entropy
type SharedEnclaveSecret [sharedSecretLenInBytes]byte
// SharedSecretService provides functionality to encapsulate, generate, extend, and encrypt the shared secret of the TEN network.
type SharedSecretService struct {
secret *SharedEnclaveSecret
logger gethlog.Logger
}
func NewSharedSecretService(logger gethlog.Logger) *SharedSecretService {
return &SharedSecretService{logger: logger}
}
// GenerateSharedSecret - called only by the genesis
func (sss *SharedSecretService) GenerateSharedSecret() {
secret, err := generateSecureEntropy(sharedSecretLenInBytes)
if err != nil {
sss.logger.Crit("could not generate secret", log.ErrKey, err)
}
var tempSecret SharedEnclaveSecret
copy(tempSecret[:], secret)
sss.secret = &tempSecret
}
// Secret - should only be used before storing it
func (sss *SharedSecretService) Secret() *SharedEnclaveSecret {
return sss.secret
}
func (sss *SharedSecretService) SetSharedSecret(ss *SharedEnclaveSecret) {
sss.secret = ss
}
// ExtendEntropy derives more entropy from the shared secret
func (sss *SharedSecretService) ExtendEntropy(extra []byte) []byte {
return crypto.Keccak256(sss.secret[:], extra)
}
func (sss *SharedSecretService) EncryptSecretWithKey(pubKey []byte) (common.EncryptedSharedEnclaveSecret, error) {
sss.logger.Info(fmt.Sprintf("Encrypting secret with public key %s", gethcommon.Bytes2Hex(pubKey)))
key, err := crypto.DecompressPubkey(pubKey)
if err != nil {
return nil, fmt.Errorf("failed to parse public key %w", err)
}
encKey, err := encryptWithPublicKey(sss.secret[:], key)
if err != nil {
sss.logger.Info("Failed to encrypt key", log.ErrKey, err)
}
return encKey, err
}
func (sss *SharedSecretService) IsInitialised() bool {
return sss.secret != nil
}