service: implement Sign/Verify functions for SessionToken

This commit is contained in:
Leonard Lyubich 2020-04-28 19:03:15 +03:00
parent e47b775a86
commit 82ffde253b
2 changed files with 231 additions and 0 deletions

View file

@ -1,7 +1,12 @@
package service
import (
"crypto/ecdsa"
"encoding/binary"
"github.com/nspcc-dev/neofs-api-go/internal"
"github.com/nspcc-dev/neofs-api-go/refs"
crypto "github.com/nspcc-dev/neofs-crypto"
)
// VerbContainer is an interface of the container of a token verb value.
@ -57,8 +62,13 @@ type SessionToken interface {
SignatureContainer
}
// ErrEmptyToken is raised when passed Token is nil.
const ErrEmptyToken = internal.Error("token is empty")
var _ SessionToken = (*Token)(nil)
var tokenEndianness = binary.BigEndian
// GetID is an ID field getter.
func (m Token_Info) GetID() TokenID {
return m.ID
@ -123,3 +133,80 @@ func (m *Token_Info) SetSessionKey(key []byte) {
func (m *Token) SetSignature(sig []byte) {
m.Signature = sig
}
// Returns byte slice that is used for creation/verification of the token signature.
func verificationTokenData(token SessionToken) []byte {
var sz int
id := token.GetID()
sz += id.Size()
ownerID := token.GetOwnerID()
sz += ownerID.Size()
verb := uint32(token.GetVerb())
sz += 4
addr := token.GetAddress()
sz += addr.CID.Size() + addr.ObjectID.Size()
cEpoch := token.CreationEpoch()
sz += 8
fEpoch := token.ExpirationEpoch()
sz += 8
key := token.GetSessionKey()
sz += len(key)
data := make([]byte, sz)
var off int
tokenEndianness.PutUint32(data, verb)
off += 4
tokenEndianness.PutUint64(data[off:], cEpoch)
off += 8
tokenEndianness.PutUint64(data[off:], fEpoch)
off += 8
off += copy(data[off:], id.Bytes())
off += copy(data[off:], ownerID.Bytes())
off += copy(data[off:], addr.CID.Bytes())
off += copy(data[off:], addr.ObjectID.Bytes())
off += copy(data[off:], key)
return data
}
// SignToken calculates and stores the signature of token information.
//
// If passed token is nil, ErrEmptyToken returns.
// If passed private key is nil, crypto.ErrEmptyPrivateKey returns.
func SignToken(token SessionToken, key *ecdsa.PrivateKey) error {
if token == nil {
return ErrEmptyToken
} else if key == nil {
return crypto.ErrEmptyPrivateKey
}
sig, err := crypto.Sign(key, verificationTokenData(token))
if err != nil {
return err
}
token.SetSignature(sig)
return nil
}
// VerifyTokenSignature checks if token was signed correctly.
func VerifyTokenSignature(token SessionToken, key *ecdsa.PublicKey) error {
return crypto.Verify(
key,
verificationTokenData(token),
token.GetSignature(),
)
}