StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Monday, April 5, 2021

Cryptography in Python

 April 05, 2021     Python     No comments   

Often there is a need to encrypt data for storing in a database or transferring to another entity for processing. Python cryptography is a package which provides cryptographic recipes and primitives to Python developers. In this article we will see how to use the cryptography package to encrypt and decrypt data.

Terminology basics

Cryptography is associated with the process of converting ordinary plain text into unintelligible text and vice-versa.

Encryption is the process of taking plain text and scrambling it into an unreadable format of “cipher text.” 

Decryption is the process of transforming data that has been rendered unreadable through encryption back to its unencrypted form

Key is a secret, like a password used to encrypt and decrypt data.

Symmetric Key Cryptography also known as secret key cryptography and the encryption and decryption process use the same key. Examples include AES, DES, 3DES etc.

Asymmetric Key Cryptography also knows as public key cryptography and uses two keys in which one key will encrypt and other key will decrypt. Examples include Diffie-Hellman, DSA, RSA etc.

Python cryptography includes both high level recipes and low level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests, and key derivation functions.

Fernet (Symmetric Key) example

Fernet is an implementation of symmetric (also known as “secret key”) authenticated cryptography. Fernet is built on top of a number of standard cryptographic primitives.

In this example, we use a predefined encryption key which needs to be securely stored in a secret store. Another variation is to use an additional password through a key derivation function.

from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt

import base64

encryption_key = "Test"
passwd = "mypasswd"

def encrypt(text):
    kdf = Scrypt(salt=encryption_key.encode(), length=32, n=2 ** 14, r=8, p=1)
    key = base64.urlsafe_b64encode(kdf.derive(b""))
    fernet = Fernet(key)
    return base64.b64encode(fernet.encrypt(str.encode(text)))


def decrypt(enc):
    kdf = Scrypt(salt=encryption_key.encode(), length=32, n=2 ** 14, r=8, p=1)
    key = base64.urlsafe_b64encode(kdf.derive(b""))
    fernet = Fernet(key)
    decoded_str = base64.b64decode(enc)
    return fernet.decrypt(decoded_str).decode()


def encrypt_with_passwd(text):
    kdf = Scrypt(salt=encryption_key.encode(), length=32, n=2 ** 14, r=8, p=1)
    key = base64.urlsafe_b64encode(kdf.derive(passwd.encode()))
    fernet = Fernet(key)
    return base64.b64encode(fernet.encrypt(str.encode(text)))


def decrypt_with_passwd(enc):
    kdf = Scrypt(salt=encryption_key.encode(), length=32, n=2 ** 14, r=8, p=1)
    key = base64.urlsafe_b64encode(kdf.derive(passwd.encode()))
    fernet = Fernet(key)
    decoded_str = base64.b64decode(enc)
    return fernet.decrypt(decoded_str).decode()


encrypted_string = encrypt("Hello")
print("Encrypted string is " + str(encrypted_string))
print("Decrypted string is " + decrypt(encrypted_string))

encrypted_string = encrypt_with_passwd("Hello World")
print("Encrypted string is " + str(encrypted_string))
print("Decrypted string is " + decrypt_with_passwd(encrypted_string))
Output is:
Encrypted string is b'Z0FBQUFBQmdiQ3VIVG9UalpzR2s5MlBxV2I2U003d21Ba044RDZxelc3Z2JURGdmbXloSXNDeHM0RUtaQ2FvZHRYclBtOGpoVFdqSzA5NlpEZm5TVVlJb0VkY1Nza0VIMmc9PQ=='
Decrypted string is Hello
Encrypted string is b'Z0FBQUFBQmdiQ3VIbVRSOFF2LTJVQ0RLX05fT1BKcEhtSk5iWFcwWlB0eWRXZFhZWlk1OEV6NnJ2UHhlQkxlRHdmajRCUGVuUVBFdzlPbXdMS3hVa2x0dVZXX0U0c0VNaWc9PQ=='
Decrypted string is Hello World

Note on Parameters:
  • salt (bytes) – A salt. 
  • length (int) – The desired length of the derived key in bytes. 
  • n (int) – CPU/Memory cost parameter. It must be larger than 1 and be a power of 2. 
  • r (int) – Block size parameter. 
  • p (int) – Parallelization parameter.
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk