2022-06-10 15:32:15 +00:00
|
|
|
package server
|
|
|
|
|
2022-06-10 23:03:16 +00:00
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/rand"
|
|
|
|
|
|
|
|
"github.com/status-im/status-go/protocol/common"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Payload struct {
|
|
|
|
plain []byte
|
|
|
|
encrypted []byte
|
|
|
|
}
|
|
|
|
|
2022-06-10 15:32:15 +00:00
|
|
|
type PayloadManager struct {
|
2022-06-10 23:03:16 +00:00
|
|
|
aesKey []byte
|
|
|
|
toSend *Payload
|
|
|
|
received *Payload
|
2022-06-10 15:32:15 +00:00
|
|
|
}
|
|
|
|
|
2022-06-10 23:03:16 +00:00
|
|
|
func NewPayloadManager(pk *ecdsa.PrivateKey) (*PayloadManager, error) {
|
|
|
|
ek, err := makeEncryptionKey(pk)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &PayloadManager{ek, new(Payload), new(Payload)}, nil
|
2022-06-10 15:32:15 +00:00
|
|
|
}
|
|
|
|
|
2022-06-10 23:03:16 +00:00
|
|
|
func (pm *PayloadManager) Mount(data []byte) error {
|
|
|
|
ep, err := common.Encrypt(data, pm.aesKey, rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
pm.toSend.plain = data
|
|
|
|
pm.toSend.encrypted = ep
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pm *PayloadManager) Receive(data []byte) error {
|
|
|
|
pd, err := common.Decrypt(data, pm.aesKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
pm.received.encrypted = data
|
|
|
|
pm.received.plain = pd
|
|
|
|
return nil
|
2022-06-10 15:32:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (pm *PayloadManager) ToSend() []byte {
|
2022-06-10 23:03:16 +00:00
|
|
|
return pm.toSend.encrypted
|
2022-06-10 15:32:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (pm *PayloadManager) Received() []byte {
|
2022-06-10 23:03:16 +00:00
|
|
|
return pm.received.plain
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pm *PayloadManager) ResetPayload() {
|
|
|
|
pm.toSend = new(Payload)
|
|
|
|
pm.received = new(Payload)
|
2022-06-10 15:32:15 +00:00
|
|
|
}
|