1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as
6 // defined in FIPS 186-3.
8 // This implementation derives the nonce from an AES-CTR CSPRNG keyed by
9 // ChopMD(256, SHA2-512(priv.D || entropy || hash)). The CSPRNG key is IRO by
10 // a result of Coron; the AES-CTR stream is IRO under standard assumptions.
14 // [NSA]: Suite B implementer's guide to FIPS 186-3,
15 // https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm
17 // http://www.secg.org/sec1-v2.pdf
24 "crypto/internal/randutil"
33 "crypto/internal/boring"
37 // A invertible implements fast inverse mod Curve.Params().N
38 type invertible interface {
39 // Inverse returns the inverse of k in GF(P)
40 Inverse(k *big.Int) *big.Int
43 // combinedMult implements fast multiplication S1*g + S2*p (g - generator, p - arbitrary point)
44 type combinedMult interface {
45 CombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int)
49 aesIV = "IV for ECDSA CTR"
52 // PublicKey represents an ECDSA public key.
53 type PublicKey struct {
60 // PrivateKey represents an ECDSA private key.
61 type PrivateKey struct {
68 type ecdsaSignature struct {
72 // Public returns the public key corresponding to priv.
73 func (priv *PrivateKey) Public() crypto.PublicKey {
74 return &priv.PublicKey
77 // Sign signs digest with priv, reading randomness from rand. The opts argument
78 // is not currently used but, in keeping with the crypto.Signer interface,
79 // should be the hash function used to digest the message.
81 // This method implements crypto.Signer, which is an interface to support keys
82 // where the private part is kept in, for example, a hardware module. Common
83 // uses should use the Sign function in this package directly.
84 func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
85 if boring.Enabled && rand == boring.RandReader {
86 b, err := boringPrivateKey(priv)
90 return boring.SignMarshalECDSA(b, digest)
92 boring.UnreachableExceptTests()
94 r, s, err := Sign(rand, priv, digest)
99 return asn1.Marshal(ecdsaSignature{r, s})
102 var one = new(big.Int).SetInt64(1)
104 // randFieldElement returns a random element of the field underlying the given
105 // curve using the procedure given in [NSA] A.2.1.
106 func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
108 b := make([]byte, params.BitSize/8+8)
109 _, err = io.ReadFull(rand, b)
114 k = new(big.Int).SetBytes(b)
115 n := new(big.Int).Sub(params.N, one)
121 // GenerateKey generates a public and private key pair.
122 func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
123 if boring.Enabled && rand == boring.RandReader {
124 x, y, d, err := boring.GenerateKeyECDSA(c.Params().Name)
128 return &PrivateKey{PublicKey: PublicKey{Curve: c, X: x, Y: y}, D: d}, nil
130 boring.UnreachableExceptTests()
132 k, err := randFieldElement(c, rand)
137 priv := new(PrivateKey)
138 priv.PublicKey.Curve = c
140 priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
144 // hashToInt converts a hash value to an integer. There is some disagreement
145 // about how this is done. [NSA] suggests that this is done in the obvious
146 // manner, but [SECG] truncates the hash to the bit-length of the curve order
147 // first. We follow [SECG] because that's what OpenSSL does. Additionally,
148 // OpenSSL right shifts excess bits from the number if the hash is too large
149 // and we mirror that too.
150 func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
151 orderBits := c.Params().N.BitLen()
152 orderBytes := (orderBits + 7) / 8
153 if len(hash) > orderBytes {
154 hash = hash[:orderBytes]
157 ret := new(big.Int).SetBytes(hash)
158 excess := len(hash)*8 - orderBits
160 ret.Rsh(ret, uint(excess))
165 // fermatInverse calculates the inverse of k in GF(P) using Fermat's method.
166 // This has better constant-time properties than Euclid's method (implemented
167 // in math/big.Int.ModInverse) although math/big itself isn't strictly
168 // constant-time so it's not perfect.
169 func fermatInverse(k, N *big.Int) *big.Int {
171 nMinus2 := new(big.Int).Sub(N, two)
172 return new(big.Int).Exp(k, nMinus2, N)
175 var errZeroParam = errors.New("zero parameter")
177 // Sign signs a hash (which should be the result of hashing a larger message)
178 // using the private key, priv. If the hash is longer than the bit-length of the
179 // private key's curve order, the hash will be truncated to that length. It
180 // returns the signature as a pair of integers. The security of the private key
181 // depends on the entropy of rand.
182 func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
183 randutil.MaybeReadByte(rand)
185 if boring.Enabled && rand == boring.RandReader {
186 b, err := boringPrivateKey(priv)
190 return boring.SignECDSA(b, hash)
192 boring.UnreachableExceptTests()
194 // Get min(log2(q) / 2, 256) bits of entropy from rand.
195 entropylen := (priv.Curve.Params().BitSize + 7) / 16
199 entropy := make([]byte, entropylen)
200 _, err = io.ReadFull(rand, entropy)
205 // Initialize an SHA-512 hash context; digest ...
207 md.Write(priv.D.Bytes()) // the private key,
208 md.Write(entropy) // the entropy,
209 md.Write(hash) // and the input hash;
210 key := md.Sum(nil)[:32] // and compute ChopMD-256(SHA-512),
211 // which is an indifferentiable MAC.
213 // Create an AES-CTR instance to use as a CSPRNG.
214 block, err := aes.NewCipher(key)
219 // Create a CSPRNG that xors a stream of zeros with
220 // the output of the AES-CTR instance.
221 csprng := cipher.StreamReader{
223 S: cipher.NewCTR(block, []byte(aesIV)),
227 c := priv.PublicKey.Curve
228 e := hashToInt(hash, c)
229 r, s, err = sign(priv, &csprng, c, e)
233 func signGeneric(priv *PrivateKey, csprng *cipher.StreamReader, c elliptic.Curve, e *big.Int) (r, s *big.Int, err error) {
236 return nil, nil, errZeroParam
242 k, err = randFieldElement(c, *csprng)
248 if in, ok := priv.Curve.(invertible); ok {
251 kInv = fermatInverse(k, N) // N != 0
254 r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
260 s = new(big.Int).Mul(priv.D, r)
263 s.Mod(s, N) // N != 0
271 // Verify verifies the signature in r, s of hash using the public key, pub. Its
272 // return value records whether the signature is valid.
273 func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
275 b, err := boringPublicKey(pub)
279 return boring.VerifyECDSA(b, hash, r, s)
281 boring.UnreachableExceptTests()
287 if r.Sign() <= 0 || s.Sign() <= 0 {
290 if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
293 e := hashToInt(hash, c)
294 return verify(pub, c, e, r, s)
297 func verifyGeneric(pub *PublicKey, c elliptic.Curve, e, r, s *big.Int) bool {
300 if in, ok := c.(invertible); ok {
303 w = new(big.Int).ModInverse(s, N)
311 // Check if implements S1*g + S2*p
313 if opt, ok := c.(combinedMult); ok {
314 x, y = opt.CombinedMult(pub.X, pub.Y, u1.Bytes(), u2.Bytes())
316 x1, y1 := c.ScalarBaseMult(u1.Bytes())
317 x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())
318 x, y = c.Add(x1, y1, x2, y2)
321 if x.Sign() == 0 && y.Sign() == 0 {
332 // Read replaces the contents of dst with zeros.
333 func (z *zr) Read(dst []byte) (n int, err error) {
340 var zeroReader = &zr{}