Hacking Secret Ciphers with Python

(Ann) #1
Chapter 24 – Public Key Cryptography and the RSA Cipher 393



  1. blockSize is set to) characters from this block integer.



  2. asciiNumber = blockInt // (BYTE_SIZE ** i)

  3. blockInt = blockInt % (BYTE_SIZE ** i)

  4. blockMessage.insert(0, chr(asciiNumber))

  5. message.extend(blockMessage)

  6. return ''.join(message)





  7. def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE):


  8. Converts the message string into a list of block integers, and then




  9. encrypts each block integer. Pass the PUBLIC key to encrypt.



  10. encryptedBlocks = []

  11. n, e = key



  12. for block in getBlocksFromText(message, blockSize):


  13. ciphertext = plaintext ^ e mod n



  14. encryptedBlocks.append(pow(block, e, n))

  15. return encryptedBlocks





  16. def decryptMessage(encryptedBlocks, messageLength, key,
    blockSize=DEFAULT_BLOCK_SIZE):


  17. Decrypts a list of encrypted block ints into the original message




  18. string. The original message length is required to properly decrypt




  19. the last block. Be sure to pass the PRIVATE key to decrypt.



  20. decryptedBlocks = []

  21. n, d = key

  22. for block in encryptedBlocks:


  23. plaintext = ciphertext ^ d mod n



  24. decryptedBlocks.append(pow(block, d, n))

  25. return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)





  26. def readKeyFile(keyFilename):


  27. Given the filename of a file that contains a public or private key,




  28. return the key as a (n,e) or (n,d) tuple value.



  29. fo = open(keyFilename)

  30. content = fo.read()

  31. fo.close()

  32. keySize, n, EorD = content.split(',')

  33. return (int(keySize), int(n), int(EorD))





  34. def encryptAndWriteToFile(messageFilename, keyFilename, message,
    blockSize=DEFAULT_BLOCK_SIZE):


  35. Using a key from a key file, encrypt the message and save it to a



Free download pdf