dsaprimes.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include "os.h"
  10. #include <mp.h>
  11. #include <libsec.h>
  12. // NIST algorithm for generating DSA primes
  13. // Menezes et al (1997) Handbook of Applied Cryptography, p.151
  14. // q is a 160-bit prime; p is a 1024-bit prime; q divides p-1
  15. // arithmetic on unsigned ints mod 2**160, represented
  16. // as 20-byte, little-endian uchar array
  17. static void
  18. Hrand(uint8_t *s)
  19. {
  20. uint32_t *u = (uint32_t*)s;
  21. *u++ = fastrand();
  22. *u++ = fastrand();
  23. *u++ = fastrand();
  24. *u++ = fastrand();
  25. *u = fastrand();
  26. }
  27. static void
  28. Hincr(uint8_t *s)
  29. {
  30. int i;
  31. for(i=0; i<20; i++)
  32. if(++s[i]!=0)
  33. break;
  34. }
  35. // this can run for quite a while; be patient
  36. void
  37. DSAprimes(mpint *q, mpint *p, uint8_t seed[SHA1dlen])
  38. {
  39. int i, j, k, n = 6, b = 63;
  40. uint8_t s[SHA1dlen], Hs[SHA1dlen], Hs1[SHA1dlen], sj[SHA1dlen], sjk[SHA1dlen];
  41. mpint *two1023, *mb, *Vk, *W, *X, *q2;
  42. two1023 = mpnew(1024);
  43. mpleft(mpone, 1023, two1023);
  44. mb = mpnew(0);
  45. mpleft(mpone, b, mb);
  46. W = mpnew(1024);
  47. Vk = mpnew(1024);
  48. X = mpnew(0);
  49. q2 = mpnew(0);
  50. forever:
  51. do{
  52. Hrand(s);
  53. memcpy(sj, s, 20);
  54. sha1(s, 20, Hs, 0);
  55. Hincr(sj);
  56. sha1(sj, 20, Hs1, 0);
  57. for(i=0; i<20; i++)
  58. Hs[i] ^= Hs1[i];
  59. Hs[0] |= 1;
  60. Hs[19] |= 0x80;
  61. letomp(Hs, 20, q);
  62. }while(!probably_prime(q, 18));
  63. if(seed != nil) // allow skeptics to confirm computation
  64. memmove(seed, s, SHA1dlen);
  65. i = 0;
  66. j = 2;
  67. Hincr(sj);
  68. mpleft(q, 1, q2);
  69. while(i<4096){
  70. memcpy(sjk, sj, 20);
  71. for(k=0; k <= n; k++){
  72. sha1(sjk, 20, Hs, 0);
  73. letomp(Hs, 20, Vk);
  74. if(k == n)
  75. mpmod(Vk, mb, Vk);
  76. mpleft(Vk, 160*k, Vk);
  77. mpadd(W, Vk, W);
  78. Hincr(sjk);
  79. }
  80. mpadd(W, two1023, X);
  81. mpmod(X, q2, W);
  82. mpsub(W, mpone, W);
  83. mpsub(X, W, p);
  84. if(mpcmp(p, two1023)>=0 && probably_prime(p, 5))
  85. goto done;
  86. i += 1;
  87. j += n+1;
  88. for(k=0; k<n+1; k++)
  89. Hincr(sj);
  90. }
  91. goto forever;
  92. done:
  93. mpfree(q2);
  94. mpfree(X);
  95. mpfree(Vk);
  96. mpfree(W);
  97. mpfree(mb);
  98. mpfree(two1023);
  99. }