[#1255] node/session: Add encryption

Add `WithEncryption` option that passes ECDSA key to the persistent session
storage. It uses 32 bytes from marshalled ECDSA key in ASN.1 DER from in
AES-256 algorithm encryption in Galois/Counter Mode.

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2022-03-21 14:53:49 +03:00 committed by Alex Vanin
parent a884ad56d9
commit 01ed366e99
6 changed files with 111 additions and 11 deletions

View file

@ -12,12 +12,19 @@ import (
const expOffset = 8
func packToken(exp uint64, key *ecdsa.PrivateKey) ([]byte, error) {
func (s *TokenStore) packToken(exp uint64, key *ecdsa.PrivateKey) ([]byte, error) {
rawKey, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, fmt.Errorf("could not marshal private key: %w", err)
}
if s.gcm != nil {
rawKey, err = s.encrypt(rawKey)
if err != nil {
return nil, fmt.Errorf("could not encrypt session key: %w", err)
}
}
res := make([]byte, expOffset, expOffset+len(rawKey))
binary.LittleEndian.PutUint64(res, exp)
@ -26,10 +33,20 @@ func packToken(exp uint64, key *ecdsa.PrivateKey) ([]byte, error) {
return res, nil
}
func unpackToken(raw []byte) (*storage.PrivateToken, error) {
epoch := binary.LittleEndian.Uint64(raw[:expOffset])
func (s *TokenStore) unpackToken(raw []byte) (*storage.PrivateToken, error) {
var err error
key, err := x509.ParseECPrivateKey(raw[expOffset:])
epoch := epochFromToken(raw)
rawKey := raw[expOffset:]
if s.gcm != nil {
rawKey, err = s.decrypt(rawKey)
if err != nil {
return nil, fmt.Errorf("could not decrypt session key: %w", err)
}
}
key, err := x509.ParseECPrivateKey(rawKey)
if err != nil {
return nil, fmt.Errorf("could not unmarshal private key: %w", err)
}