You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.3 KiB

  1. //go:build !libsecp256k1
  2. // +build !libsecp256k1
  3. package secp256k1
  4. import (
  5. "math/big"
  6. secp256k1 "github.com/btcsuite/btcd/btcec"
  7. "github.com/tendermint/tendermint/crypto"
  8. )
  9. // used to reject malleable signatures
  10. // see:
  11. // - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
  12. // - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39
  13. var secp256k1halfN = new(big.Int).Rsh(secp256k1.S256().N, 1)
  14. // Sign creates an ECDSA signature on curve Secp256k1, using SHA256 on the msg.
  15. // The returned signature will be of the form R || S (in lower-S form).
  16. func (privKey PrivKey) Sign(msg []byte) ([]byte, error) {
  17. priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey)
  18. sig, err := priv.Sign(crypto.Sha256(msg))
  19. if err != nil {
  20. return nil, err
  21. }
  22. sigBytes := serializeSig(sig)
  23. return sigBytes, nil
  24. }
  25. // VerifySignature verifies a signature of the form R || S.
  26. // It rejects signatures which are not in lower-S form.
  27. func (pubKey PubKey) VerifySignature(msg []byte, sigStr []byte) bool {
  28. if len(sigStr) != 64 {
  29. return false
  30. }
  31. pub, err := secp256k1.ParsePubKey(pubKey, secp256k1.S256())
  32. if err != nil {
  33. return false
  34. }
  35. // parse the signature:
  36. signature := signatureFromBytes(sigStr)
  37. // Reject malleable signatures. libsecp256k1 does this check but btcec doesn't.
  38. // see: https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
  39. if signature.S.Cmp(secp256k1halfN) > 0 {
  40. return false
  41. }
  42. return signature.Verify(crypto.Sha256(msg), pub)
  43. }
  44. // Read Signature struct from R || S. Caller needs to ensure
  45. // that len(sigStr) == 64.
  46. func signatureFromBytes(sigStr []byte) *secp256k1.Signature {
  47. return &secp256k1.Signature{
  48. R: new(big.Int).SetBytes(sigStr[:32]),
  49. S: new(big.Int).SetBytes(sigStr[32:64]),
  50. }
  51. }
  52. // Serialize signature to R || S.
  53. // R, S are padded to 32 bytes respectively.
  54. func serializeSig(sig *secp256k1.Signature) []byte {
  55. rBytes := sig.R.Bytes()
  56. sBytes := sig.S.Bytes()
  57. sigBytes := make([]byte, 64)
  58. // 0 pad the byte arrays from the left if they aren't big enough.
  59. copy(sigBytes[32-len(rBytes):32], rBytes)
  60. copy(sigBytes[64-len(sBytes):64], sBytes)
  61. return sigBytes
  62. }