2020-08-12 14:03:11 +00:00
|
|
|
package signature
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
|
|
|
|
2022-02-22 11:25:43 +00:00
|
|
|
"github.com/nspcc-dev/neofs-api-go/v2/refs"
|
2020-08-12 14:03:11 +00:00
|
|
|
crypto "github.com/nspcc-dev/neofs-crypto"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DataSource interface {
|
|
|
|
ReadSignedData([]byte) ([]byte, error)
|
2020-08-12 15:20:04 +00:00
|
|
|
SignedDataSize() int
|
2020-08-12 14:03:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type DataWithSignature interface {
|
|
|
|
DataSource
|
2022-02-22 11:25:43 +00:00
|
|
|
GetSignature() *refs.Signature
|
|
|
|
SetSignature(*refs.Signature)
|
2020-08-12 14:03:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type SignOption func(*cfg)
|
|
|
|
|
2022-02-22 11:25:43 +00:00
|
|
|
type KeySignatureHandler func(*refs.Signature)
|
2020-08-12 14:03:11 +00:00
|
|
|
|
2022-02-22 11:25:43 +00:00
|
|
|
type KeySignatureSource func() *refs.Signature
|
2020-08-12 14:03:11 +00:00
|
|
|
|
2022-02-22 11:25:43 +00:00
|
|
|
func SignDataWithHandler(key *ecdsa.PrivateKey, src DataSource, handler KeySignatureHandler, opts ...SignOption) error {
|
2020-08-12 14:03:11 +00:00
|
|
|
if key == nil {
|
2022-02-22 11:25:43 +00:00
|
|
|
return crypto.ErrEmptyPrivateKey
|
2020-08-12 14:03:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
data, err := dataForSignature(src)
|
|
|
|
if err != nil {
|
2022-02-22 11:25:43 +00:00
|
|
|
return err
|
2020-08-12 14:03:11 +00:00
|
|
|
}
|
|
|
|
defer bytesPool.Put(data)
|
|
|
|
|
|
|
|
cfg := defaultCfg()
|
|
|
|
|
|
|
|
for i := range opts {
|
|
|
|
opts[i](cfg)
|
|
|
|
}
|
|
|
|
|
2022-02-22 11:25:43 +00:00
|
|
|
sigData, err := sign(cfg, cfg.defaultScheme, key, data)
|
2020-08-12 14:03:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-02-22 11:25:43 +00:00
|
|
|
sig := new(refs.Signature)
|
|
|
|
sig.SetScheme(cfg.defaultScheme)
|
|
|
|
sig.SetKey(crypto.MarshalPublicKey(&key.PublicKey))
|
|
|
|
sig.SetSign(sigData)
|
|
|
|
handler(sig)
|
2020-08-12 14:03:11 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func VerifyDataWithSource(dataSrc DataSource, sigSrc KeySignatureSource, opts ...SignOption) error {
|
|
|
|
data, err := dataForSignature(dataSrc)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer bytesPool.Put(data)
|
|
|
|
|
|
|
|
cfg := defaultCfg()
|
|
|
|
|
|
|
|
for i := range opts {
|
|
|
|
opts[i](cfg)
|
|
|
|
}
|
|
|
|
|
2022-02-22 11:25:43 +00:00
|
|
|
return verify(cfg, data, sigSrc())
|
2020-08-12 14:03:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func SignData(key *ecdsa.PrivateKey, v DataWithSignature, opts ...SignOption) error {
|
2022-02-22 11:25:43 +00:00
|
|
|
return SignDataWithHandler(key, v, v.SetSignature, opts...)
|
2020-08-12 14:03:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func VerifyData(src DataWithSignature, opts ...SignOption) error {
|
2022-02-22 11:25:43 +00:00
|
|
|
return VerifyDataWithSource(src, src.GetSignature, opts...)
|
2020-08-12 14:03:11 +00:00
|
|
|
}
|