From 05e74d56db04131a73895347123e3b3ec7aa78e6 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Fri, 28 May 2021 10:56:30 +0300 Subject: [PATCH] [#283] pkg/session: Implement Sign/Verify methods on Token Implement `Token.Sign` method which calculates signature of the data of the `Token` and writes the signature into it. Implement `Token.VerifySignature` which checks if `Token` signature is presented and valid. These methods allow to abstract the external context from the details of what kind of data is being signed and how the signature is stored. Signed-off-by: Leonard Lyubich --- pkg/session/session.go | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/pkg/session/session.go b/pkg/session/session.go index b11a058..ecdb93b 100644 --- a/pkg/session/session.go +++ b/pkg/session/session.go @@ -1,9 +1,14 @@ package session import ( + "crypto/ecdsa" + "github.com/nspcc-dev/neofs-api-go/pkg" "github.com/nspcc-dev/neofs-api-go/pkg/owner" + "github.com/nspcc-dev/neofs-api-go/util/signature" + "github.com/nspcc-dev/neofs-api-go/v2/refs" "github.com/nspcc-dev/neofs-api-go/v2/session" + v2signature "github.com/nspcc-dev/neofs-api-go/v2/signature" ) // Token represents NeoFS API v2-compatible @@ -84,6 +89,44 @@ func (t *Token) SetSessionKey(v []byte) { }) } +// Sign calculates and writes signature of the Token data. +// +// Returns signature calculation errors. +func (t *Token) Sign(key *ecdsa.PrivateKey) error { + tV2 := (*session.SessionToken)(t) + + signedData := v2signature.StableMarshalerWrapper{ + SM: tV2.GetBody(), + } + + return signature.SignDataWithHandler(key, signedData, func(key, sig []byte) { + tSig := tV2.GetSignature() + if tSig == nil { + tSig = new(refs.Signature) + } + + tSig.SetKey(key) + tSig.SetSign(sig) + + tV2.SetSignature(tSig) + }) +} + +// VerifySignature checks if token signature is +// presented and valid. +func (t *Token) VerifySignature() bool { + tV2 := (*session.SessionToken)(t) + + signedData := v2signature.StableMarshalerWrapper{ + SM: tV2.GetBody(), + } + + return signature.VerifyDataWithSource(signedData, func() (key, sig []byte) { + tSig := tV2.GetSignature() + return tSig.GetKey(), tSig.GetSign() + }) == nil +} + // Signature returns Token signature. func (t *Token) Signature() *pkg.Signature { return pkg.NewSignatureFromV2(