Encrypting and encrypting information with pycryptodome

Encrypting and encrypting information with pycryptodome

Introduction to cryptography

Cryptography is the fascinating science and art of protecting information by transforming it into a secret form, only accessible to authorized parties. It plays a crucial role in our digital world, ensuring secure online transactions, secure communication, and protecting sensitive data. Here’s a comprehensive introduction to get you started:

1. Basic Concepts:

  • Plaintext: The original, understandable message.
  • Ciphertext: The scrambled and unreadable form of the message after encryption.
  • Encryption: The process of converting plaintext to ciphertext using a secret key or algorithm.
  • Decryption: The reverse process of converting ciphertext back to plaintext using the same key or algorithm.
  • Key: A secret piece of information used for encryption and decryption.

2. Types of Cryptography:

  • Symmetric Cryptography (Secret Key Cryptography): Both sender and receiver share a single secret key for encryption and decryption. Examples: AES, DES.
  • Asymmetric Cryptography (Public Key Cryptography): Uses two mathematically linked keys – a public key (widely distributed) and a private key (kept secret). Anyone can encrypt with the public key, but only the holder of the private key can decrypt. Examples: RSA, ECC.

3. Applications of Cryptography:

  • Secure communication: Protecting online communication like emails, chats, and video calls.
  • Secure transactions: Securing online payments, banking, and financial data.
  • Data privacy: Protecting sensitive data stored on hard drives, databases, and cloud storage.
  • Digital signatures: Ensuring the authenticity and integrity of electronic documents.
  • Virtual Private Networks (VPNs): Encrypting internet traffic for secure browsing and anonymity.

4. Why is Cryptography Important?

  • Privacy and security: Protects our personal information, financial data, and communications from unauthorized access.
  • Trust and confidence: Enables secure online transactions and interactions, building trust in digital services.
  • National security: Protects sensitive government information and critical infrastructure.

Cryptology is a complex and fascinating field, but this introduction should give you a solid foundation to dive deeper and explore its many applications in our digital world.

Remember, cryptography is a powerful tool, and it’s crucial to use it responsibly and ethically for the benefit of all.

Introduction to Pycryptodome

Pycryptodome is a self-contained Python package of low-level cryptographic primitives. It is a drop-in replacement for the older Pycrypto library. Pycryptodome is often used by developers and security professionals to perform cryptographic operations in Python applications.

Here’s a brief introduction to Pycryptodome:

  1. Installation:

    • You can install Pycryptodome using pip:
      pip install pycryptodome
      
  2. Supported Algorithms:

    • Pycryptodome supports a wide range of cryptographic algorithms, including symmetric and asymmetric ciphers, hash functions, digital signatures, key derivation functions, and more.
  3. Usage:

    • Pycryptodome provides a simple and consistent interface for cryptographic operations. You can use it to encrypt and decrypt data, generate digital signatures, hash data, work with secure random numbers, and more.
  4. Symmetric Ciphers:

    • Pycryptodome supports popular symmetric encryption algorithms such as AES (Advanced Encryption Standard), DES (Data Encryption Standard), and others.

      Example of using AES encryption:

      from Crypto.Cipher import AES
      from Crypto.Random import get_random_bytes
      
      key = get_random_bytes(16)
      cipher = AES.new(key, AES.MODE_EAX)
      
      plaintext = b'This is a secret message.'
      ciphertext, tag = cipher.encrypt_and_digest(plaintext)
      
      print('Ciphertext:', ciphertext)
      
  5. Asymmetric Ciphers:

    • Asymmetric encryption algorithms like RSA are also supported.

      Example of using RSA encryption:

      from Crypto.PublicKey import RSA
      from Crypto.Cipher import PKCS1_OAEP
      
      key = RSA.generate(2048)
      cipher = PKCS1_OAEP.new(key)
      
      plaintext = b'This is a secret message.'
      ciphertext = cipher.encrypt(plaintext)
      
      print('Ciphertext:', ciphertext)
      
  6. Hash Functions:

    • Pycryptodome includes hash functions such as SHA-256, SHA-3, MD5, and others.

      Example of using SHA-256:

      from Crypto.Hash import SHA256
      
      hasher = SHA256.new()
      hasher.update(b'This is some data to hash.')
      hash_value = hasher.digest()
      
      print('Hash:', hash_value)
      
  7. Digital Signatures:

    • Pycryptodome allows you to work with digital signatures using algorithms like RSA.

      Example of signing and verifying a message:

      from Crypto.Signature import pkcs1_15
      from Crypto.Hash import SHA256
      
      key = RSA.generate(2048)
      signer = pkcs1_15.new(key)
      
      message = b'This is a signed message.'
      signature = signer.sign(SHA256.new(message))
      
      # Verifying the signature
      verifier = pkcs1_15.new(key.publickey())
      try:
          verifier.verify(SHA256.new(message), signature)
          print('Signature is valid.')
      except (ValueError, TypeError):
          print('Signature is invalid.')
      

Pycryptodome is a powerful library that provides essential cryptographic functionality for Python developers. Always ensure you follow best practices and stay updated on cryptographic standards when working with sensitive data and cryptography.

MD5 hash function to obtain the checksum of a file

Python
from Crypto.Hash import MD5

def get_file_checksum(filename):
    # Create an MD5 hash object
    hash = MD5.new()
    
    # Define the chunk size for reading the file in chunks
    chunk_size = 8191
    
    # Open the file in binary mode for reading
    with open(filename, 'rb') as file:
        # Read the file in chunks and update the hash object
        while True:
            chunk = file.read(chunk_size)
            if len(chunk) == 0:
                break
            hash.update(chunk)
            
    # Return the hexadecimal representation of the MD5 hash
    return hash.hexdigest()

# Print the MD5 checksum of the specified file
print('The MD5 checksum is', get_file_checksum('checksSumFile.py'))

This Python script calculates the MD5 checksum of a file using the Crypto.Hash module from the Pycryptodome library. The MD5 checksum is a 128-bit hash value commonly used for data integrity verification. Here’s an explanation of the code:

Explanation:

  1. Importing the MD5 Module:

    • The script imports the MD5 module from the Crypto.Hash package provided by the Pycryptodome library.
  2. get_file_checksum Function:

    • The function takes a filename as an input parameter.
    • It creates an MD5 hash object using MD5.new().
  3. Calculating the MD5 Checksum:

    • The script reads the file in chunks defined by chunk_size (in this case, 8191 bytes).
    • It updates the MD5 hash object with each chunk using the update method.
  4. Hexadecimal Digest:

    • The function returns the hexadecimal representation of the MD5 hash using the hexdigest() method.
  5. Usage Example:

    • The script then prints the MD5 checksum of the specified file (checksSumFile.py in this case).
  6. Note:

    • The with statement is used to open the file. It ensures that the file is properly closed after reading, even if an exception occurs during the reading process.
  7. Indentation and Looping:

    • Pay attention to the indentation of the return statement. The return statement should be outside the while loop to ensure that the entire file is read before returning the checksum.

Encrypting and Decrypting with the DES algorithm

To encrypt and decrypt using the DES (Data Encryption Standard) algorithm in Python, you can use the Crypto.Cipher module from the Pycryptodome library. DES is a symmetric-key algorithm, meaning the same key is used for both encryption and decryption.

Python
from Crypto.Cipher import DES

# Fill with spaces the user until 8 characters
user =  "user    ".encode("utf8")
message = "message ".encode("utf8")

key='mycipher'

# we create the cipher with DES
cipher = DES.new(key.encode("utf8"),DES.MODE_ECB)

# encrypt username and message
cipher_user = cipher.encrypt(user)
cipher_message = cipher.encrypt(message)

print("Cipher User: " + str(cipher_user))
print("Cipher message: " + str(cipher_message))

# We simulate the server where the messages arrive encrypted
cipher = DES.new(key.encode("utf8"),DES.MODE_ECB)
decipher_user = cipher.decrypt(cipher_user)
decipher_message = cipher.decrypt(cipher_message)

print("Decipher user: " + str(decipher_user.decode()))
print("Decipher Message: " + str(decipher_message.decode()))

This Python script demonstrates the use of the DES (Data Encryption Standard) algorithm for encrypting and decrypting a user and message. The DES algorithm is used from the Crypto.Cipher module provided by the Pycryptodome library. Here’s an explanation of the code:

Explanation:

  1. Padding:

    • The script begins by encoding the user and message strings in UTF-8 and ensuring the user string is 8 characters long by filling it with spaces.
  2. Key:

    • The variable key is set to ‘mycipher’, which is used as the encryption key. Note that for DES, the key must be 8 bytes long.
  3. Cipher Object:

    • A DES cipher object is created using the ECB (Electronic Codebook) mode with the specified key.
  4. Encryption:

    • The encrypt method is used to encrypt the user and message strings separately.
  5. Print Encrypted Values:

    • The encrypted values (cipher_user and cipher_message) are printed.
  6. Server Simulation:

    • The script simulates a server where the encrypted messages arrive. Another DES cipher object is created for decryption.
  7. Decryption:

    • The decrypt method is used to decrypt the received encrypted user and message.
  8. Print Decrypted Values:

    • The decrypted values (decipher_user and decipher_message) are printed.

Keep in mind that DES is considered insecure for many applications due to its short key length. For stronger security, consider using a more modern algorithm like AES with a longer key length. Additionally, using modes other than ECB (Electronic Codebook) may provide better security in practical applications.

Encrypting and Decrypting with the AES algorithm

The Advanced Encryption Standard (AES) is a symmetric encryption algorithm established by the U.S. National Institute of Standards and Technology (NIST) in 2001. It is widely used and considered secure for a broad range of applications. AES operates on blocks of data and supports key sizes of 128, 192, or 256 bits.

key characteristics of the AES algorithm:

  1. Block Cipher:

    • AES operates on fixed-size blocks of data, and the block size is 128 bits (16 bytes).
  2. Key Sizes:

    • AES supports three key sizes: 128 bits, 192 bits, and 256 bits.
  3. Rounds:

    • The number of rounds (iterations) in the AES algorithm depends on the key size. It has 10 rounds for 128-bit keys, 12 rounds for 192-bit keys, and 14 rounds for 256-bit keys.
  4. Substitution-Permutation Network:

    • AES uses a substitution-permutation network (SPN) structure. It involves substitution (SubBytes), permutation (ShiftRows), mixing (MixColumns), and adding a round key (AddRoundKey) operations in each round.
  5. Key Expansion:

    • The original key is expanded to create a set of round keys used in each round of the algorithm.
  6. Security:

    • AES is considered secure against known cryptographic attacks when used with an appropriate key size. As of my last knowledge update in January 2022, there have been no practical attacks against the full AES algorithm.
  7. Modes of Operation:

    • AES can be used in different modes of operation, such as Electronic Codebook (ECB), Cipher Block Chaining (CBC), Counter (CTR), Galois/Counter Mode (GCM), etc., depending on the desired properties and use case.
  8. Applications:

    • AES is widely used for securing sensitive data in various applications, including encryption of communication over the internet (e.g., TLS/SSL), disk encryption, file encryption, and more.

Here’s a simplified example of the AES encryption process:

  • Key Expansion: Generate a set of round keys from the original key.

  • Initial Round: AddRoundKey operation with the initial key.

  • Main Rounds (10, 12, or 14):

    • SubBytes: Substitute each byte with another byte from the S-Box.
    • ShiftRows: Permute the bytes within each row.
    • MixColumns: Mix the bytes within each column.
    • AddRoundKey: XOR the state with the round key.
  • Final Round:

    • Similar to the main rounds but without the MixColumns operation.

The AES decryption process is the inverse of the encryption process, involving operations such as InvSubBytes, InvShiftRows, InvMixColumns, and InvAddRoundKey.

Python
from Crypto.Cipher import AES

# Key has to be 16, 24, or 32 bytes long
key = "secret-key-12345"

# Create an AES cipher object in CBC mode with a specified IV (Initialization Vector)
encrypt_AES = AES.new(key.encode("utf8"), AES.MODE_CBC, 'This is an IV-12'.encode("utf8"))

# Fill with spaces the user until 32 characters
message = "This is the secret message      ".encode("utf8")

# Encrypt the message
ciphertext = encrypt_AES.encrypt(message)
print("Cipher text:", ciphertext)

# Create a new AES cipher object for decryption with the same key and IV
decrypt_AES = AES.new(key.encode("utf8"), AES.MODE_CBC, 'This is an IV-12'.encode("utf8"))

# Decrypt the ciphertext
message_decrypted = decrypt_AES.decrypt(ciphertext)

# Print the decrypted message after stripping trailing spaces
print("Decrypted text:", message_decrypted.strip().decode())

This Python script demonstrates how to encrypt and decrypt a message using the AES algorithm in CBC (Cipher Block Chaining) mode. Here’s an explanation of the code:

Explanation:

  1. Key and IV:

    • The key is the secret key used for encryption and decryption. It must be 16, 24, or 32 bytes long for AES-128, AES-192, or AES-256, respectively.
    • An Initialization Vector (IV) is used in CBC mode to provide an additional layer of security. It should be a block size (16 bytes) long.
  2. Encryption:

    • An AES cipher object (encrypt_AES) is created with the key, mode (CBC), and IV for encryption.
    • The message is padded and then encrypted using the encrypt method of the cipher object.
  3. Decryption:

    • Another AES cipher object (decrypt_AES) is created with the same key, mode, and IV for decryption.
    • The ciphertext is decrypted using the decrypt method of the cipher object.
  4. Output:

    • The encrypted ciphertext and the decrypted message are printed.

Enhance security by using a key derivation function (PBKDF2) to derive a key from a password

Python
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto import Random

# Key has to be 16, 24, or 32 bytes long
password = "secret-key-12345"

# Parameters for key derivation
iterations = 10000
key_size = 16
salt = Random.new().read(key_size)
iv = Random.new().read(AES.block_size)

# Derive a key from the password using PBKDF2
derived_key = PBKDF2(password, salt, key_size, iterations)

# Create an AES cipher object in CBC mode with the derived key and IV
encrypt_AES = AES.new(derived_key, AES.MODE_CBC, iv)

# Fill with spaces the user until 32 characters
message = "This is the secret message      ".encode("utf8")

# Encrypt the message
ciphertext = encrypt_AES.encrypt(message)
print("Cipher text:", ciphertext)

# Create a new AES cipher object for decryption with the derived key and IV
decrypt_AES = AES.new(derived_key, AES.MODE_CBC, iv)

# Decrypt the ciphertext
message_decrypted = decrypt_AES.decrypt(ciphertext)

# Print the decrypted message after stripping trailing spaces
print("Decrypted text:", message_decrypted.strip().decode())

Explanation:

  1. Key Derivation:

    • Instead of using a static key, a key is derived from a password using the PBKDF2 key derivation function.
    • The key derivation parameters include the password, a random salt, key size, and the number of iterations.
  2. Encryption and Decryption:

    • The derived key is used to create an AES cipher object for encryption and decryption.
    • The rest of the encryption and decryption process remains the same as in the previous example.
  3. Security Considerations:

    • Using a key derivation function like PBKDF2 strengthens the security of the system by making it computationally expensive for an attacker to brute-force the password.
    • Random values (salt and IV) are crucial for adding entropy and preventing certain types of attacks.

File encryption with AES

Python
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import os, random, struct
from Crypto import Random

def encrypt_file(key, filename):
    chunk_size = 64*1024

    output_filename = filename + '.encrypted'

    # Random Initialization vector
    iv = Random.new().read(AES.block_size)

    #create the encryption cipher
    encryptor = AES.new(key, AES.MODE_CBC, iv)

    #Determine the size of the file
    filesize = os.path.getsize(filename)
	
	#Open the output file and write the size of the file. 
	#We use the struct package for the purpose.
    with open(filename, 'rb') as inputfile:
        with open(output_filename, 'wb') as outputfile:
            outputfile.write(struct.pack(', filesize))
            outputfile.write(iv)
            
            while True:
                chunk = inputfile.read(chunk_size)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += bytes(' ','utf-8') * (16 - len(chunk) % 16)

                outputfile.write(encryptor.encrypt(chunk))


def decrypt_file(key, filename):
    chunk_size = 64*1024

    output_filename = os.path.splitext(filename)[0]
	
	#open the encrypted file and read the file size and the initialization vector. 
	#The IV is required for creating the cipher.
    with open(filename, 'rb') as infile:
        origsize = struct.unpack(', infile.read(struct.calcsize('Q')))[0]
        iv = infile.read(16)
		
		#create the cipher using the key and the IV.
        decryptor = AES.new(key, AES.MODE_CBC, iv)
		
		#We also write the decrypted data to a verification file, 
		#so we can check the results of the encryption 
		#and decryption by comparing with the original file.
        with open(output_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunk_size)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))

            outfile.truncate(origsize)


def getKey(password):
    hasher = SHA256.new(password)
    return hasher.digest()


def main():
    choice = input("do you want to (E)ncrypt or (D)ecrypt?: ")
    
    if choice == 'E':
        filename = input('file to encrypt: ')
        password = input('password: ')
        encrypt_file(getKey(password.encode("utf8")), filename)
        print('done.')

    elif choice == 'D':
        filename = input('file to decrypt: ')
        password = input('password: ')
        decrypt_file(getKey(password.encode("utf8")), filename)
        print('done.')

    else:
        print('no option selected.')

if __name__ == "__main__":
    main()
    

Explanation:

  1. Encryption (encrypt_file function):

    • The file is encrypted using the AES algorithm in CBC mode with a randomly generated Initialization Vector (IV).
    • The file size and IV are written to the output file.
    • The file is read in chunks, padded if necessary, and encrypted.
  2. Decryption (decrypt_file function):

    • The encrypted file is read, and the file size and IV are extracted.
    • The file is decrypted using the key, IV, and the AES algorithm in CBC mode.
    • The decrypted data is written to an output file, which is truncated to the original file size.
  3. Key Derivation (getKey function):

    • The user’s password is hashed using the SHA-256 algorithm to derive a key.
  4. User Interface (main function):

    • The user is prompted to choose between encryption and decryption.
    • The user provides the filename and password.
    • The appropriate function is called based on the user’s choice.

Generating RSA signature using pycryptodome

Python
from Crypto.PublicKey import RSA 
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5

def generate(bit_size):
    keys = RSA.generate(bit_size)
    return keys

def encrypt(pub_key, data):
    cipher = PKCS1_OAEP.new(pub_key)
    return cipher.encrypt(data)

def decrypt(priv_key, data):
    cipher = PKCS1_OAEP.new(priv_key)
    return cipher.decrypt(data)

keys = generate(2048)

print("Public key:")
print(keys.publickey().export_key('PEM').decode(), end='\n\n')
with open("public.key",'wb') as file:
    file.write(keys.publickey().export_key())

print("Private Key:")
print(keys.export_key('PEM').decode())
with open("private.key",'wb') as file:
    file.write(keys.export_key('PEM'))

text2cipher = "text2cipher".encode("utf8")

hasher = SHA256.new(text2cipher)
signer = PKCS1_v1_5.new(keys)
signature = signer.sign(hasher)

verifier = PKCS1_v1_5.new(keys)
if verifier.verify(hasher, signature):
    print('The signature is valid!')
else:
    print('The message was signed with the wrong private key or modified')
 
encrypted_data = encrypt(keys.publickey(),text2cipher)
print("Text encrypted:",encrypted_data)

decrypted_data = decrypt(keys,encrypted_data)
print("Text Decrypted:",decrypted_data.decode())

It demonstrates the generation of an RSA key pair, encryption and decryption of data, and the signing and verification of a message using the RSA algorithm and various cryptographic modules from the Crypto library:

Explanation:

  1. Key Generation (generate):

    • Generates an RSA key pair with a specified bit size (2048 in this case).
  2. Encryption (encrypt):

    • Uses the public key to encrypt data using the PKCS1_OAEP cipher.
  3. Decryption (decrypt):

    • Uses the private key to decrypt data using the PKCS1_OAEP cipher.
  4. Signing (sign):

    • Creates a digital signature for a message using the PKCS1_v1_5 signature scheme.
  5. Verification (verify):

    • Verifies the signature of a message using the PKCS1_v1_5 signature scheme.
  6. Example Usage:

    • Generates an RSA key pair.
    • Prints and saves the public and private keys.
    • Signs and verifies a message.
    • Encrypts and decrypts a message.
Total
3
Shares

Leave a Reply

Previous Post
Chrome forensic with python

Chrome forensic with python

Next Post
Encrypting and Decrypting information with cryptography

Encrypting and Decrypting information with cryptography

Related Posts