genrandom.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "os.h"
  2. #include <mp.h>
  3. #include <libsec.h>
  4. typedef struct State{
  5. QLock lock;
  6. int seeded;
  7. uvlong seed;
  8. DES3state des3;
  9. } State;
  10. static State x917state;
  11. static void
  12. X917(uchar *rand, int nrand)
  13. {
  14. int i, m, n8;
  15. uvlong I, x;
  16. /* 1. Compute intermediate value I = Ek(time). */
  17. I = nsec();
  18. triple_block_cipher(x917state.des3.expanded, (uchar*)&I, 0); /* two-key EDE */
  19. /* 2. x[i] = Ek(I^seed); seed = Ek(x[i]^I); */
  20. m = (nrand+7)/8;
  21. for(i=0; i<m; i++){
  22. x = I ^ x917state.seed;
  23. triple_block_cipher(x917state.des3.expanded, (uchar*)&x, 0);
  24. n8 = (nrand>8) ? 8 : nrand;
  25. memcpy(rand, (uchar*)&x, n8);
  26. rand += 8;
  27. nrand -= 8;
  28. x ^= I;
  29. triple_block_cipher(x917state.des3.expanded, (uchar*)&x, 0);
  30. x917state.seed = x;
  31. }
  32. }
  33. static void
  34. X917init(void)
  35. {
  36. int n;
  37. uchar mix[128];
  38. uchar key3[3][8];
  39. ulong *ulp;
  40. ulp = (ulong*)key3;
  41. for(n = 0; n < sizeof(key3)/sizeof(ulong); n++)
  42. ulp[n] = truerand();
  43. setupDES3state(&x917state.des3, key3, nil);
  44. X917(mix, sizeof mix);
  45. x917state.seeded = 1;
  46. }
  47. void
  48. genrandom(uchar *p, int n)
  49. {
  50. qlock(&x917state.lock);
  51. if(x917state.seeded == 0)
  52. X917init();
  53. X917(p, n);
  54. qunlock(&x917state.lock);
  55. }