Hacking Secret Ciphers with Python

(Ann) #1

394 http://inventwithpython.com/hacking


Email questions to the author: [email protected]




  1. file. Returns the encrypted message string.



  2. keySize, n, e = readKeyFile(keyFilename)




  3. Check that key size is greater than block size.



  4. if keySize < blockSize 8: # 8 to convert bytes to bits

  5. sys.exit('ERROR: Block size is %s bits and key size is %s bits.
    The RSA cipher requires the block size to be equal to or less than the key
    size. Either increase the block size or use different keys.' % (blockSize * 8,
    keySize))






  6. Encrypt the message



  7. encryptedBlocks = encryptMessage(message, (n, e), blockSize)




  8. Convert the large int values to one string value.



  9. for i in range(len(encryptedBlocks)):

  10. encryptedBlocks[i] = str(encryptedBlocks[i])

  11. encryptedContent = ','.join(encryptedBlocks)




  12. Write out the encrypted string to the output file.



  13. encryptedContent = '%s%s%s' % (len(message), blockSize,
    encryptedContent)

  14. fo = open(messageFilename, 'w')

  15. fo.write(encryptedContent)

  16. fo.close()


  17. Also return the encrypted string.



  18. return encryptedContent





  19. def readFromFileAndDecrypt(messageFilename, keyFilename):


  20. Using a key from a key file, read an encrypted message from a file




  21. and then decrypt it. Returns the decrypted message string.



  22. keySize, n, d = readKeyFile(keyFilename)






  23. Read in the message length and the encrypted message from the file.



  24. fo = open(messageFilename)

  25. content = fo.read()

  26. messageLength, blockSize, encryptedMessage = content.split('_')

  27. messageLength = int(messageLength)

  28. blockSize = int(blockSize)




  29. Check that key size is greater than block size.



  30. if keySize < blockSize 8: # 8 to convert bytes to bits

  31. sys.exit('ERROR: Block size is %s bits and key size is %s bits.
    The RSA cipher requires the block size to be equal to or less than the key

Free download pdf