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 // http://www.nsa.gov/ia/_files/ecdsa.pdf
17 // http://www.secg.org/sec1-v2.pdf
31 // A invertible implements fast inverse mod Curve.Params().N
32 type invertible
interface {
33 // Inverse returns the inverse of k in GF(P)
34 Inverse(k
*big
.Int
) *big
.Int
37 // combinedMult implements fast multiplication S1*g + S2*p (g - generator, p - arbitrary point)
38 type combinedMult
interface {
39 CombinedMult(bigX
, bigY
*big
.Int
, baseScalar
, scalar
[]byte) (x
, y
*big
.Int
)
43 aesIV
= "IV for ECDSA CTR"
46 // PublicKey represents an ECDSA public key.
47 type PublicKey
struct {
52 // PrivateKey represents a ECDSA private key.
53 type PrivateKey
struct {
58 type ecdsaSignature
struct {
62 // Public returns the public key corresponding to priv.
63 func (priv
*PrivateKey
) Public() crypto
.PublicKey
{
64 return &priv
.PublicKey
67 // Sign signs msg with priv, reading randomness from rand. This method is
68 // intended to support keys where the private part is kept in, for example, a
69 // hardware module. Common uses should use the Sign function in this package
71 func (priv
*PrivateKey
) Sign(rand io
.Reader
, msg
[]byte, opts crypto
.SignerOpts
) ([]byte, error
) {
72 r
, s
, err
:= Sign(rand
, priv
, msg
)
77 return asn1
.Marshal(ecdsaSignature
{r
, s
})
80 var one
= new(big
.Int
).SetInt64(1)
82 // randFieldElement returns a random element of the field underlying the given
83 // curve using the procedure given in [NSA] A.2.1.
84 func randFieldElement(c elliptic
.Curve
, rand io
.Reader
) (k
*big
.Int
, err error
) {
86 b
:= make([]byte, params
.BitSize
/8+8)
87 _
, err
= io
.ReadFull(rand
, b
)
92 k
= new(big
.Int
).SetBytes(b
)
93 n
:= new(big
.Int
).Sub(params
.N
, one
)
99 // GenerateKey generates a public and private key pair.
100 func GenerateKey(c elliptic
.Curve
, rand io
.Reader
) (priv
*PrivateKey
, err error
) {
101 k
, err
:= randFieldElement(c
, rand
)
106 priv
= new(PrivateKey
)
107 priv
.PublicKey
.Curve
= c
109 priv
.PublicKey
.X
, priv
.PublicKey
.Y
= c
.ScalarBaseMult(k
.Bytes())
113 // hashToInt converts a hash value to an integer. There is some disagreement
114 // about how this is done. [NSA] suggests that this is done in the obvious
115 // manner, but [SECG] truncates the hash to the bit-length of the curve order
116 // first. We follow [SECG] because that's what OpenSSL does. Additionally,
117 // OpenSSL right shifts excess bits from the number if the hash is too large
118 // and we mirror that too.
119 func hashToInt(hash
[]byte, c elliptic
.Curve
) *big
.Int
{
120 orderBits
:= c
.Params().N
.BitLen()
121 orderBytes
:= (orderBits
+ 7) / 8
122 if len(hash
) > orderBytes
{
123 hash
= hash
[:orderBytes
]
126 ret
:= new(big
.Int
).SetBytes(hash
)
127 excess
:= len(hash
)*8 - orderBits
129 ret
.Rsh(ret
, uint(excess
))
134 // fermatInverse calculates the inverse of k in GF(P) using Fermat's method.
135 // This has better constant-time properties than Euclid's method (implemented
136 // in math/big.Int.ModInverse) although math/big itself isn't strictly
137 // constant-time so it's not perfect.
138 func fermatInverse(k
, N
*big
.Int
) *big
.Int
{
140 nMinus2
:= new(big
.Int
).Sub(N
, two
)
141 return new(big
.Int
).Exp(k
, nMinus2
, N
)
144 var errZeroParam
= errors
.New("zero parameter")
146 // Sign signs an arbitrary length hash (which should be the result of hashing a
147 // larger message) using the private key, priv. It returns the signature as a
148 // pair of integers. The security of the private key depends on the entropy of
150 func Sign(rand io
.Reader
, priv
*PrivateKey
, hash
[]byte) (r
, s
*big
.Int
, err error
) {
151 // Get max(log2(q) / 2, 256) bits of entropy from rand.
152 entropylen
:= (priv
.Curve
.Params().BitSize
+ 7) / 16
156 entropy
:= make([]byte, entropylen
)
157 _
, err
= io
.ReadFull(rand
, entropy
)
162 // Initialize an SHA-512 hash context; digest ...
164 md
.Write(priv
.D
.Bytes()) // the private key,
165 md
.Write(entropy
) // the entropy,
166 md
.Write(hash
) // and the input hash;
167 key
:= md
.Sum(nil)[:32] // and compute ChopMD-256(SHA-512),
168 // which is an indifferentiable MAC.
170 // Create an AES-CTR instance to use as a CSPRNG.
171 block
, err
:= aes
.NewCipher(key
)
176 // Create a CSPRNG that xors a stream of zeros with
177 // the output of the AES-CTR instance.
178 csprng
:= cipher
.StreamReader
{
180 S
: cipher
.NewCTR(block
, []byte(aesIV
)),
184 c
:= priv
.PublicKey
.Curve
187 return nil, nil, errZeroParam
192 k
, err
= randFieldElement(c
, csprng
)
198 if in
, ok
:= priv
.Curve
.(invertible
); ok
{
201 kInv
= fermatInverse(k
, N
) // N != 0
204 r
, _
= priv
.Curve
.ScalarBaseMult(k
.Bytes())
211 e
:= hashToInt(hash
, c
)
212 s
= new(big
.Int
).Mul(priv
.D
, r
)
215 s
.Mod(s
, N
) // N != 0
224 // Verify verifies the signature in r, s of hash using the public key, pub. Its
225 // return value records whether the signature is valid.
226 func Verify(pub
*PublicKey
, hash
[]byte, r
, s
*big
.Int
) bool {
231 if r
.Sign() == 0 || s
.Sign() == 0 {
234 if r
.Cmp(N
) >= 0 || s
.Cmp(N
) >= 0 {
237 e
:= hashToInt(hash
, c
)
240 if in
, ok
:= c
.(invertible
); ok
{
243 w
= new(big
.Int
).ModInverse(s
, N
)
251 // Check if implements S1*g + S2*p
253 if opt
, ok
:= c
.(combinedMult
); ok
{
254 x
, y
= opt
.CombinedMult(pub
.X
, pub
.Y
, u1
.Bytes(), u2
.Bytes())
256 x1
, y1
:= c
.ScalarBaseMult(u1
.Bytes())
257 x2
, y2
:= c
.ScalarMult(pub
.X
, pub
.Y
, u2
.Bytes())
258 x
, y
= c
.Add(x1
, y1
, x2
, y2
)
261 if x
.Sign() == 0 && y
.Sign() == 0 {
272 // Read replaces the contents of dst with zeros.
273 func (z
*zr
) Read(dst
[]byte) (n
int, err error
) {
280 var zeroReader
= &zr
{}