394 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
file. Returns the encrypted message string.
- keySize, n, e = readKeyFile(keyFilename)
Check that key size is greater than block size.
- if keySize < blockSize 8: # 8 to convert bytes to bits
- 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))
Encrypt the message
- encryptedBlocks = encryptMessage(message, (n, e), blockSize)
Convert the large int values to one string value.
- for i in range(len(encryptedBlocks)):
- encryptedBlocks[i] = str(encryptedBlocks[i])
- encryptedContent = ','.join(encryptedBlocks)
Write out the encrypted string to the output file.
- encryptedContent = '%s%s%s' % (len(message), blockSize,
encryptedContent) - fo = open(messageFilename, 'w')
- fo.write(encryptedContent)
- fo.close()
Also return the encrypted string.
- return encryptedContent
- def readFromFileAndDecrypt(messageFilename, keyFilename):
Using a key from a key file, read an encrypted message from a file
and then decrypt it. Returns the decrypted message string.
- keySize, n, d = readKeyFile(keyFilename)
Read in the message length and the encrypted message from the file.
- fo = open(messageFilename)
- content = fo.read()
- messageLength, blockSize, encryptedMessage = content.split('_')
- messageLength = int(messageLength)
- blockSize = int(blockSize)
Check that key size is greater than block size.
- if keySize < blockSize 8: # 8 to convert bytes to bits
- 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