github.com/chain5j/chain5j-pkg@v1.0.7/crypto/signature/secp256k1/signature.go (about)

     1  // Package secp256k1
     2  //
     3  // @author: xwc1125
     4  package secp256k1
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"errors"
     9  	"fmt"
    10  	"math/big"
    11  
    12  	"github.com/chain5j/chain5j-pkg/crypto/signature/secp256k1/btcecv1"
    13  )
    14  
    15  var (
    16  	secp256k1N, _  = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
    17  	secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
    18  )
    19  
    20  // RecoverPubkey returns the uncompressed public key that created the given signature.
    21  func RecoverPubkey(hash, sig []byte) ([]byte, error) {
    22  	pub, err := SigToPub(hash, sig)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  	p := (*btcecv1.PublicKey)(pub)
    27  	bytes := p.SerializeUncompressed()
    28  	return bytes, err
    29  }
    30  
    31  // SigToPub returns the public key that created the given signature.
    32  func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
    33  	// Convert to btcec input format with 'recovery id' v at the beginning.
    34  	btcsig := make([]byte, 65)
    35  	btcsig[0] = sig[64] + 27
    36  	copy(btcsig[1:], sig)
    37  
    38  	pub, _, err := btcecv1.RecoverCompact(btcecv1.S256(), btcsig, hash)
    39  	return pub.ToECDSA(), err
    40  }
    41  
    42  // Sign calculates an ECDSA signature.
    43  //
    44  // This function is susceptible to chosen plaintext attacks that can leak
    45  // information about the private key that is used for signing. Callers must
    46  // be aware that the given hash cannot be chosen by an adversery. Common
    47  // solution is to hash any input before calculating the signature.
    48  //
    49  // The produced signature is in the [R || S || V] format where V is 0 or 1.
    50  func Sign(prv *ecdsa.PrivateKey, hash []byte) ([]byte, error) {
    51  	if len(hash) != 32 {
    52  		return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
    53  	}
    54  	if prv.Curve != btcecv1.S256() {
    55  		return nil, fmt.Errorf("private key curve is not secp256k1")
    56  	}
    57  	sig, err := btcecv1.SignCompact(btcecv1.S256(), (*btcecv1.PrivateKey)(prv), hash, false)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	// Convert to Ethereum signature format with 'recovery id' v at the end.
    62  	v := sig[0] - 27
    63  	copy(sig, sig[1:])
    64  	sig[64] = v
    65  	return sig, nil
    66  }
    67  
    68  func Verify(pub *ecdsa.PublicKey, hash []byte, signature []byte) bool {
    69  	sig := &btcecv1.Signature{R: new(big.Int).SetBytes(signature[:32]), S: new(big.Int).SetBytes(signature[32:64])}
    70  	key := (*btcecv1.PublicKey)(pub)
    71  	return sig.Verify(hash, key)
    72  }
    73  
    74  // VerifySignature checks that the given public key created signature over hash.
    75  // The public key should be in compressed (33 bytes) or uncompressed (65 bytes) format.
    76  // The signature should have the 64 byte [R || S] format.
    77  func VerifySignature(pubkey, hash, signature []byte) bool {
    78  	if len(signature) != 64 {
    79  		return false
    80  	}
    81  	sig := &btcecv1.Signature{R: new(big.Int).SetBytes(signature[:32]), S: new(big.Int).SetBytes(signature[32:])}
    82  	key, err := btcecv1.ParsePubKey(pubkey, btcecv1.S256())
    83  	if err != nil {
    84  		return false
    85  	}
    86  	return sig.Verify(hash, key)
    87  }
    88  
    89  // DecompressPubkey parses a public key in the 33-byte compressed format.
    90  func DecompressPubkey(pubkey []byte) (*ecdsa.PublicKey, error) {
    91  	if len(pubkey) != 33 {
    92  		return nil, errors.New("invalid compressed public key length")
    93  	}
    94  	key, err := btcecv1.ParsePubKey(pubkey, btcecv1.S256())
    95  	if err != nil {
    96  		return nil, err
    97  	}
    98  	return key.ToECDSA(), nil
    99  }
   100  
   101  // CompressPubkey encodes a public key to the 33-byte compressed format.
   102  func CompressPubkey(pubkey *ecdsa.PublicKey) []byte {
   103  	return (*btcecv1.PublicKey)(pubkey).SerializeCompressed()
   104  }