Hacking Secret Ciphers with Python

(Ann) #1

392 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Founding Fathers gave the free press the protection it must have to bare the
secrets of government and inform the people." -Hugo Black'''



  1. pubKeyFilename = 'al_sweigart_pubkey.txt'

  2. print('Encrypting and writing to %s...' % (filename))

  3. encryptedText = encryptAndWriteToFile(filename, pubKeyFilename,
    message)



  4. print('Encrypted text:')

  5. print(encryptedText)



  6. elif mode == 'decrypt':

  7. privKeyFilename = 'al_sweigart_privkey.txt'

  8. print('Reading from %s and decrypting...' % (filename))

  9. decryptedText = readFromFileAndDecrypt(filename, privKeyFilename)



  10. print('Decrypted text:')

  11. print(decryptedText)





  12. def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE):


  13. Converts a string message to a list of block integers. Each integer




  14. represents 128 (or whatever blockSize is set to) string characters.





  15. messageBytes = message.encode('ascii') # convert the string to bytes



  16. blockInts = []

  17. for blockStart in range(0, len(messageBytes), blockSize):


  18. Calculate the block integer for this block of text



  19. blockInt = 0

  20. for i in range(blockStart, min(blockStart + blockSize,
    len(messageBytes))):

  21. blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize))

  22. blockInts.append(blockInt)

  23. return blockInts





  24. def getTextFromBlocks(blockInts, messageLength,
    blockSize=DEFAULT_BLOCK_SIZE):


  25. Converts a list of block integers to the original message string.




  26. The original message length is needed to properly convert the last




  27. block integer.



  28. message = []

  29. for blockInt in blockInts:

  30. blockMessage = []

  31. for i in range(blockSize - 1, -1, -1):

  32. if len(message) + i < messageLength:


  33. Decode the message string for the 128 (or whatever



Free download pdf