btcec

package module
v0.0.0-...-4ca0daa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2014 License: BSD-3-Clause, ISC Imports: 8 Imported by: 15

README

btcec

[Build Status] (https://travis-ci.org/conformal/btcec) [![Coverage Status] (https://coveralls.io/repos/conformal/btcec/badge.png?branch=master)] (https://coveralls.io/r/conformal/btcec?branch=master)

Package btcec implements elliptic curve cryptography needed for working with Bitcoin (secp256k1 only for now). It is designed so that it may be used with the standard crypto/ecdsa packages provided with go. A comprehensive suite of test is provided to ensure proper functionality. Package btcec was originally based on work from ThePiachu which is licensed under the same terms as Go, but it has signficantly diverged since then. The Conformal original is licensed under the liberal ISC license.

This package is one of the core packages from btcd, an alternative full-node implementation of bitcoin which is under active development by Conformal. Although it was primarily written for btcd, this package has intentionally been designed so it can be used as a standalone package for any projects needing to use secp256k1 elliptic curve cryptography.

Documentation

[GoDoc] (http://godoc.org/github.com/conformal/btcec)

Full go doc style documentation for the project can be viewed online without installing this package by using the GoDoc site here.

You can also view the documentation locally once the package is installed with the godoc tool by running godoc -http=":6060" and pointing your browser to http://localhost:6060/pkg/github.com/conformal/btcec

Installation

$ go get github.com/conformal/btcec

Examples

GPG Verification Key

All official release tags are signed by Conformal so users can ensure the code has not been tampered with and is coming from Conformal. To verify the signature perform the following:

  • Download the public key from the Conformal website at https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt

  • Import the public key into your GPG keyring:

    gpg --import GIT-GPG-KEY-conformal.txt
    
  • Verify the release tag with the following command where TAG_NAME is a placeholder for the specific tag:

    git tag -v TAG_NAME
    

License

Package btcec is licensed under the copyfree ISC License except for btcec.go and btcec_test.go which is under the same license as Go.

Documentation

Overview

Package btcec implements support for the elliptic curves needed for bitcoin.

Bitcoin uses elliptic curve cryptography using koblitz curves (specifically secp256k1) for cryptographic functions. See http://www.secg.org/collateral/sec2_final.pdf for details on the standard.

This package provides the data structures and functions implementing the crypto/elliptic Curve interface in order to permit using these curves with the standard crypto/ecdsa package provided with go. Helper functionality is provided to parse signatures and public keys from standard formats. It was designed for use with btcd, but should be general enough for other uses of elliptic curve crypto. It was originally based on some initial work by ThePiachu, but has significantly diverged since then.

Example (SignMessage)

This example demonstrates signing a message with a secp256k1 private key that is first parsed form raw bytes and serializing the generated signature.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/conformal/btcec"
	"github.com/conformal/btcwire"
)

func main() {
	// Decode a hex-encoded private key.
	pkBytes, err := hex.DecodeString("22a47fa09a223f2aa079edf85a7c2d4f87" +
		"20ee63e502ee2869afab7de234b80c")
	if err != nil {
		fmt.Println(err)
		return
	}
	privKey, pubKey := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes)

	// Sign a message using the private key.
	message := "test message"
	messageHash := btcwire.DoubleSha256([]byte(message))
	signature, err := privKey.Sign(messageHash)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Serialize and display the signature.
	//
	// NOTE: This is commented out for the example since the signature
	// produced uses random numbers and therefore will always be different.
	//fmt.Printf("Serialized Signature: %x\n", signature.Serialize())

	// Verify the signature for the message using the public key.
	verified := signature.Verify(messageHash, pubKey)
	fmt.Printf("Signature Verified? %v\n", verified)

}
Output:

Signature Verified? true
Example (VerifySignature)

This example demonstrates verifying a secp256k1 signature against a public key that is first parsed from raw bytes. The signature is also parsed from raw bytes.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/conformal/btcec"
	"github.com/conformal/btcwire"
)

func main() {
	// Decode hex-encoded serialized public key.
	pubKeyBytes, err := hex.DecodeString("02a673638cb9587cb68ea08dbef685c" +
		"6f2d2a751a8b3c6f2a7e9a4999e6e4bfaf5")
	if err != nil {
		fmt.Println(err)
		return
	}
	pubKey, err := btcec.ParsePubKey(pubKeyBytes, btcec.S256())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Decode hex-encoded serialized signature.
	sigBytes, err := hex.DecodeString("30450220090ebfb3690a0ff115bb1b38b" +
		"8b323a667b7653454f1bccb06d4bbdca42c2079022100ec95778b51e707" +
		"1cb1205f8bde9af6592fc978b0452dafe599481c46d6b2e479")
	if err != nil {
		fmt.Println(err)
		return
	}
	signature, err := btcec.ParseSignature(sigBytes, btcec.S256())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Verify the signature for the message using the public key.
	message := "test message"
	messageHash := btcwire.DoubleSha256([]byte(message))
	verified := signature.Verify(messageHash, pubKey)
	fmt.Println("Signature Verified?", verified)

}
Output:

Signature Verified? true

Index

Examples

Constants

View Source
const (
	PubKeyBytesLenCompressed   = 33
	PubKeyBytesLenUncompressed = 65
	PubKeyBytesLenHybrid       = 65
)

These constants define the lengths of serialized public keys.

View Source
const PrivKeyBytesLen = 32

PrivKeyBytesLen defines the length in bytes of a serialized private key.

Variables

This section is empty.

Functions

func PrivKeyFromBytes

func PrivKeyFromBytes(curve *KoblitzCurve, pk []byte) (*PrivateKey,
	*PublicKey)

PrivKeyFromBytes returns a private and public key for `curve' based on the private key passed as an argument as a byte slice.

func RecoverCompact

func RecoverCompact(curve *KoblitzCurve, signature,
	hash []byte) (*ecdsa.PublicKey, bool, error)

RecoverCompact verifies the compact signature "signature" of "hash" for the Koblitz curve in "curve". If the signature matches then the recovered public key will be returned as well as a boolen if the original key was compressed or not, else an error will be returned.

func SignCompact

func SignCompact(curve *KoblitzCurve, key *ecdsa.PrivateKey,
	hash []byte, isCompressedKey bool) ([]byte, error)

SignCompact produces a compact signature of the data in hash with the given private key on the given koblitz curve. The isCompressed parameter should be used to detail if the given signature should reference a compressed public key or not. If successful the bytes of the compact signature will be returned in the format: <(byte of 27+public key solution)+4 if compressed >< padded bytes for signature R><padded bytes for signature S> where the R and S parameters are padde up to the bitlengh of the curve.

Types

type KoblitzCurve

type KoblitzCurve struct {
	*elliptic.CurveParams

	H int // cofactor of the curve.
	// contains filtered or unexported fields
}

KoblitzCurve supports a koblitz curve implementation that fits the ECC Curve interface from crypto/elliptic.

func S256

func S256() *KoblitzCurve

S256 returns a Curve which implements secp256k1.

func (*KoblitzCurve) Add

func (curve *KoblitzCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)

Add returns the sum of (x1,y1) and (x2,y2). Part of the elliptic.Curve interface.

func (*KoblitzCurve) Double

func (curve *KoblitzCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int)

Double returns 2*(x1,y1). Part of the elliptic.Curve interface.

func (*KoblitzCurve) IsOnCurve

func (curve *KoblitzCurve) IsOnCurve(x, y *big.Int) bool

IsOnCurve returns boolean if the point (x,y) is on the curve. Part of the elliptic.Curve interface. This function differs from the crypto/elliptic algorithm since a = 0 not -3.

func (*KoblitzCurve) Params

func (curve *KoblitzCurve) Params() *elliptic.CurveParams

Params returns the parameters for the curve.

func (*KoblitzCurve) QPlus1Div4

func (curve *KoblitzCurve) QPlus1Div4() *big.Int

QPlus1Div4 returns the Q+1/4 constant for the curve for use in calculating square roots via exponention.

func (*KoblitzCurve) ScalarBaseMult

func (curve *KoblitzCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int)

ScalarBaseMult returns k*G where G is the base point of the group and k is a big endian integer. Part of the elliptic.Curve interface.

func (*KoblitzCurve) ScalarMult

func (curve *KoblitzCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int)

ScalarMult returns k*(Bx, By) where k is a big endian integer. Part of the elliptic.Curve interface.

type PrivateKey

type PrivateKey ecdsa.PrivateKey

PrivateKey wraps an ecdsa.PrivateKey as a convenience mainly for signing things with the the private key without having to directly import the ecdsa package.

func (*PrivateKey) Serialize

func (p *PrivateKey) Serialize() []byte

Serialize returns the private key number d as a big-endian binary-encoded number, padded to a length of 32 bytes.

func (*PrivateKey) Sign

func (p *PrivateKey) Sign(hash []byte) (*Signature, error)

Sign wraps ecdsa.Sign to sign the provided hash (which should be the result of hashing a larger message) using the private key.

func (*PrivateKey) ToECDSA

func (p *PrivateKey) ToECDSA() *ecdsa.PrivateKey

ToECDSA returns the private key as a *ecdsa.PrivateKey.

type PublicKey

type PublicKey ecdsa.PublicKey

PublicKey is an ecdsa.PublicKey with additional functions to serialize in uncompressed, compressed, and hybrid formats.

func ParsePubKey

func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err error)

ParsePubKey parses a public key for a koblitz curve from a bytestring into a ecdsa.Publickey, verifying that it is valid. It supports compressed, uncompressed and hybrid signature formats.

func (*PublicKey) SerializeCompressed

func (p *PublicKey) SerializeCompressed() []byte

SerializeCompressed serializes a public key in a 33-byte compressed format.

func (*PublicKey) SerializeHybrid

func (p *PublicKey) SerializeHybrid() []byte

SerializeHybrid serializes a public key in a 65-byte hybrid format.

func (*PublicKey) SerializeUncompressed

func (p *PublicKey) SerializeUncompressed() []byte

SerializeUncompressed serializes a public key in a 65-byte uncompressed format.

func (*PublicKey) ToECDSA

func (p *PublicKey) ToECDSA() *ecdsa.PublicKey

ToECDSA returns the public key as a *ecdsa.PublicKey.

type Signature

type Signature struct {
	R *big.Int
	S *big.Int
}

Signature is a type representing an ecdsa signature.

func ParseDERSignature

func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error)

ParseDERSignature parses a signature in DER format for the curve type `curve` into a Signature type. If parsing according to the less strict BER format is needed, use ParseSignature.

func ParseSignature

func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error)

ParseSignature parses a signature in BER format for the curve type `curve' into a Signature type, perfoming some basic sanity checks. If parsing according to the more strict DER format is needed, use ParseDERSignature.

func (*Signature) Serialize

func (sig *Signature) Serialize() []byte

Serialize returns the ECDSA signature in the more strict DER format. Note that the serialized bytes returned do not include the appended hash type used in Bitcoin signature scripts.

encoding/asn1 is broken so we hand roll this output:

0x30 <length> 0x02 <length r> r 0x02 <length s> s

func (*Signature) Verify

func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool

Verify calls ecdsa.Verify to verify the signature of hash using the public key. It returns true if the signature is valid, false otherwise.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL