mprand.c 584 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include "os.h"
  2. #include <mp.h>
  3. #include <libsec.h>
  4. #include "dat.h"
  5. mpint*
  6. mprand(int bits, void (*gen)(uchar*, int), mpint *b)
  7. {
  8. int n, m;
  9. mpdigit mask;
  10. uchar *p;
  11. n = DIGITS(bits);
  12. if(b == nil)
  13. b = mpnew(bits);
  14. else
  15. mpbits(b, bits);
  16. p = malloc(n*Dbytes);
  17. if(p == nil)
  18. return nil;
  19. (*gen)(p, n*Dbytes);
  20. betomp(p, n*Dbytes, b);
  21. free(p);
  22. // make sure we don't give too many bits
  23. m = bits%Dbits;
  24. n--;
  25. if(m > 0){
  26. mask = 1;
  27. mask <<= m;
  28. mask--;
  29. b->p[n] &= mask;
  30. }
  31. for(; n >= 0; n--)
  32. if(b->p[n] != 0)
  33. break;
  34. b->top = n+1;
  35. b->sign = 1;
  36. return b;
  37. }