-
Notifications
You must be signed in to change notification settings - Fork 38
/
da_enc_service.go
96 lines (79 loc) · 2.59 KB
/
da_enc_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
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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"errors"
"fmt"
gethlog "github.com/ethereum/go-ethereum/log"
"github.com/ten-protocol/go-ten/go/common/log"
)
const (
// GCMNonceLength is the nonce's length in bytes for encrypting and decrypting transactions.
GCMNonceLength = 12
// daSuffix is used for generating the encryption key from the shared secret
daSuffix = 0
)
// DAEncryptionService - handles encryption/decryption of the data stored in the DA layer
type DAEncryptionService struct {
sharedSecretService *SharedSecretService
cipher *cipher.AEAD
logger gethlog.Logger
}
func NewDAEncryptionService(sharedSecretService *SharedSecretService, logger gethlog.Logger) *DAEncryptionService {
da := &DAEncryptionService{
sharedSecretService: sharedSecretService,
logger: logger,
}
_ = da.Initialise()
return da
}
func (t *DAEncryptionService) Initialise() error {
if !t.sharedSecretService.IsInitialised() {
return errors.New("shared secret service is not initialised")
}
var err error
t.cipher, err = createCypher(t.sharedSecretService)
if err != nil {
return fmt.Errorf("error creating cypher: %w", err)
}
return nil
}
func createCypher(sharedSecretService *SharedSecretService) (*cipher.AEAD, error) {
key := sharedSecretService.ExtendEntropy([]byte{byte(daSuffix)})
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("could not initialise AES cipher for enclave DA key. cause %w", err)
}
cipher, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("could not initialise GCM cipher for enclave DA key. cause %w", err)
}
return &cipher, nil
}
func (t *DAEncryptionService) Encrypt(blob []byte) ([]byte, error) {
if t.cipher == nil {
return nil, errors.New("not initialised")
}
nonce, err := generateSecureEntropy(GCMNonceLength)
if err != nil {
t.logger.Error("could not generate nonce to encrypt transactions.", log.ErrKey, err)
return nil, err
}
ciphertext := (*t.cipher).Seal(nil, nonce, blob, nil)
// We prepend the nonce to the ciphertext, so that it can be retrieved when decrypting.
return append(nonce, ciphertext...), nil //nolint:makezero
}
func (t *DAEncryptionService) Decrypt(blob []byte) ([]byte, error) {
if t.cipher == nil {
return nil, errors.New("not initialised")
}
// The nonce is prepended to the ciphertext.
nonce := blob[0:GCMNonceLength]
ciphertext := blob[GCMNonceLength:]
plaintext, err := (*t.cipher).Open(nil, nonce, ciphertext, nil)
if err != nil {
t.logger.Error("could not decrypt blob.", log.ErrKey, err)
return nil, err
}
return plaintext, nil
}