home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Demo / rsa / rsademo.py < prev    next >
Text File  |  1993-12-17  |  2KB  |  64 lines

  1. # Demonstration of the RSA cryptosystem.  This lets you use a public
  2. # channel (one where everybody can read what you send) to send
  3. # messages encrypted using a public encryption key, but which can
  4. # only be decrypted by who knows the secret decryption key.
  5. #
  6. # The security of the method comes from the fact that it is hard to
  7. # factorize the product of two large primes -- and we can always use
  8. # larger primes if the enemy buys a faster computer.
  9. #
  10. # It works as follows (in laymen's terms, and without proof):
  11. # - Let n be a large number, the modulus (e.g. about 512 bits).
  12. # - Let sk be the secret key and pk be the public key.
  13. # - Let plaintext be the message we want to encode, a number less than n.
  14. # - Let crypttext be plaintext to the power pk modulo n.
  15. # Then crypttext to the power sk modulo n equals plaintext again.
  16. #
  17. # Actually, n is the product of two (pseudo-)primes n1 and n2, pk is a
  18. # (small) prime, and sk is the inverse of pk mod (n1-1)*(n2-1), i.e.
  19. # pk*sk == 1 mod (n1-1)*(n2-1).  Then x**(pk*sk) == x (mod n) for all x.
  20. # This is the Chinese remainder theorem -- it actually only works for
  21. # real primes!
  22. #
  23. # The hard problem is coming up with suitable primes; our
  24. # implementation only uses pseudo-primes (numbers that aren't
  25. # obviously non-primes, given a suitable pseudo-primality test).
  26. #
  27. # Reference:
  28. #
  29. # RL Rivest, A Shamir, L Adleman.  A method for obtaining digital
  30. # signatures and public-key cryptosystems.  CACM 21(2):120-126,
  31. # February, 1978.
  32.  
  33.  
  34. # Import some functions
  35. from rsakeys import makersaset, default_pk
  36. from simplerandom import simplerandom
  37. from mpz import powm
  38.  
  39. # Make a random function (the seed determines the secret key computed!)
  40. rf = simplerandom('<YOUR SEED HERE>').random
  41.  
  42. # Use the default public key
  43. pk = default_pk
  44.  
  45. # Choose a random n and secret key (this takes a minute and a half
  46. # on an R3000 processor at 33 MHz!).  Note that this is deterministic
  47. # if you don't vary the seed for the random function above
  48. n, sk = makersaset(512, rf)
  49.  
  50. # Choose a random plaintext message to test the algorithms
  51. plaintext = rf(n)
  52.  
  53. # Encrypt the plaintext
  54. crypttext = powm(plaintext, pk, n)
  55.  
  56. # Decrypt the crypttext
  57. testvalue = powm(crypttext, sk, n)
  58.  
  59. # The decrypted crypttext should be the same as the original plaintext
  60. if testvalue != plaintext:
  61.     raise 'FATAL', 'RSA implementation failed!'
  62.  
  63. print 'Test succeeded.'
  64.