diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 13:16:40 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 13:16:40 +0000 |
commit | 47ab3d4a42e9ab51c465c4322d2ec233f6324e6b (patch) | |
tree | a61a0ffd83f4a3def4b36e5c8e99630c559aa723 /src/crypto/ecdsa | |
parent | Initial commit. (diff) | |
download | golang-1.18-47ab3d4a42e9ab51c465c4322d2ec233f6324e6b.tar.xz golang-1.18-47ab3d4a42e9ab51c465c4322d2ec233f6324e6b.zip |
Adding upstream version 1.18.10.upstream/1.18.10upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/crypto/ecdsa')
-rw-r--r-- | src/crypto/ecdsa/ecdsa.go | 368 | ||||
-rw-r--r-- | src/crypto/ecdsa/ecdsa_noasm.go | 21 | ||||
-rw-r--r-- | src/crypto/ecdsa/ecdsa_s390x.go | 163 | ||||
-rw-r--r-- | src/crypto/ecdsa/ecdsa_s390x.s | 28 | ||||
-rw-r--r-- | src/crypto/ecdsa/ecdsa_s390x_test.go | 32 | ||||
-rw-r--r-- | src/crypto/ecdsa/ecdsa_test.go | 401 | ||||
-rw-r--r-- | src/crypto/ecdsa/equal_test.go | 75 | ||||
-rw-r--r-- | src/crypto/ecdsa/example_test.go | 32 | ||||
-rw-r--r-- | src/crypto/ecdsa/testdata/SigVer.rsp.bz2 | bin | 0 -> 95485 bytes |
9 files changed, 1120 insertions, 0 deletions
diff --git a/src/crypto/ecdsa/ecdsa.go b/src/crypto/ecdsa/ecdsa.go new file mode 100644 index 0000000..9f9a09a --- /dev/null +++ b/src/crypto/ecdsa/ecdsa.go @@ -0,0 +1,368 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as +// defined in FIPS 186-4 and SEC 1, Version 2.0. +// +// Signatures generated by this package are not deterministic, but entropy is +// mixed with the private key and the message, achieving the same level of +// security in case of randomness source failure. +package ecdsa + +// [FIPS 186-4] references ANSI X9.62-2005 for the bulk of the ECDSA algorithm. +// That standard is not freely available, which is a problem in an open source +// implementation, because not only the implementer, but also any maintainer, +// contributor, reviewer, auditor, and learner needs access to it. Instead, this +// package references and follows the equivalent [SEC 1, Version 2.0]. +// +// [FIPS 186-4]: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf +// [SEC 1, Version 2.0]: https://www.secg.org/sec1-v2.pdf + +import ( + "crypto" + "crypto/aes" + "crypto/cipher" + "crypto/elliptic" + "crypto/internal/randutil" + "crypto/sha512" + "errors" + "io" + "math/big" + + "golang.org/x/crypto/cryptobyte" + "golang.org/x/crypto/cryptobyte/asn1" +) + +// A invertible implements fast inverse in GF(N). +type invertible interface { + // Inverse returns the inverse of k mod Params().N. + Inverse(k *big.Int) *big.Int +} + +// A combinedMult implements fast combined multiplication for verification. +type combinedMult interface { + // CombinedMult returns [s1]G + [s2]P where G is the generator. + CombinedMult(Px, Py *big.Int, s1, s2 []byte) (x, y *big.Int) +} + +const ( + aesIV = "IV for ECDSA CTR" +) + +// PublicKey represents an ECDSA public key. +type PublicKey struct { + elliptic.Curve + X, Y *big.Int +} + +// Any methods implemented on PublicKey might need to also be implemented on +// PrivateKey, as the latter embeds the former and will expose its methods. + +// Equal reports whether pub and x have the same value. +// +// Two keys are only considered to have the same value if they have the same Curve value. +// Note that for example elliptic.P256() and elliptic.P256().Params() are different +// values, as the latter is a generic not constant time implementation. +func (pub *PublicKey) Equal(x crypto.PublicKey) bool { + xx, ok := x.(*PublicKey) + if !ok { + return false + } + return pub.X.Cmp(xx.X) == 0 && pub.Y.Cmp(xx.Y) == 0 && + // Standard library Curve implementations are singletons, so this check + // will work for those. Other Curves might be equivalent even if not + // singletons, but there is no definitive way to check for that, and + // better to err on the side of safety. + pub.Curve == xx.Curve +} + +// PrivateKey represents an ECDSA private key. +type PrivateKey struct { + PublicKey + D *big.Int +} + +// Public returns the public key corresponding to priv. +func (priv *PrivateKey) Public() crypto.PublicKey { + return &priv.PublicKey +} + +// Equal reports whether priv and x have the same value. +// +// See PublicKey.Equal for details on how Curve is compared. +func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool { + xx, ok := x.(*PrivateKey) + if !ok { + return false + } + return priv.PublicKey.Equal(&xx.PublicKey) && priv.D.Cmp(xx.D) == 0 +} + +// Sign signs digest with priv, reading randomness from rand. The opts argument +// is not currently used but, in keeping with the crypto.Signer interface, +// should be the hash function used to digest the message. +// +// This method implements crypto.Signer, which is an interface to support keys +// where the private part is kept in, for example, a hardware module. Common +// uses can use the SignASN1 function in this package directly. +func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { + r, s, err := Sign(rand, priv, digest) + if err != nil { + return nil, err + } + + var b cryptobyte.Builder + b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) { + b.AddASN1BigInt(r) + b.AddASN1BigInt(s) + }) + return b.Bytes() +} + +var one = new(big.Int).SetInt64(1) + +// randFieldElement returns a random element of the order of the given +// curve using the procedure given in FIPS 186-4, Appendix B.5.1. +func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) { + params := c.Params() + // Note that for P-521 this will actually be 63 bits more than the order, as + // division rounds down, but the extra bit is inconsequential. + b := make([]byte, params.BitSize/8+8) // TODO: use params.N.BitLen() + _, err = io.ReadFull(rand, b) + if err != nil { + return + } + + k = new(big.Int).SetBytes(b) + n := new(big.Int).Sub(params.N, one) + k.Mod(k, n) + k.Add(k, one) + return +} + +// GenerateKey generates a public and private key pair. +func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) { + k, err := randFieldElement(c, rand) + if err != nil { + return nil, err + } + + priv := new(PrivateKey) + priv.PublicKey.Curve = c + priv.D = k + priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes()) + return priv, nil +} + +// hashToInt converts a hash value to an integer. Per FIPS 186-4, Section 6.4, +// we use the left-most bits of the hash to match the bit-length of the order of +// the curve. This also performs Step 5 of SEC 1, Version 2.0, Section 4.1.3. +func hashToInt(hash []byte, c elliptic.Curve) *big.Int { + orderBits := c.Params().N.BitLen() + orderBytes := (orderBits + 7) / 8 + if len(hash) > orderBytes { + hash = hash[:orderBytes] + } + + ret := new(big.Int).SetBytes(hash) + excess := len(hash)*8 - orderBits + if excess > 0 { + ret.Rsh(ret, uint(excess)) + } + return ret +} + +// fermatInverse calculates the inverse of k in GF(P) using Fermat's method +// (exponentiation modulo P - 2, per Euler's theorem). This has better +// constant-time properties than Euclid's method (implemented in +// math/big.Int.ModInverse and FIPS 186-4, Appendix C.1) although math/big +// itself isn't strictly constant-time so it's not perfect. +func fermatInverse(k, N *big.Int) *big.Int { + two := big.NewInt(2) + nMinus2 := new(big.Int).Sub(N, two) + return new(big.Int).Exp(k, nMinus2, N) +} + +var errZeroParam = errors.New("zero parameter") + +// Sign signs a hash (which should be the result of hashing a larger message) +// using the private key, priv. If the hash is longer than the bit-length of the +// private key's curve order, the hash will be truncated to that length. It +// returns the signature as a pair of integers. Most applications should use +// SignASN1 instead of dealing directly with r, s. +func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) { + randutil.MaybeReadByte(rand) + + // This implementation derives the nonce from an AES-CTR CSPRNG keyed by: + // + // SHA2-512(priv.D || entropy || hash)[:32] + // + // The CSPRNG key is indifferentiable from a random oracle as shown in + // [Coron], the AES-CTR stream is indifferentiable from a random oracle + // under standard cryptographic assumptions (see [Larsson] for examples). + // + // [Coron]: https://cs.nyu.edu/~dodis/ps/merkle.pdf + // [Larsson]: https://web.archive.org/web/20040719170906/https://www.nada.kth.se/kurser/kth/2D1441/semteo03/lecturenotes/assump.pdf + + // Get 256 bits of entropy from rand. + entropy := make([]byte, 32) + _, err = io.ReadFull(rand, entropy) + if err != nil { + return + } + + // Initialize an SHA-512 hash context; digest... + md := sha512.New() + md.Write(priv.D.Bytes()) // the private key, + md.Write(entropy) // the entropy, + md.Write(hash) // and the input hash; + key := md.Sum(nil)[:32] // and compute ChopMD-256(SHA-512), + // which is an indifferentiable MAC. + + // Create an AES-CTR instance to use as a CSPRNG. + block, err := aes.NewCipher(key) + if err != nil { + return nil, nil, err + } + + // Create a CSPRNG that xors a stream of zeros with + // the output of the AES-CTR instance. + csprng := cipher.StreamReader{ + R: zeroReader, + S: cipher.NewCTR(block, []byte(aesIV)), + } + + c := priv.PublicKey.Curve + return sign(priv, &csprng, c, hash) +} + +func signGeneric(priv *PrivateKey, csprng *cipher.StreamReader, c elliptic.Curve, hash []byte) (r, s *big.Int, err error) { + // SEC 1, Version 2.0, Section 4.1.3 + N := c.Params().N + if N.Sign() == 0 { + return nil, nil, errZeroParam + } + var k, kInv *big.Int + for { + for { + k, err = randFieldElement(c, *csprng) + if err != nil { + r = nil + return + } + + if in, ok := priv.Curve.(invertible); ok { + kInv = in.Inverse(k) + } else { + kInv = fermatInverse(k, N) // N != 0 + } + + r, _ = priv.Curve.ScalarBaseMult(k.Bytes()) + r.Mod(r, N) + if r.Sign() != 0 { + break + } + } + + e := hashToInt(hash, c) + s = new(big.Int).Mul(priv.D, r) + s.Add(s, e) + s.Mul(s, kInv) + s.Mod(s, N) // N != 0 + if s.Sign() != 0 { + break + } + } + + return +} + +// SignASN1 signs a hash (which should be the result of hashing a larger message) +// using the private key, priv. If the hash is longer than the bit-length of the +// private key's curve order, the hash will be truncated to that length. It +// returns the ASN.1 encoded signature. +func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) { + return priv.Sign(rand, hash, nil) +} + +// Verify verifies the signature in r, s of hash using the public key, pub. Its +// return value records whether the signature is valid. Most applications should +// use VerifyASN1 instead of dealing directly with r, s. +func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool { + c := pub.Curve + N := c.Params().N + + if r.Sign() <= 0 || s.Sign() <= 0 { + return false + } + if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 { + return false + } + return verify(pub, c, hash, r, s) +} + +func verifyGeneric(pub *PublicKey, c elliptic.Curve, hash []byte, r, s *big.Int) bool { + // SEC 1, Version 2.0, Section 4.1.4 + e := hashToInt(hash, c) + var w *big.Int + N := c.Params().N + if in, ok := c.(invertible); ok { + w = in.Inverse(s) + } else { + w = new(big.Int).ModInverse(s, N) + } + + u1 := e.Mul(e, w) + u1.Mod(u1, N) + u2 := w.Mul(r, w) + u2.Mod(u2, N) + + // Check if implements S1*g + S2*p + var x, y *big.Int + if opt, ok := c.(combinedMult); ok { + x, y = opt.CombinedMult(pub.X, pub.Y, u1.Bytes(), u2.Bytes()) + } else { + x1, y1 := c.ScalarBaseMult(u1.Bytes()) + x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes()) + x, y = c.Add(x1, y1, x2, y2) + } + + if x.Sign() == 0 && y.Sign() == 0 { + return false + } + x.Mod(x, N) + return x.Cmp(r) == 0 +} + +// VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the +// public key, pub. Its return value records whether the signature is valid. +func VerifyASN1(pub *PublicKey, hash, sig []byte) bool { + var ( + r, s = &big.Int{}, &big.Int{} + inner cryptobyte.String + ) + input := cryptobyte.String(sig) + if !input.ReadASN1(&inner, asn1.SEQUENCE) || + !input.Empty() || + !inner.ReadASN1Integer(r) || + !inner.ReadASN1Integer(s) || + !inner.Empty() { + return false + } + return Verify(pub, hash, r, s) +} + +type zr struct { + io.Reader +} + +// Read replaces the contents of dst with zeros. +func (z *zr) Read(dst []byte) (n int, err error) { + for i := range dst { + dst[i] = 0 + } + return len(dst), nil +} + +var zeroReader = &zr{} diff --git a/src/crypto/ecdsa/ecdsa_noasm.go b/src/crypto/ecdsa/ecdsa_noasm.go new file mode 100644 index 0000000..7fbca10 --- /dev/null +++ b/src/crypto/ecdsa/ecdsa_noasm.go @@ -0,0 +1,21 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !s390x + +package ecdsa + +import ( + "crypto/cipher" + "crypto/elliptic" + "math/big" +) + +func sign(priv *PrivateKey, csprng *cipher.StreamReader, c elliptic.Curve, hash []byte) (r, s *big.Int, err error) { + return signGeneric(priv, csprng, c, hash) +} + +func verify(pub *PublicKey, c elliptic.Curve, hash []byte, r, s *big.Int) bool { + return verifyGeneric(pub, c, hash, r, s) +} diff --git a/src/crypto/ecdsa/ecdsa_s390x.go b/src/crypto/ecdsa/ecdsa_s390x.go new file mode 100644 index 0000000..1480d1b --- /dev/null +++ b/src/crypto/ecdsa/ecdsa_s390x.go @@ -0,0 +1,163 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ecdsa + +import ( + "crypto/cipher" + "crypto/elliptic" + "internal/cpu" + "math/big" +) + +// kdsa invokes the "compute digital signature authentication" +// instruction with the given function code and 4096 byte +// parameter block. +// +// The return value corresponds to the condition code set by the +// instruction. Interrupted invocations are handled by the +// function. +//go:noescape +func kdsa(fc uint64, params *[4096]byte) (errn uint64) + +// testingDisableKDSA forces the generic fallback path. It must only be set in tests. +var testingDisableKDSA bool + +// canUseKDSA checks if KDSA instruction is available, and if it is, it checks +// the name of the curve to see if it matches the curves supported(P-256, P-384, P-521). +// Then, based on the curve name, a function code and a block size will be assigned. +// If KDSA instruction is not available or if the curve is not supported, canUseKDSA +// will set ok to false. +func canUseKDSA(c elliptic.Curve) (functionCode uint64, blockSize int, ok bool) { + if testingDisableKDSA { + return 0, 0, false + } + if !cpu.S390X.HasECDSA { + return 0, 0, false + } + switch c.Params().Name { + case "P-256": + return 1, 32, true + case "P-384": + return 2, 48, true + case "P-521": + return 3, 80, true + } + return 0, 0, false // A mismatch +} + +func hashToBytes(dst, hash []byte, c elliptic.Curve) { + l := len(dst) + if n := c.Params().N.BitLen(); n == l*8 { + // allocation free path for curves with a length that is a whole number of bytes + if len(hash) >= l { + // truncate hash + copy(dst, hash[:l]) + return + } + // pad hash with leading zeros + p := l - len(hash) + for i := 0; i < p; i++ { + dst[i] = 0 + } + copy(dst[p:], hash) + return + } + // TODO(mundaym): avoid hashToInt call here + hashToInt(hash, c).FillBytes(dst) +} + +func sign(priv *PrivateKey, csprng *cipher.StreamReader, c elliptic.Curve, hash []byte) (r, s *big.Int, err error) { + if functionCode, blockSize, ok := canUseKDSA(c); ok { + for { + var k *big.Int + k, err = randFieldElement(c, *csprng) + if err != nil { + return nil, nil, err + } + + // The parameter block looks like the following for sign. + // +---------------------+ + // | Signature(R) | + // +---------------------+ + // | Signature(S) | + // +---------------------+ + // | Hashed Message | + // +---------------------+ + // | Private Key | + // +---------------------+ + // | Random Number | + // +---------------------+ + // | | + // | ... | + // | | + // +---------------------+ + // The common components(signatureR, signatureS, hashedMessage, privateKey and + // random number) each takes block size of bytes. The block size is different for + // different curves and is set by canUseKDSA function. + var params [4096]byte + + // Copy content into the parameter block. In the sign case, + // we copy hashed message, private key and random number into + // the parameter block. + hashToBytes(params[2*blockSize:3*blockSize], hash, c) + priv.D.FillBytes(params[3*blockSize : 4*blockSize]) + k.FillBytes(params[4*blockSize : 5*blockSize]) + // Convert verify function code into a sign function code by adding 8. + // We also need to set the 'deterministic' bit in the function code, by + // adding 128, in order to stop the instruction using its own random number + // generator in addition to the random number we supply. + switch kdsa(functionCode+136, ¶ms) { + case 0: // success + r = new(big.Int) + r.SetBytes(params[:blockSize]) + s = new(big.Int) + s.SetBytes(params[blockSize : 2*blockSize]) + return + case 1: // error + return nil, nil, errZeroParam + case 2: // retry + continue + } + panic("unreachable") + } + } + return signGeneric(priv, csprng, c, hash) +} + +func verify(pub *PublicKey, c elliptic.Curve, hash []byte, r, s *big.Int) bool { + if functionCode, blockSize, ok := canUseKDSA(c); ok { + // The parameter block looks like the following for verify: + // +---------------------+ + // | Signature(R) | + // +---------------------+ + // | Signature(S) | + // +---------------------+ + // | Hashed Message | + // +---------------------+ + // | Public Key X | + // +---------------------+ + // | Public Key Y | + // +---------------------+ + // | | + // | ... | + // | | + // +---------------------+ + // The common components(signatureR, signatureS, hashed message, public key X, + // and public key Y) each takes block size of bytes. The block size is different for + // different curves and is set by canUseKDSA function. + var params [4096]byte + + // Copy content into the parameter block. In the verify case, + // we copy signature (r), signature(s), hashed message, public key x component, + // and public key y component into the parameter block. + r.FillBytes(params[0*blockSize : 1*blockSize]) + s.FillBytes(params[1*blockSize : 2*blockSize]) + hashToBytes(params[2*blockSize:3*blockSize], hash, c) + pub.X.FillBytes(params[3*blockSize : 4*blockSize]) + pub.Y.FillBytes(params[4*blockSize : 5*blockSize]) + return kdsa(functionCode, ¶ms) == 0 + } + return verifyGeneric(pub, c, hash, r, s) +} diff --git a/src/crypto/ecdsa/ecdsa_s390x.s b/src/crypto/ecdsa/ecdsa_s390x.s new file mode 100644 index 0000000..ba5b3bf --- /dev/null +++ b/src/crypto/ecdsa/ecdsa_s390x.s @@ -0,0 +1,28 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "textflag.h" + +// func kdsa(fc uint64, params *[4096]byte) (errn uint64) +TEXT ·kdsa(SB), NOSPLIT|NOFRAME, $0-24 + MOVD fc+0(FP), R0 // function code + MOVD params+8(FP), R1 // address parameter block + +loop: + WORD $0xB93A0008 // compute digital signature authentication + BVS loop // branch back if interrupted + BGT retry // signing unsuccessful, but retry with new CSPRN + BLT error // condition code of 1 indicates a failure + +success: + MOVD $0, errn+16(FP) // return 0 - sign/verify was successful + RET + +error: + MOVD $1, errn+16(FP) // return 1 - sign/verify failed + RET + +retry: + MOVD $2, errn+16(FP) // return 2 - sign/verify was unsuccessful -- if sign, retry with new RN + RET diff --git a/src/crypto/ecdsa/ecdsa_s390x_test.go b/src/crypto/ecdsa/ecdsa_s390x_test.go new file mode 100644 index 0000000..fd1dc7c --- /dev/null +++ b/src/crypto/ecdsa/ecdsa_s390x_test.go @@ -0,0 +1,32 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build s390x + +package ecdsa + +import ( + "crypto/elliptic" + "testing" +) + +func TestNoAsm(t *testing.T) { + testingDisableKDSA = true + defer func() { testingDisableKDSA = false }() + + curves := [...]elliptic.Curve{ + elliptic.P256(), + elliptic.P384(), + elliptic.P521(), + } + + for _, curve := range curves { + name := curve.Params().Name + t.Run(name, func(t *testing.T) { testKeyGeneration(t, curve) }) + t.Run(name, func(t *testing.T) { testSignAndVerify(t, curve) }) + t.Run(name, func(t *testing.T) { testNonceSafety(t, curve) }) + t.Run(name, func(t *testing.T) { testINDCCA(t, curve) }) + t.Run(name, func(t *testing.T) { testNegativeInputs(t, curve) }) + } +} diff --git a/src/crypto/ecdsa/ecdsa_test.go b/src/crypto/ecdsa/ecdsa_test.go new file mode 100644 index 0000000..c8390b2 --- /dev/null +++ b/src/crypto/ecdsa/ecdsa_test.go @@ -0,0 +1,401 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ecdsa + +import ( + "bufio" + "compress/bzip2" + "crypto/elliptic" + "crypto/rand" + "crypto/sha1" + "crypto/sha256" + "crypto/sha512" + "encoding/hex" + "hash" + "io" + "math/big" + "os" + "strings" + "testing" +) + +func testAllCurves(t *testing.T, f func(*testing.T, elliptic.Curve)) { + tests := []struct { + name string + curve elliptic.Curve + }{ + {"P256", elliptic.P256()}, + {"P224", elliptic.P224()}, + {"P384", elliptic.P384()}, + {"P521", elliptic.P521()}, + } + if testing.Short() { + tests = tests[:1] + } + for _, test := range tests { + curve := test.curve + t.Run(test.name, func(t *testing.T) { + t.Parallel() + f(t, curve) + }) + } +} + +func TestKeyGeneration(t *testing.T) { + testAllCurves(t, testKeyGeneration) +} + +func testKeyGeneration(t *testing.T, c elliptic.Curve) { + priv, err := GenerateKey(c, rand.Reader) + if err != nil { + t.Fatal(err) + } + if !c.IsOnCurve(priv.PublicKey.X, priv.PublicKey.Y) { + t.Errorf("public key invalid: %s", err) + } +} + +func TestSignAndVerify(t *testing.T) { + testAllCurves(t, testSignAndVerify) +} + +func testSignAndVerify(t *testing.T, c elliptic.Curve) { + priv, _ := GenerateKey(c, rand.Reader) + + hashed := []byte("testing") + r, s, err := Sign(rand.Reader, priv, hashed) + if err != nil { + t.Errorf("error signing: %s", err) + return + } + + if !Verify(&priv.PublicKey, hashed, r, s) { + t.Errorf("Verify failed") + } + + hashed[0] ^= 0xff + if Verify(&priv.PublicKey, hashed, r, s) { + t.Errorf("Verify always works!") + } +} + +func TestSignAndVerifyASN1(t *testing.T) { + testAllCurves(t, testSignAndVerifyASN1) +} + +func testSignAndVerifyASN1(t *testing.T, c elliptic.Curve) { + priv, _ := GenerateKey(c, rand.Reader) + + hashed := []byte("testing") + sig, err := SignASN1(rand.Reader, priv, hashed) + if err != nil { + t.Errorf("error signing: %s", err) + return + } + + if !VerifyASN1(&priv.PublicKey, hashed, sig) { + t.Errorf("VerifyASN1 failed") + } + + hashed[0] ^= 0xff + if VerifyASN1(&priv.PublicKey, hashed, sig) { + t.Errorf("VerifyASN1 always works!") + } +} + +func TestNonceSafety(t *testing.T) { + testAllCurves(t, testNonceSafety) +} + +func testNonceSafety(t *testing.T, c elliptic.Curve) { + priv, _ := GenerateKey(c, rand.Reader) + + hashed := []byte("testing") + r0, s0, err := Sign(zeroReader, priv, hashed) + if err != nil { + t.Errorf("error signing: %s", err) + return + } + + hashed = []byte("testing...") + r1, s1, err := Sign(zeroReader, priv, hashed) + if err != nil { + t.Errorf("error signing: %s", err) + return + } + + if s0.Cmp(s1) == 0 { + // This should never happen. + t.Errorf("the signatures on two different messages were the same") + } + + if r0.Cmp(r1) == 0 { + t.Errorf("the nonce used for two different messages was the same") + } +} + +func TestINDCCA(t *testing.T) { + testAllCurves(t, testINDCCA) +} + +func testINDCCA(t *testing.T, c elliptic.Curve) { + priv, _ := GenerateKey(c, rand.Reader) + + hashed := []byte("testing") + r0, s0, err := Sign(rand.Reader, priv, hashed) + if err != nil { + t.Errorf("error signing: %s", err) + return + } + + r1, s1, err := Sign(rand.Reader, priv, hashed) + if err != nil { + t.Errorf("error signing: %s", err) + return + } + + if s0.Cmp(s1) == 0 { + t.Errorf("two signatures of the same message produced the same result") + } + + if r0.Cmp(r1) == 0 { + t.Errorf("two signatures of the same message produced the same nonce") + } +} + +func fromHex(s string) *big.Int { + r, ok := new(big.Int).SetString(s, 16) + if !ok { + panic("bad hex") + } + return r +} + +func TestVectors(t *testing.T) { + // This test runs the full set of NIST test vectors from + // https://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3ecdsatestvectors.zip + // + // The SigVer.rsp file has been edited to remove test vectors for + // unsupported algorithms and has been compressed. + + if testing.Short() { + return + } + + f, err := os.Open("testdata/SigVer.rsp.bz2") + if err != nil { + t.Fatal(err) + } + + buf := bufio.NewReader(bzip2.NewReader(f)) + + lineNo := 1 + var h hash.Hash + var msg []byte + var hashed []byte + var r, s *big.Int + pub := new(PublicKey) + + for { + line, err := buf.ReadString('\n') + if len(line) == 0 { + if err == io.EOF { + break + } + t.Fatalf("error reading from input: %s", err) + } + lineNo++ + // Need to remove \r\n from the end of the line. + if !strings.HasSuffix(line, "\r\n") { + t.Fatalf("bad line ending (expected \\r\\n) on line %d", lineNo) + } + line = line[:len(line)-2] + + if len(line) == 0 || line[0] == '#' { + continue + } + + if line[0] == '[' { + line = line[1 : len(line)-1] + curve, hash, _ := strings.Cut(line, ",") + + switch curve { + case "P-224": + pub.Curve = elliptic.P224() + case "P-256": + pub.Curve = elliptic.P256() + case "P-384": + pub.Curve = elliptic.P384() + case "P-521": + pub.Curve = elliptic.P521() + default: + pub.Curve = nil + } + + switch hash { + case "SHA-1": + h = sha1.New() + case "SHA-224": + h = sha256.New224() + case "SHA-256": + h = sha256.New() + case "SHA-384": + h = sha512.New384() + case "SHA-512": + h = sha512.New() + default: + h = nil + } + + continue + } + + if h == nil || pub.Curve == nil { + continue + } + + switch { + case strings.HasPrefix(line, "Msg = "): + if msg, err = hex.DecodeString(line[6:]); err != nil { + t.Fatalf("failed to decode message on line %d: %s", lineNo, err) + } + case strings.HasPrefix(line, "Qx = "): + pub.X = fromHex(line[5:]) + case strings.HasPrefix(line, "Qy = "): + pub.Y = fromHex(line[5:]) + case strings.HasPrefix(line, "R = "): + r = fromHex(line[4:]) + case strings.HasPrefix(line, "S = "): + s = fromHex(line[4:]) + case strings.HasPrefix(line, "Result = "): + expected := line[9] == 'P' + h.Reset() + h.Write(msg) + hashed := h.Sum(hashed[:0]) + if Verify(pub, hashed, r, s) != expected { + t.Fatalf("incorrect result on line %d", lineNo) + } + default: + t.Fatalf("unknown variable on line %d: %s", lineNo, line) + } + } +} + +func TestNegativeInputs(t *testing.T) { + testAllCurves(t, testNegativeInputs) +} + +func testNegativeInputs(t *testing.T, curve elliptic.Curve) { + key, err := GenerateKey(curve, rand.Reader) + if err != nil { + t.Errorf("failed to generate key") + } + + var hash [32]byte + r := new(big.Int).SetInt64(1) + r.Lsh(r, 550 /* larger than any supported curve */) + r.Neg(r) + + if Verify(&key.PublicKey, hash[:], r, r) { + t.Errorf("bogus signature accepted") + } +} + +func TestZeroHashSignature(t *testing.T) { + testAllCurves(t, testZeroHashSignature) +} + +func testZeroHashSignature(t *testing.T, curve elliptic.Curve) { + zeroHash := make([]byte, 64) + + privKey, err := GenerateKey(curve, rand.Reader) + if err != nil { + panic(err) + } + + // Sign a hash consisting of all zeros. + r, s, err := Sign(rand.Reader, privKey, zeroHash) + if err != nil { + panic(err) + } + + // Confirm that it can be verified. + if !Verify(&privKey.PublicKey, zeroHash, r, s) { + t.Errorf("zero hash signature verify failed for %T", curve) + } +} + +func benchmarkAllCurves(t *testing.B, f func(*testing.B, elliptic.Curve)) { + tests := []struct { + name string + curve elliptic.Curve + }{ + {"P256", elliptic.P256()}, + {"P224", elliptic.P224()}, + {"P384", elliptic.P384()}, + {"P521", elliptic.P521()}, + } + for _, test := range tests { + curve := test.curve + t.Run(test.name, func(t *testing.B) { + f(t, curve) + }) + } +} + +func BenchmarkSign(b *testing.B) { + benchmarkAllCurves(b, func(b *testing.B, curve elliptic.Curve) { + priv, err := GenerateKey(curve, rand.Reader) + if err != nil { + b.Fatal(err) + } + hashed := []byte("testing") + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + sig, err := SignASN1(rand.Reader, priv, hashed) + if err != nil { + b.Fatal(err) + } + // Prevent the compiler from optimizing out the operation. + hashed[0] = sig[0] + } + }) +} + +func BenchmarkVerify(b *testing.B) { + benchmarkAllCurves(b, func(b *testing.B, curve elliptic.Curve) { + priv, err := GenerateKey(curve, rand.Reader) + if err != nil { + b.Fatal(err) + } + hashed := []byte("testing") + r, s, err := Sign(rand.Reader, priv, hashed) + if err != nil { + b.Fatal(err) + } + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if !Verify(&priv.PublicKey, hashed, r, s) { + b.Fatal("verify failed") + } + } + }) +} + +func BenchmarkGenerateKey(b *testing.B) { + benchmarkAllCurves(b, func(b *testing.B, curve elliptic.Curve) { + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := GenerateKey(curve, rand.Reader); err != nil { + b.Fatal(err) + } + } + }) +} diff --git a/src/crypto/ecdsa/equal_test.go b/src/crypto/ecdsa/equal_test.go new file mode 100644 index 0000000..53ac850 --- /dev/null +++ b/src/crypto/ecdsa/equal_test.go @@ -0,0 +1,75 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ecdsa_test + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "testing" +) + +func testEqual(t *testing.T, c elliptic.Curve) { + private, _ := ecdsa.GenerateKey(c, rand.Reader) + public := &private.PublicKey + + if !public.Equal(public) { + t.Errorf("public key is not equal to itself: %v", public) + } + if !public.Equal(crypto.Signer(private).Public().(*ecdsa.PublicKey)) { + t.Errorf("private.Public() is not Equal to public: %q", public) + } + if !private.Equal(private) { + t.Errorf("private key is not equal to itself: %v", private) + } + + enc, err := x509.MarshalPKCS8PrivateKey(private) + if err != nil { + t.Fatal(err) + } + decoded, err := x509.ParsePKCS8PrivateKey(enc) + if err != nil { + t.Fatal(err) + } + if !public.Equal(decoded.(crypto.Signer).Public()) { + t.Errorf("public key is not equal to itself after decoding: %v", public) + } + if !private.Equal(decoded) { + t.Errorf("private key is not equal to itself after decoding: %v", private) + } + + other, _ := ecdsa.GenerateKey(c, rand.Reader) + if public.Equal(other.Public()) { + t.Errorf("different public keys are Equal") + } + if private.Equal(other) { + t.Errorf("different private keys are Equal") + } + + // Ensure that keys with the same coordinates but on different curves + // aren't considered Equal. + differentCurve := &ecdsa.PublicKey{} + *differentCurve = *public // make a copy of the public key + if differentCurve.Curve == elliptic.P256() { + differentCurve.Curve = elliptic.P224() + } else { + differentCurve.Curve = elliptic.P256() + } + if public.Equal(differentCurve) { + t.Errorf("public keys with different curves are Equal") + } +} + +func TestEqual(t *testing.T) { + t.Run("P224", func(t *testing.T) { testEqual(t, elliptic.P224()) }) + if testing.Short() { + return + } + t.Run("P256", func(t *testing.T) { testEqual(t, elliptic.P256()) }) + t.Run("P384", func(t *testing.T) { testEqual(t, elliptic.P384()) }) + t.Run("P521", func(t *testing.T) { testEqual(t, elliptic.P521()) }) +} diff --git a/src/crypto/ecdsa/example_test.go b/src/crypto/ecdsa/example_test.go new file mode 100644 index 0000000..652c165 --- /dev/null +++ b/src/crypto/ecdsa/example_test.go @@ -0,0 +1,32 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ecdsa_test + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "fmt" +) + +func Example() { + privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + panic(err) + } + + msg := "hello, world" + hash := sha256.Sum256([]byte(msg)) + + sig, err := ecdsa.SignASN1(rand.Reader, privateKey, hash[:]) + if err != nil { + panic(err) + } + fmt.Printf("signature: %x\n", sig) + + valid := ecdsa.VerifyASN1(&privateKey.PublicKey, hash[:], sig) + fmt.Println("signature verified:", valid) +} diff --git a/src/crypto/ecdsa/testdata/SigVer.rsp.bz2 b/src/crypto/ecdsa/testdata/SigVer.rsp.bz2 Binary files differnew file mode 100644 index 0000000..09fe2b4 --- /dev/null +++ b/src/crypto/ecdsa/testdata/SigVer.rsp.bz2 |