dsa.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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.
  4. // Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
  5. //
  6. // The DSA operations in this package are not implemented using constant-time algorithms.
  7. //
  8. // Warning: DSA is a legacy algorithm, and modern alternatives such as
  9. // Ed25519 (implemented by package crypto/ed25519) should be used instead. Keys
  10. // with 1024-bit moduli (L1024N160 parameters) are cryptographically weak, while
  11. // bigger keys are not widely supported. Note that FIPS 186-5 no longer approves
  12. // DSA for signature generation.
  13. package dsa
  14. import (
  15. "errors"
  16. "io"
  17. "math/big"
  18. "github.com/zmap/zcrypto/internal/randutil"
  19. )
  20. // Parameters represents the domain parameters for a key. These parameters can
  21. // be shared across many keys. The bit length of Q must be a multiple of 8.
  22. type Parameters struct {
  23. P, Q, G *big.Int
  24. }
  25. // PublicKey represents a DSA public key.
  26. type PublicKey struct {
  27. Parameters
  28. Y *big.Int
  29. }
  30. // PrivateKey represents a DSA private key.
  31. type PrivateKey struct {
  32. PublicKey
  33. X *big.Int
  34. }
  35. // ErrInvalidPublicKey results when a public key is not usable by this code.
  36. // FIPS is quite strict about the format of DSA keys, but other code may be
  37. // less so. Thus, when using keys which may have been generated by other code,
  38. // this error must be handled.
  39. var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key")
  40. // ParameterSizes is an enumeration of the acceptable bit lengths of the primes
  41. // in a set of DSA parameters. See FIPS 186-3, section 4.2.
  42. type ParameterSizes int
  43. const (
  44. L1024N160 ParameterSizes = iota
  45. L2048N224
  46. L2048N256
  47. L3072N256
  48. )
  49. // numMRTests is the number of Miller-Rabin primality tests that we perform. We
  50. // pick the largest recommended number from table C.1 of FIPS 186-3.
  51. const numMRTests = 64
  52. // GenerateParameters puts a random, valid set of DSA parameters into params.
  53. // This function can take many seconds, even on fast machines.
  54. func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) error {
  55. // This function doesn't follow FIPS 186-3 exactly in that it doesn't
  56. // use a verification seed to generate the primes. The verification
  57. // seed doesn't appear to be exported or used by other code and
  58. // omitting it makes the code cleaner.
  59. var L, N int
  60. switch sizes {
  61. case L1024N160:
  62. L = 1024
  63. N = 160
  64. case L2048N224:
  65. L = 2048
  66. N = 224
  67. case L2048N256:
  68. L = 2048
  69. N = 256
  70. case L3072N256:
  71. L = 3072
  72. N = 256
  73. default:
  74. return errors.New("crypto/dsa: invalid ParameterSizes")
  75. }
  76. qBytes := make([]byte, N/8)
  77. pBytes := make([]byte, L/8)
  78. q := new(big.Int)
  79. p := new(big.Int)
  80. rem := new(big.Int)
  81. one := new(big.Int)
  82. one.SetInt64(1)
  83. GeneratePrimes:
  84. for {
  85. if _, err := io.ReadFull(rand, qBytes); err != nil {
  86. return err
  87. }
  88. qBytes[len(qBytes)-1] |= 1
  89. qBytes[0] |= 0x80
  90. q.SetBytes(qBytes)
  91. if !q.ProbablyPrime(numMRTests) {
  92. continue
  93. }
  94. for i := 0; i < 4*L; i++ {
  95. if _, err := io.ReadFull(rand, pBytes); err != nil {
  96. return err
  97. }
  98. pBytes[len(pBytes)-1] |= 1
  99. pBytes[0] |= 0x80
  100. p.SetBytes(pBytes)
  101. rem.Mod(p, q)
  102. rem.Sub(rem, one)
  103. p.Sub(p, rem)
  104. if p.BitLen() < L {
  105. continue
  106. }
  107. if !p.ProbablyPrime(numMRTests) {
  108. continue
  109. }
  110. params.P = p
  111. params.Q = q
  112. break GeneratePrimes
  113. }
  114. }
  115. h := new(big.Int)
  116. h.SetInt64(2)
  117. g := new(big.Int)
  118. pm1 := new(big.Int).Sub(p, one)
  119. e := new(big.Int).Div(pm1, q)
  120. for {
  121. g.Exp(h, e, p)
  122. if g.Cmp(one) == 0 {
  123. h.Add(h, one)
  124. continue
  125. }
  126. params.G = g
  127. return nil
  128. }
  129. }
  130. // GenerateKey generates a public&private key pair. The Parameters of the
  131. // PrivateKey must already be valid (see GenerateParameters).
  132. func GenerateKey(priv *PrivateKey, rand io.Reader) error {
  133. if priv.P == nil || priv.Q == nil || priv.G == nil {
  134. return errors.New("crypto/dsa: parameters not set up before generating key")
  135. }
  136. x := new(big.Int)
  137. xBytes := make([]byte, priv.Q.BitLen()/8)
  138. for {
  139. _, err := io.ReadFull(rand, xBytes)
  140. if err != nil {
  141. return err
  142. }
  143. x.SetBytes(xBytes)
  144. if x.Sign() != 0 && x.Cmp(priv.Q) < 0 {
  145. break
  146. }
  147. }
  148. priv.X = x
  149. priv.Y = new(big.Int)
  150. priv.Y.Exp(priv.G, x, priv.P)
  151. return nil
  152. }
  153. // fermatInverse calculates the inverse of k in GF(P) using Fermat's method.
  154. // This has better constant-time properties than Euclid's method (implemented
  155. // in math/big.Int.ModInverse) although math/big itself isn't strictly
  156. // constant-time so it's not perfect.
  157. func fermatInverse(k, P *big.Int) *big.Int {
  158. two := big.NewInt(2)
  159. pMinus2 := new(big.Int).Sub(P, two)
  160. return new(big.Int).Exp(k, pMinus2, P)
  161. }
  162. // Sign signs an arbitrary length hash (which should be the result of hashing a
  163. // larger message) using the private key, priv. It returns the signature as a
  164. // pair of integers. The security of the private key depends on the entropy of
  165. // rand.
  166. //
  167. // Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
  168. // to the byte-length of the subgroup. This function does not perform that
  169. // truncation itself.
  170. //
  171. // Be aware that calling Sign with an attacker-controlled PrivateKey may
  172. // require an arbitrary amount of CPU.
  173. func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
  174. randutil.MaybeReadByte(rand)
  175. // FIPS 186-3, section 4.6
  176. n := priv.Q.BitLen()
  177. if priv.Q.Sign() <= 0 || priv.P.Sign() <= 0 || priv.G.Sign() <= 0 || priv.X.Sign() <= 0 || n%8 != 0 {
  178. err = ErrInvalidPublicKey
  179. return
  180. }
  181. n >>= 3
  182. var attempts int
  183. for attempts = 10; attempts > 0; attempts-- {
  184. k := new(big.Int)
  185. buf := make([]byte, n)
  186. for {
  187. _, err = io.ReadFull(rand, buf)
  188. if err != nil {
  189. return
  190. }
  191. k.SetBytes(buf)
  192. // priv.Q must be >= 128 because the test above
  193. // requires it to be > 0 and that
  194. // ceil(log_2(Q)) mod 8 = 0
  195. // Thus this loop will quickly terminate.
  196. if k.Sign() > 0 && k.Cmp(priv.Q) < 0 {
  197. break
  198. }
  199. }
  200. kInv := fermatInverse(k, priv.Q)
  201. r = new(big.Int).Exp(priv.G, k, priv.P)
  202. r.Mod(r, priv.Q)
  203. if r.Sign() == 0 {
  204. continue
  205. }
  206. z := k.SetBytes(hash)
  207. s = new(big.Int).Mul(priv.X, r)
  208. s.Add(s, z)
  209. s.Mod(s, priv.Q)
  210. s.Mul(s, kInv)
  211. s.Mod(s, priv.Q)
  212. if s.Sign() != 0 {
  213. break
  214. }
  215. }
  216. // Only degenerate private keys will require more than a handful of
  217. // attempts.
  218. if attempts == 0 {
  219. return nil, nil, ErrInvalidPublicKey
  220. }
  221. return
  222. }
  223. // Verify verifies the signature in r, s of hash using the public key, pub. It
  224. // reports whether the signature is valid.
  225. //
  226. // Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
  227. // to the byte-length of the subgroup. This function does not perform that
  228. // truncation itself.
  229. func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
  230. // FIPS 186-3, section 4.7
  231. if pub.P.Sign() == 0 {
  232. return false
  233. }
  234. if r.Sign() < 1 || r.Cmp(pub.Q) >= 0 {
  235. return false
  236. }
  237. if s.Sign() < 1 || s.Cmp(pub.Q) >= 0 {
  238. return false
  239. }
  240. w := new(big.Int).ModInverse(s, pub.Q)
  241. if w == nil {
  242. return false
  243. }
  244. n := pub.Q.BitLen()
  245. if n%8 != 0 {
  246. return false
  247. }
  248. z := new(big.Int).SetBytes(hash)
  249. u1 := new(big.Int).Mul(z, w)
  250. u1.Mod(u1, pub.Q)
  251. u2 := w.Mul(r, w)
  252. u2.Mod(u2, pub.Q)
  253. v := u1.Exp(pub.G, u1, pub.P)
  254. u2.Exp(pub.Y, u2, pub.P)
  255. v.Mul(v, u2)
  256. v.Mod(v, pub.P)
  257. v.Mod(v, pub.Q)
  258. return v.Cmp(r) == 0
  259. }