Introduction to pycrypto

When it comes to encrypting information with Python, we have some options, but one of the most reliable is the PyCrypto cryptographic library, which supports functions for block-encryption, flow-encryption, and hash-calculation.

The PyCrypto module provides all needed functions for implementing strong cryptography in a Python program, including both hash functions and encryption algorithms.

For example, the block ciphers supported by pycrypto are:

  • AES
  • ARC2
  • Blowfish
  • CAST
  • DES
  • DES3
  • IDEA
  • RC5

In general, all these ciphers are used in the same way.

We can use the Crypto.Cipher package to import a specific cipher type:

from Crypto.Cipher import [Chiper_Type]

We can use the new method constructor to initialize the cipher:

new ([key], [mode], [Vector IV])

With this method, only the key is mandatory, and we must take into account whether the type of encryption requires that it has a specific size. The possible modes are MODE_ECB, MODE_CBC, MODE_CFB, MODE_PGP, MODE_OFB, MODE_CTR, and MODE_OPENPGP.

If the MODE_CBC or MODE_CFB modes are used, the third parameter (Vector IV) must be initialized, which allows an initial value to be given to the cipher. Some ciphers may have optional parameters, such as AES, which can specify the block and key size with the block_size and key_size parameters.

In the same way we have seen with hashlib, hash Functions also are supported by pycrypto. The use of general hash functions with pycrypto is similar:

  • We can use the Crypto.Hash package to import a specific hash type: from Crypto.Hash import [Hash Type]
  • We can use the update method to set the data we need obtain the hash: update('data')
  • We can use the hexdigest() method to generate the hash: hexdigest()

The following is the same example that we saw for obtaining the checksum of a file, in this case we are using pycrypt instead of hashlib.

You can find the following code in the hash.py file inside the pycrypto folder:

from Crypto.Hash import MD5

def md5Checksum(filePath):
fh = open(filePath, 'rb')
m = MD5.new()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()

print('The MD5 checksum is' + md5Checksum('hash.py'))

To encrypt and decrypt data, we can use the encrypt and decrypt functions:

encrypt ('clear text')
decrypt ('encrypted text')

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.37.10