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.

71 lines
2.3 KiB

  1. // +build !cgo
  2. package secp256k1
  3. import (
  4. "math/big"
  5. secp256k1 "github.com/btcsuite/btcd/btcec"
  6. "github.com/tendermint/tendermint/crypto"
  7. )
  8. // used to reject malleable signatures
  9. // see:
  10. // - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
  11. // - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39
  12. var secp256k1N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
  13. var secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
  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 PrivKeySecp256k1) 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. // VerifyBytes verifies a signature of the form R || S.
  26. // It rejects signatures which are not in lower-S form.
  27. func (pubKey PubKeySecp256k1) VerifyBytes(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. new(big.Int).SetBytes(sigStr[:32]),
  49. 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. }