secp256k1

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2016 License: ISC Imports: 22 Imported by: 0

README

secp256k1

Package dcrec implements elliptic curve cryptography needed for working with Decred (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 dcrec was originally based on work from ThePiachu which is licensed under the same terms as Go, but it has signficantly diverged since then. The decred developers original is licensed under the liberal ISC license.

Although this package was primarily written for dcrd, it 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/decred/dcrd/dcrec)

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/decred/dcrd/dcrec

Installation

$ go get github.com/decred/dcrd/dcrec

Examples

License

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

Documentation

Overview

Package secp256k1 implements support for the elliptic curves needed for decred.

Decred 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 dcrd, 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 (DecryptMessage)

This example demonstrates decrypting a message using a private key that is first parsed from raw bytes.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/decred/dcrd/dcrec/secp256k1"
)

func main() {
	// Decode the hex-encoded private key.
	pkBytes, err := hex.DecodeString("a11b0a4e1a132305652ee7a8eb7848f6ad" +
		"5ea381e3ce20a2c086a2e388230811")
	if err != nil {
		fmt.Println(err)
		return
	}

	privKey, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), pkBytes)

	ciphertext, err := hex.DecodeString("35f644fbfb208bc71e57684c3c8b437402ca" +
		"002047a2f1b38aa1a8f1d5121778378414f708fe13ebf7b4a7bb74407288c1958969" +
		"00207cf4ac6057406e40f79961c973309a892732ae7a74ee96cd89823913b8b8d650" +
		"a44166dc61ea1c419d47077b748a9c06b8d57af72deb2819d98a9d503efc59fc8307" +
		"d14174f8b83354fac3ff56075162")

	// Try decrypting the message.
	plaintext, err := secp256k1.Decrypt(privKey, ciphertext)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(plaintext))

}
Output:

test message
Example (EncryptMessage)

This example demonstrates encrypting a message for a public key that is first parsed from raw bytes, then decrypting it using the corresponding private key.

package main

import (
	"encoding/hex"
	"fmt"

	"github.com/decred/dcrd/dcrec/secp256k1"
)

func main() {
	// Decode the hex-encoded pubkey of the recipient.
	pubKeyBytes, err := hex.DecodeString("04115c42e757b2efb7671c578530ec191a1" +
		"359381e6a71127a9d37c486fd30dae57e76dc58f693bd7e7010358ce6b165e483a29" +
		"21010db67ac11b1b51b651953d2") // uncompressed pubkey
	if err != nil {
		fmt.Println(err)
		return
	}
	pubKey, err := secp256k1.ParsePubKey(pubKeyBytes, secp256k1.S256())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Encrypt a message decryptable by the private key corresponding to pubKey
	message := "test message"
	ciphertext, err := secp256k1.Encrypt(pubKey, []byte(message))
	if err != nil {
		fmt.Println(err)
		return
	}

	// Decode the hex-encoded private key.
	pkBytes, err := hex.DecodeString("a11b0a4e1a132305652ee7a8eb7848f6ad" +
		"5ea381e3ce20a2c086a2e388230811")
	if err != nil {
		fmt.Println(err)
		return
	}
	// note that we already have corresponding pubKey
	privKey, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), pkBytes)

	// Try decrypting and verify if it's the same message.
	plaintext, err := secp256k1.Decrypt(privKey, ciphertext)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(plaintext))

}
Output:

test message
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/decred/dcrd/chaincfg/chainhash"
	"github.com/decred/dcrd/dcrec/secp256k1"
)

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

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

	// Serialize and display the signature.
	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:

Serialized Signature: 3045022100fcc0a8768cfbcefcf2cadd7cfb0fb18ed08dd2e2ae84bef1a474a3d351b26f0302200fc1a350b45f46fa00101391302818d748c2b22615511a3ffd5bb638bd777207
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/decred/dcrd/chaincfg/chainhash"
	"github.com/decred/dcrd/dcrec/secp256k1"
)

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

	// Decode hex-encoded serialized signature.
	sigBytes, err := hex.DecodeString("3045022100fcc0a8768cfbcefcf2cadd7cfb0" +
		"fb18ed08dd2e2ae84bef1a474a3d351b26f0302200fc1a350b45f46fa0010139130" +
		"2818d748c2b22615511a3ffd5bb638bd777207")

	if err != nil {
		fmt.Println(err)
		return
	}
	signature, err := secp256k1.ParseSignature(sigBytes, secp256k1.S256())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Verify the signature for the message using the public key.
	message := "test message"
	messageHash := chainhash.HashFuncB([]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

View Source
var (
	// ErrInvalidMAC occurs when Message Authentication Check (MAC) fails
	// during decryption. This happens because of either invalid private key or
	// corrupt ciphertext.
	ErrInvalidMAC = errors.New("invalid mac hash")
)
View Source
var (
	// FieldOne is simply the integer 1 in field representation.  It is
	// used to avoid needing to create it multiple times during the internal
	// arithmetic.
	FieldOne = new(FieldVal).SetInt(1)
)

Functions

func DecompressPoint

func DecompressPoint(curve *KoblitzCurve, x *big.Int, ybit bool) (*big.Int, error)

DecompressPoint decompresses a point on the given curve given the X point and the solution to use.

func Decrypt

func Decrypt(priv *PrivateKey, in []byte) ([]byte, error)

Decrypt decrypts data that was encrypted using the Encrypt function.

func Encrypt

func Encrypt(pubkey *PublicKey, in []byte) ([]byte, error)

Encrypt encrypts data for the target public key using AES-256-CBC. It also generates a private key (the pubkey of which is also in the output). The only supported curve is secp256k1. The `structure' that it encodes everything into is:

struct {
	// Initialization Vector used for AES-256-CBC
	IV [16]byte
	// Public Key: curve(2) + len_of_pubkeyX(2) + pubkeyX +
	// len_of_pubkeyY(2) + pubkeyY (curve = 714)
	PublicKey [70]byte
	// Cipher text
	Data []byte
	// HMAC-SHA-256 Message Authentication Code
	HMAC [32]byte
}

The primary aim is to ensure byte compatibility with Pyelliptic. Additionaly, refer to section 5.8.1 of ANSI X9.63 for rationale on this format.

func GenerateKey

func GenerateKey(curve *KoblitzCurve, rand io.Reader) (priv []byte, x,
	y *big.Int, err error)

GenerateKey generates a key using a random number generator, returning the private scalar and the corresponding public key points.

func GenerateSharedSecret

func GenerateSharedSecret(privkey *PrivateKey, pubkey *PublicKey) []byte

GenerateSharedSecret generates a shared secret based on a private key and a private key using Diffie-Hellman key exchange (ECDH) (RFC 4753). RFC5903 Section 9 states we should only return x.

func NAF

func NAF(k []byte) ([]byte, []byte)

NAF takes a positive integer k and returns the Non-Adjacent Form (NAF) as two byte slices. The first is where 1s will be. The second is where -1s will be. NAF is convenient in that on average, only 1/3rd of its values are non-zero. This is algorithm 3.30 from [GECC].

Essentially, this makes it possible to minimize the number of operations since the resulting ints returned will be at least 50% 0s.

func NonceRFC6979

func NonceRFC6979(privkey *big.Int, hash []byte, extra []byte,
	version []byte) *big.Int

NonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to RFC 6979. It takes a 32-byte hash as an input and returns 32-byte nonce to be used in ECDSA algorithm.

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 PrivKeyFromScalar

func PrivKeyFromScalar(curve *KoblitzCurve, s []byte) (*PrivateKey,
	*PublicKey)

PrivKeyFromScalar is the same as PrivKeyFromBytes in secp256k1.

func SignCompact

func SignCompact(curve *KoblitzCurve, key *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 FieldVal

type FieldVal struct {
	// contains filtered or unexported fields
}

FieldVal implements optimized fixed-precision arithmetic over the secp256k1 finite field. This means all arithmetic is performed modulo 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f. It represents each 256-bit value as 10 32-bit integers in base 2^26. This provides 6 bits of overflow in each word (10 bits in the most significant word) for a total of 64 bits of overflow (9*6 + 10 = 64). It only implements the arithmetic needed for elliptic curve operations.

The following depicts the internal representation:

 -----------------------------------------------------------------
|        n[9]       |        n[8]       | ... |        n[0]       |
| 32 bits available | 32 bits available | ... | 32 bits available |
| 22 bits for value | 26 bits for value | ... | 26 bits for value |
| 10 bits overflow  |  6 bits overflow  | ... |  6 bits overflow  |
| Mult: 2^(26*9)    | Mult: 2^(26*8)    | ... | Mult: 2^(26*0)    |
 -----------------------------------------------------------------

For example, consider the number 2^49 + 1. It would be represented as:

n[0] = 1
n[1] = 2^23
n[2..9] = 0

The full 256-bit value is then calculated by looping i from 9..0 and doing sum(n[i] * 2^(26i)) like so:

n[9] * 2^(26*9) = 0    * 2^234 = 0
n[8] * 2^(26*8) = 0    * 2^208 = 0
...
n[1] * 2^(26*1) = 2^23 * 2^26  = 2^49
n[0] * 2^(26*0) = 1    * 2^0   = 1
Sum: 0 + 0 + ... + 2^49 + 1 = 2^49 + 1

func (*FieldVal) Add

func (f *FieldVal) Add(val *FieldVal) *FieldVal

Add adds the passed value to the existing field value and stores the result in f.

The field value is returned to support chaining. This enables syntax like: f.Add(f2).AddInt(1) so that f = f + f2 + 1.

func (*FieldVal) Add2

func (f *FieldVal) Add2(val *FieldVal, val2 *FieldVal) *FieldVal

Add2 adds the passed two field values together and stores the result in f.

The field value is returned to support chaining. This enables syntax like: f3.Add2(f, f2).AddInt(1) so that f3 = f + f2 + 1.

func (*FieldVal) AddInt

func (f *FieldVal) AddInt(ui uint) *FieldVal

AddInt adds the passed integer to the existing field value and stores the result in f. This is a convenience function since it is fairly common to perform some arithemetic with small native integers.

The field value is returned to support chaining. This enables syntax like: f.AddInt(1).Add(f2) so that f = f + 1 + f2.

func (*FieldVal) Bytes

func (f *FieldVal) Bytes() *[32]byte

Bytes unpacks the field value to a 32-byte big-endian value. See PutBytes for a variant that allows the a buffer to be passed which can be useful to to cut down on the number of allocations by allowing the caller to reuse a buffer.

The field value must be normalized for this function to return correct result.

func (*FieldVal) Equals

func (f *FieldVal) Equals(val *FieldVal) bool

Equals returns whether or not the two field values are the same. Both field values being compared must be normalized for this function to return the correct result.

func (*FieldVal) Inverse

func (f *FieldVal) Inverse() *FieldVal

Inverse finds the modular multiplicative inverse of the field value. The existing field value is modified.

The field value is returned to support chaining. This enables syntax like: f.Inverse().Mul(f2) so that f = f^-1 * f2.

func (*FieldVal) IsOdd

func (f *FieldVal) IsOdd() bool

IsOdd returns whether or not the field value is an odd number.

The field value must be normalized for this function to return correct result.

func (*FieldVal) IsZero

func (f *FieldVal) IsZero() bool

IsZero returns whether or not the field value is equal to zero.

func (*FieldVal) Mul

func (f *FieldVal) Mul(val *FieldVal) *FieldVal

Mul multiplies the passed value to the existing field value and stores the result in f. Note that this function can overflow if multiplying any of the individual words exceeds a max uint32. In practice, this means the magnitude of either value involved in the multiplication must be a max of 8.

The field value is returned to support chaining. This enables syntax like: f.Mul(f2).AddInt(1) so that f = (f * f2) + 1.

func (*FieldVal) Mul2

func (f *FieldVal) Mul2(val *FieldVal, val2 *FieldVal) *FieldVal

Mul2 multiplies the passed two field values together and stores the result result in f. Note that this function can overflow if multiplying any of the individual words exceeds a max uint32. In practice, this means the magnitude of either value involved in the multiplication must be a max of 8.

The field value is returned to support chaining. This enables syntax like: f3.Mul2(f, f2).AddInt(1) so that f3 = (f * f2) + 1.

func (*FieldVal) MulInt

func (f *FieldVal) MulInt(val uint) *FieldVal

MulInt multiplies the field value by the passed int and stores the result in f. Note that this function can overflow if multiplying the value by any of the individual words exceeds a max uint32. Therefore it is important that the caller ensures no overflows will occur before using this function.

The field value is returned to support chaining. This enables syntax like: f.MulInt(2).Add(f2) so that f = 2 * f + f2.

func (*FieldVal) Negate

func (f *FieldVal) Negate(magnitude uint32) *FieldVal

Negate negates the field value. The existing field value is modified. The caller must provide the magnitude of the field value for a correct result.

The field value is returned to support chaining. This enables syntax like: f.Negate().AddInt(1) so that f = -f + 1.

func (*FieldVal) NegateVal

func (f *FieldVal) NegateVal(val *FieldVal, magnitude uint32) *FieldVal

NegateVal negates the passed value and stores the result in f. The caller must provide the magnitude of the passed value for a correct result.

The field value is returned to support chaining. This enables syntax like: f.NegateVal(f2).AddInt(1) so that f = -f2 + 1.

func (*FieldVal) Normalize

func (f *FieldVal) Normalize() *FieldVal

Normalize normalizes the internal field words into the desired range and performs fast modular reduction over the secp256k1 prime by making use of the special form of the prime.

func (*FieldVal) PutBytes

func (f *FieldVal) PutBytes(b *[32]byte)

PutBytes unpacks the field value to a 32-byte big-endian value using the passed byte array. There is a similar function, Bytes, which unpacks the field value into a new array and returns that. This version is provided since it can be useful to cut down on the number of allocations by allowing the caller to reuse a buffer.

The field value must be normalized for this function to return the correct result.

func (*FieldVal) Set

func (f *FieldVal) Set(val *FieldVal) *FieldVal

Set sets the field value equal to the passed value.

The field value is returned to support chaining. This enables syntax like: f := new(FieldVal).Set(f2).Add(1) so that f = f2 + 1 where f2 is not modified.

func (*FieldVal) SetByteSlice

func (f *FieldVal) SetByteSlice(b []byte) *FieldVal

SetByteSlice packs the passed big-endian value into the internal field value representation. Only the first 32-bytes are used. As a result, it is up to the caller to ensure numbers of the appropriate size are used or the value will be truncated.

The field value is returned to support chaining. This enables syntax like: f := new(FieldVal).SetByteSlice(byteSlice)

func (*FieldVal) SetBytes

func (f *FieldVal) SetBytes(b *[32]byte) *FieldVal

SetBytes packs the passed 32-byte big-endian value into the internal field value representation.

The field value is returned to support chaining. This enables syntax like: f := new(FieldVal).SetBytes(byteArray).Mul(f2) so that f = ba * f2.

func (*FieldVal) SetHex

func (f *FieldVal) SetHex(hexString string) *FieldVal

SetHex decodes the passed big-endian hex string into the internal field value representation. Only the first 32-bytes are used.

The field value is returned to support chaining. This enables syntax like: f := new(FieldVal).SetHex("0abc").Add(1) so that f = 0x0abc + 1

func (*FieldVal) SetInt

func (f *FieldVal) SetInt(ui uint) *FieldVal

SetInt sets the field value to the passed integer. This is a convenience function since it is fairly common to perform some arithemetic with small native integers.

The field value is returned to support chaining. This enables syntax such as f := new(FieldVal).SetInt(2).Mul(f2) so that f = 2 * f2.

func (*FieldVal) Square

func (f *FieldVal) Square() *FieldVal

Square squares the field value. The existing field value is modified. Note that this function can overflow if multiplying any of the individual words exceeds a max uint32. In practice, this means the magnitude of the field must be a max of 8 to prevent overflow.

The field value is returned to support chaining. This enables syntax like: f.Square().Mul(f2) so that f = f^2 * f2.

func (*FieldVal) SquareVal

func (f *FieldVal) SquareVal(val *FieldVal) *FieldVal

SquareVal squares the passed value and stores the result in f. Note that this function can overflow if multiplying any of the individual words exceeds a max uint32. In practice, this means the magnitude of the field being squred must be a max of 8 to prevent overflow.

The field value is returned to support chaining. This enables syntax like: f3.SquareVal(f).Mul(f) so that f3 = f^2 * f = f^3.

func (FieldVal) String

func (f FieldVal) String() string

String returns the field value as a human-readable hex string.

func (*FieldVal) Zero

func (f *FieldVal) Zero()

Zero sets the field value to zero. A newly created field value is already set to zero. This function can be useful to clear an existing field value for reuse.

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) AddJacobian

func (curve *KoblitzCurve) AddJacobian(x1, y1, z1, x2, y2, z2, x3, y3, z3 *FieldVal)

AddJacobian adds the passed Jacobian points (x1, y1, z1) and (x2, y2, z2) together and stores the result in (x3, y3, z3).

func (*KoblitzCurve) BigAffineToField

func (curve *KoblitzCurve) BigAffineToField(x, y *big.Int) (*FieldVal, *FieldVal)

BigAffineToField takes an affine point (x, y) as big integers and converts it to an affine point as field values.

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) FieldJacobianToBigAffine

func (curve *KoblitzCurve) FieldJacobianToBigAffine(x, y, z *FieldVal) (*big.Int, *big.Int)

FieldJacobianToBigAffine takes a Jacobian point (x, y, z) as field values and converts it to an affine point as big integers.

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 GeneratePrivateKey

func GeneratePrivateKey(curve *KoblitzCurve) (*PrivateKey, error)

GeneratePrivateKey is a wrapper for ecdsa.GenerateKey that returns a PrivateKey instead of the normal ecdsa.PrivateKey.

func NewPrivateKey

func NewPrivateKey(curve *KoblitzCurve, d *big.Int) *PrivateKey

NewPrivateKey instantiates a new private key from a scalar encoded as a big integer.

func (PrivateKey) GetD

func (p PrivateKey) GetD() *big.Int

GetD satisfies the chainec PrivateKey interface.

func (PrivateKey) GetType

func (p PrivateKey) GetType() int

GetType satisfies the chainec PrivateKey interface.

func (PrivateKey) Public

func (p PrivateKey) Public() (*big.Int, *big.Int)

Public returns the PublicKey corresponding to this private key.

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) SerializeSecret

func (p PrivateKey) SerializeSecret() []byte

SerializeSecret satisfies the chainec PrivateKey interface.

func (*PrivateKey) Sign

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

Sign generates an ECDSA signature for the provided hash (which should be the result of hashing a larger message) using the private key. Produced signature is deterministic (same message and same key yield the same signature) and canonical in accordance with RFC6979 and BIP0062.

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 NewPublicKey

func NewPublicKey(curve *KoblitzCurve, x *big.Int, y *big.Int) *PublicKey

NewPublicKey instantiates a new public key with the given X,Y coordinates.

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 RecoverCompact

func RecoverCompact(curve *KoblitzCurve, signature,
	hash []byte) (*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 (PublicKey) GetCurve

func (p PublicKey) GetCurve() interface{}

GetCurve satisfies the chainec PublicKey interface.

func (PublicKey) GetType

func (p PublicKey) GetType() int

GetType satisfies the chainec PublicKey interface.

func (PublicKey) GetX

func (p PublicKey) GetX() *big.Int

GetX satisfies the chainec PublicKey interface.

func (PublicKey) GetY

func (p PublicKey) GetY() *big.Int

GetY satisfies the chainec PublicKey interface.

func (PublicKey) Serialize

func (p PublicKey) Serialize() []byte

Serialize serializes a public key in a 33-byte compressed format. It is the default serialization method.

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 NewSignature

func NewSignature(r, s *big.Int) *Signature

NewSignature instantiates a new signature given some R,S values.

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) GetR

func (sig Signature) GetR() *big.Int

GetR satisfies the chainec PublicKey interface.

func (Signature) GetS

func (sig Signature) GetS() *big.Int

GetS satisfies the chainec PublicKey interface.

func (Signature) GetType

func (sig Signature) GetType() int

GetType satisfies the chainec Signature interface.

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 Decred 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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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