Data Encryption and Decryption in Python

    python-logo

    In this post, we will learn how to implement data encryption and decryption in Python using the PyCryptoDome library. Encryption is the process of converting plaintext data into an unreadable format, called ciphertext, to protect its confidentiality. Decryption is the process of converting ciphertext back into plaintext, making it readable again.

    Installing PyCryptoDome

    To get started, you need to install the PyCryptoDome library, which is an easy-to-use cryptographic library for Python. You can install it using pip:

    pip install pycryptodome

    Encrypting Data

    First, let's see how to encrypt data using AES (Advanced Encryption Standard) encryption. We will create a function called encrypt_data that takes a message and a secret key as input and returns the encrypted data.

    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes
    
    def encrypt_data(message, key):
        cipher = AES.new(key, AES.MODE_EAX)
        nonce = cipher.nonce
        ciphertext, _ = cipher.encrypt_and_digest(message.encode('utf-8'))
        return (nonce, ciphertext)
    def decrypt_data(nonce, ciphertext, key):
        cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
        decrypted_data = cipher.decrypt(ciphertext)
        return decrypted_data.decode('utf-8')

    Decrypting Data

    Now let's create a function called decrypt_data that takes the encrypted data (nonce and ciphertext) and the secret key as input, and returns the decrypted message.

    def decrypt_data(nonce, ciphertext, key):
    cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
    decrypted_data = cipher.decrypt(ciphertext)
    return decrypted_data.decode('utf-8')

    Example Usage

    Here's an example of how to use the encrypt_data and decrypt_data functions to encrypt and decrypt a message:

    key = get_random_bytes(16)
    message = "This is a secret message."
    
    # Encrypt the message
    nonce, ciphertext = encrypt_data(message, key)
    print("Encrypted data:", ciphertext)
    
    # Decrypt the message
    decrypted_message = decrypt_data(nonce, ciphertext, key)
    print("Decrypted data:", decrypted_message)

    Conclusion

    In this post, we've learned how to implement data encryption and decryption in Python using the PyCryptoDome library. This is a simple and effective way to protect sensitive information in your applications. Remember to keep your secret keys secure, as they are the key to unlocking your encrypted data.