2019-10-17 13:11:58 +00:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"crypto/sha256"
|
|
|
|
"math/big"
|
|
|
|
|
|
|
|
"github.com/nspcc-dev/neofs-crypto/internal"
|
|
|
|
"github.com/nspcc-dev/rfc6979"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// RFC6979SignatureSize contains r and s coordinates (32 bytes)
|
|
|
|
RFC6979SignatureSize = 64
|
|
|
|
|
2019-11-12 08:13:12 +00:00
|
|
|
// ErrWrongHashSize when passed signature to VerifyRFC6979 has wrong size.
|
2019-10-17 13:11:58 +00:00
|
|
|
ErrWrongHashSize = internal.Error("wrong hash size")
|
|
|
|
|
2019-11-12 08:13:12 +00:00
|
|
|
// ErrWrongSignature when passed signature to VerifyRFC6979 isn't valid.
|
2019-10-17 13:11:58 +00:00
|
|
|
ErrWrongSignature = internal.Error("wrong signature")
|
|
|
|
)
|
|
|
|
|
2019-11-12 13:00:27 +00:00
|
|
|
// hashBytesRFC6979 returns the sha256 sum.
|
|
|
|
func hashBytesRFC6979(data []byte) []byte {
|
|
|
|
sign := sha256.Sum256(data)
|
|
|
|
return sign[:]
|
|
|
|
}
|
|
|
|
|
2019-10-17 13:11:58 +00:00
|
|
|
// SignRFC6979 signs an arbitrary length hash (which should be the result of
|
|
|
|
// hashing a larger message) using the private key. It returns the
|
|
|
|
// signature as a pair of integers.
|
|
|
|
//
|
|
|
|
// Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
|
2019-11-12 08:13:12 +00:00
|
|
|
// to the byte-length of the subgroup. This function does not perform that.
|
2019-10-17 13:11:58 +00:00
|
|
|
func SignRFC6979(key *ecdsa.PrivateKey, msg []byte) ([]byte, error) {
|
2020-01-14 09:06:13 +00:00
|
|
|
if key == nil {
|
|
|
|
return nil, ErrEmptyPrivateKey
|
2019-10-17 13:11:58 +00:00
|
|
|
}
|
2020-01-14 09:06:13 +00:00
|
|
|
r, s := rfc6979.SignECDSA(key, hashBytesRFC6979(msg), sha256.New)
|
2019-10-17 13:11:58 +00:00
|
|
|
return append(r.Bytes(), s.Bytes()...), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func decodeSignature(sig []byte) (*big.Int, *big.Int, error) {
|
|
|
|
if ln := len(sig); ln != RFC6979SignatureSize {
|
|
|
|
return nil, nil, errors.Wrapf(ErrWrongHashSize, "actual=%d, expect=%d", ln, RFC6979SignatureSize)
|
|
|
|
}
|
|
|
|
|
|
|
|
return new(big.Int).SetBytes(sig[:32]), new(big.Int).SetBytes(sig[32:]), nil
|
|
|
|
}
|
|
|
|
|
2019-11-12 08:13:12 +00:00
|
|
|
// VerifyRFC6979 verifies the signature of msg using the public key. It
|
|
|
|
// return nil only if signature is valid.
|
2019-11-12 12:52:13 +00:00
|
|
|
func VerifyRFC6979(key *ecdsa.PublicKey, msg, sig []byte) error {
|
2020-01-14 09:06:13 +00:00
|
|
|
if key == nil {
|
|
|
|
return ErrEmptyPublicKey
|
|
|
|
} else if r, s, err := decodeSignature(sig); err != nil {
|
2019-10-17 13:11:58 +00:00
|
|
|
return err
|
2019-11-12 13:00:27 +00:00
|
|
|
} else if !ecdsa.Verify(key, hashBytesRFC6979(msg), r, s) {
|
2019-10-17 13:11:58 +00:00
|
|
|
return ErrWrongSignature
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|