Hacking Secret Ciphers with Python

(Ann) #1

384 http://inventwithpython.com/hacking


Email questions to the author: [email protected]



  1. p = rabinMiller.generateLargePrime(keySize)

  2. print('Generating q prime...')

  3. q = rabinMiller.generateLargePrime(keySize)

  4. n = p * q




  5. Step 2: Create a number e that is relatively prime to (p-1)*(q-1).



  6. print('Generating e that is relatively prime to (p-1)*(q-1)...')

  7. while True:


  8. Keep trying random numbers for e until one is valid.



  9. e = random.randrange(2 (keySize - 1), 2 (keySize))

  10. if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:

  11. break




  12. Step 3: Calculate d, the mod inverse of e.



  13. print('Calculating d that is mod inverse of e...')

  14. d = cryptomath.findModInverse(e, (p - 1) * (q - 1))



  15. publicKey = (n, e)

  16. privateKey = (n, d)



  17. print('Public key:', publicKey)

  18. print('Private key:', privateKey)



  19. return (publicKey, privateKey)





  20. def makeKeyFiles(name, keySize):


  21. Creates two files 'x_pubkey.txt' and 'x_privkey.txt' (where x is the




  22. value in name) with the the n,e and d,e integers written in them,




  23. delimited by a comma.






  24. Our safety check will prevent us from overwriting our old key files:



  25. if os.path.exists('%s_pubkey.txt' % (name)) or
    os.path.exists('%s_privkey.txt' % (name)):

  26. sys.exit('WARNING: The file %s_pubkey.txt or %s_privkey.txt already
    exists! Use a different name or delete these files and re-run this program.' %
    (name, name))



  27. publicKey, privateKey = generateKey(keySize)



  28. print()

  29. print('The public key is a %s and a %s digit number.' %
    (len(str(publicKey[0])), len(str(publicKey[1]))))

  30. print('Writing public key to file %s_pubkey.txt...' % (name))

  31. fo = open('%s_pubkey.txt' % (name), 'w')

  32. fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1]))

Free download pdf