Activity 44: Documentation of Python Flask Encryption and Decryption

What is Python Flask Encryption and Decryption?

Encryption and decryption are two fundamental concepts in cryptography that are used to ensure the security of sensitive data.

  • Encryption: The process of converting readable data (plaintext) into an unreadable format (ciphertext) using an algorithm and an encryption key. This is done to protect sensitive information from unauthorized access. Only those who have the correct decryption key can convert the ciphertext back into its original form.

  • Decryption: The reverse process of encryption. It is the conversion of encrypted data (ciphertext) back into its readable form (plaintext) using a decryption key.

Python Flask is a lightweight web framework used to build web applications. In the context of encryption and decryption, Flask can provide the server-side logic to handle requests for encrypting and decrypting data, usually with the help of libraries like cryptography.

Importance of Python Flask Encryption and Decryption

  1. Data Security: Flask Encryption and Decryption help ensure that sensitive data (like passwords, credit card numbers, personal details) are not exposed in their original form. They are encrypted during transmission and storage.

  2. Compliance: Many industries are subject to regulatory requirements (e.g., HIPAA, GDPR) that mandate the encryption of sensitive data. Flask encryption helps meet these requirements.

  3. Authentication: Encryption is also crucial in authentication systems (e.g., OTPs, session tokens), ensuring that sensitive information like passwords or tokens are stored securely.

  4. Protection Against Data Breaches: Encrypted data is less likely to be useful to attackers if exposed, reducing the risk of data breaches.

The cryptography Library and Fernet

  • cryptography library: This Python library provides robust encryption tools, including symmetric encryption algorithms like Fernet.

  • Fernet: A symmetric encryption method that uses a single key for both encryption and decryption. It ensures that data is encrypted securely and provides a simple API for encrypting and decrypting messages.

Step-by-Step Guide for Activity 43: Python Flask Encryption and Decryption

Step 1: Set up your Environment

  1. Create a Virtual Environment:

    • Open Command Prompt or PowerShell.

    • Navigate to your project directory:

          codemkdir nicolas_python_flask_encryption_and_decryption
          cd nicolas_python_flask_encryption_and_decryption
      
    • Create the virtual environment:

          python -m venv env
      
    • Activate the virtual environment:

          .\env\Scripts\activate
      

Step 2: Install Flask and cryptography

Install the necessary libraries, Flask and cryptography, to handle the web app and encryption functionality:

pip install Flask cryptography

Step 3: Create app.py

Create a new file named app.py in your project folder.

  • Using Command Prompt

        echo. > app.py
    

Step 4: Write the Flask Application Code

Open your app.py where you would write the Flask application code.

Here’s the basic structure of my Flask app:

  1. Import Libraries: I first imported the necessary libraries (Flask, request, jsonify, and Fernet from cryptography).

  2. Create the Flask App: I created a new Flask application instance:

      app = Flask(__name__)
    
  3. Fernet Encryption Setup: Next, I generated an encryption key using the Fernet class from cryptography. The key will be used to both encrypt and decrypt the data:

      key = Fernet.generate_key()
      cipher_suite = Fernet(key)
    

Step 5: Adding the Encrypt Endpoint

Create an endpoint that would accept text and return the encrypted version. For this, I used a POST method and created a route /encrypt in Flask.

  1. Defined the route /encrypt that listens for POST requests:

      @app.route('/encrypt', methods=['POST'])
      def encrypt():
          try:
              data = request.json  # Get the incoming data
              text = data['text']  # Extract the text to encrypt
              encrypted_text = cipher_suite.encrypt(text.encode())  # Encrypt the text
              return jsonify({"encrypted_text": encrypted_text.decode()})
          except Exception as e:
              return jsonify({"error": str(e)}), 400
    
    • Here, I used request.json to get the JSON data sent in the POST request.

    • The text was encrypted using cipher_suite.encrypt().

    • The result was returned as a JSON response.

Step 6: Adding the Decrypt Endpoint

Similarly, I created another route /decrypt for handling decryption of the encrypted data. This endpoint listens for POST requests containing the encrypted text and then returns the decrypted version.

Here’s the code for the /decrypt endpoint:

@app.route('/decrypt', methods=['POST'])
def decrypt():
    try:
        data = request.json  # Get the encrypted data from the request
        encrypted_text = data['encrypted_text']  # Extract the encrypted text
        decrypted_text = cipher_suite.decrypt(encrypted_text.encode()).decode()  # Decrypt the text
        return jsonify({"decrypted_text": decrypted_text})
    except Exception as e:
        return jsonify({"error": str(e)}), 400
  • Used cipher_suite.decrypt() to decrypt the data.

  • The decrypted text was then returned as a JSON response.

Step 7: Run the Flask App

Run the app to start the Flask server:

python app.py

This will start the server on http://127.0.0.1:5000/

Step 8: Test the Endpoints Using Postman

  1. Test /encrypt Endpoint:

    • Open Postman

    • Set the method to POST and the URL to http://127.0.0.1:5000/encrypt.

    • In the Body section, select raw and JSON format, then enter:

          {
            "text": "Hello, this is a test."
          }
      
    • Send the request and verify the encrypted text response.

  2. Test /decrypt Endpoint:

    • Use the encrypted text received from the previous response

    • Set the method to POST and the URL to http://127.0.0.1:5000/decrypt

    • In the Body section, select raw and JSON format, then enter:

          {
            "encrypted_text": "gAAAAABlYlxrGJkjbfvKAHghFfD_TtQlN7rltfI4Y5wXB_E5eFdbflE_1z_RAn8Hpn2o37Z_lDZmTZcUMMZZvMkNlQ9I4JOhOoL-AvldHDWdfTVxHpBUn8g55f7c0qD4iA8yKw_JR3Zfx4F0LggG-9MkblPYVXQ6_O9YBsd01ltS6k_j0uI9DkhBZ3xi_w0ThsZXmdnb0dA"
          }
      
    • Send the request and verify the decrypted text response.

Step 9: Push to GitHub

  1.   git init
      git add .
      git commit -m "Initial commit"
      git remote add origin  https://github.com/MonetForProgrammingPurposes/cd-nicolas_python_flask_encryption_and_decryption.git
      git push -u origin master