egencrypt.c 806 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include "os.h"
  2. #include <mp.h>
  3. #include <libsec.h>
  4. mpint*
  5. egencrypt(EGpub *pub, mpint *in, mpint *out)
  6. {
  7. mpint *m, *k, *gamma, *delta, *pm1;
  8. mpint *p = pub->p, *alpha = pub->alpha;
  9. int plen = mpsignif(p);
  10. int shift = ((plen+Dbits)/Dbits)*Dbits;
  11. // in libcrypt version, (int)(LENGTH(pub->p)*sizeof(NumType)*CHARBITS);
  12. if(out == nil)
  13. out = mpnew(0);
  14. pm1 = mpnew(0);
  15. m = mpnew(0);
  16. gamma = mpnew(0);
  17. delta = mpnew(0);
  18. mpmod(in, p, m);
  19. while(1){
  20. k = mprand(plen, genrandom, nil);
  21. if((mpcmp(mpone, k) <= 0) && (mpcmp(k, pm1) < 0))
  22. break;
  23. }
  24. mpexp(alpha, k, p, gamma);
  25. mpexp(pub->key, k, p, delta);
  26. mpmul(m, delta, delta);
  27. mpmod(delta, p, delta);
  28. mpleft(gamma, shift, out);
  29. mpadd(delta, out, out);
  30. mpfree(pm1);
  31. mpfree(m);
  32. mpfree(k);
  33. mpfree(gamma);
  34. mpfree(delta);
  35. return out;
  36. }