Introduction To Data Encryption With Python

samcodesign

Sam

Posted on March 8, 2020

Introduction To Data Encryption With Python

Summary:

  1. Cryptography

    1. Definition
    2. Terminologies of Cryptography
  2. Reverse Cipher

    1. Example
    2. Python Basics
    3. Coding a Reverse Cipher program
  3. Algorithm of Caesar Cipher

    1. Coding Time
    2. Getting the Caesar cipher key
    3. Using the key to find the password
  4. Algorithm ROT 13 Cipher

    1. Definition
  5. Creating A Cipher

    1. Installing the library
    2. Testing the library
    3. Generating a key
    4. Encrypting
    5. Decrypting
  6. Bonus

    1. Generating a Key From A Password
    2. Encrypting and Decrypting Files

video

1. Cryptography

1.1 Definition

Cryptography is the art of communication between two users via coded messages. The science of cryptography emerged with the basic motive of providing security to the confidential messages transferred from one party to another.

The pre-fix "crypt" means "hidden" or "vault" and the suffix "graphy" stands for "writing".

Cryptography is defined as the art and science of concealing the message to introduce privacy and secrecy as recognized in information security.

1.2 Terminologies of Cryptography:

  • Plain Text (Texte Brut):

    ​ The text which is readable and can be understood by all users.

  • Cipher Text (Texte Chiffré):

    ​ The message obtained after applying cryptography on plain text.

  • Encryption (Chiffrement):

    ​ The process of converting (from plain text to Cipher text).

  • Decryption (Décryptage):

    ​ The process of converting (from cipher text to plain text).

    (Drawing a schema)

 2. Reverse Cipher

 2.1 Example:

Let’s examine the following examples of Plaintext and Reverse Cipher

  1. Every skill acquired in cyber security is hard won. It includes a wide array of prerequisites (even) to get started.

  2. edrtarts teg ot setisiuqererp fo yarra a sedulcni now drah si ytiruces rebyc ni deriuqca lliks yrevE.

With statement (1), anybody can read and understand it clearly. What about statement 2 — it’s absolute gibberish, or so it seems like it. However, a cryptanalyst may be able to decrypt the concept of statement (2).

In the examples above, statement (1) is plain text, while statement (2) is a reverse cipher text. Thus, cryptography is defined as the art of manipulating or scrambling plain text into cipher text.

 2.2 Python Basics

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.

# Printing a "Hello World!"
print("Hello world!")

# Declaration of strings is shown below:
variable_name_string = "Variable content string"
print(variable_name_string)

# He lists of python can be declared as compound data types, separated by commas and enclosed within square brackets ([]).
list = [ 'abcd', 786 , 2.23, 'rocky', 70.2 ]
tinylist = [123, 'rocky']
print(list[0])
print(tinylist)

# Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python, which are usually numbers or strings.
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)
print(thisdict["model"]) # Note the difference

# Printing the values
for x in thisdict:
  print(x)

# Printing the keys
for x in thisdict:
  print(thisdict[x])

# Printing keys + values
for x, y in thisdict.items():
  print(x, y) 

# adding a key and its value
thisdict["color"] = "red"
print(thisdict)

# removing the first item (here it's brand)
thisdict.popitem()
print(thisdict)

# The del keyword removes the item with the specified key name
del thisdict["model"]
print(thisdict)
Enter fullscreen mode Exit fullscreen mode

2.3 Coding a Reverse Cipher Program:

(Making a suitable algorithm for this case) -> Cipher type = Reverse Cipher.


message = 'This is program to explain reverse cipher.'
translated = '' #cipher text is stored in this variable
i = len(message) - 1

while i >= 0:
   translated = translated + message[i]
   i = i - 1
print("The cipher text is : ", translated)
Enter fullscreen mode Exit fullscreen mode

3. Algorithm of Caesar Cipher

The algorithm of Caesar cipher holds the following features:

  • Caesar Cipher Technique is the simple and easy method of encryption technique.
  • It is simple type of substitution cipher.
  • Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.

Algorithm of Caesar Cipher


#A python program to illustrate Caesar Cipher Technique 
def encrypt(text,s): 
    result = "" 

    # traverse text 
    for i in range(len(text)): 
        char = text[i] 

        # Encrypt uppercase characters 
        if (char.isupper()): 
            result += chr((ord(char) + s-65) % 26 + 65) 

        # Encrypt lowercase characters 
        else: 
            result += chr((ord(char) + s - 97) % 26 + 97) 

    return result 

#check the above function 
text = "CIPHER CAESAR ENCRYPTION"
s = 4
print ("Text : " + text) 
print ("Shift : " + str(s)) 
print ("Cipher: " + encrypt(text,s))
Enter fullscreen mode Exit fullscreen mode

3.2 Getting the key


message = 'GIEWIVrGMTLIVrHIQS' #encrypted message
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

for key in range(len(LETTERS)):
   translated = ''
   for symbol in message:
      if symbol in LETTERS:
         num = LETTERS.find(symbol)
         num = num - key
         if num < 0:
            num = num + len(LETTERS)
         translated = translated + LETTERS[num]
      else:
         translated = translated + symbol
print('Hacking key #%s: %s' % (key, translated))
Enter fullscreen mode Exit fullscreen mode

3.3 Hacking the CAESAR cipher using the Key


import string
from time import sleep

alphabet = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz"

def decrypt():

    print("Welcome to Caesar Cipher Decryption.\n")
    encrypted_message = input("Enter the message you would like to decrypt: ").strip()
    print()
    key = int(input("Enter key to decrypt: "))

    decrypted_message = ""

    for c in encrypted_message:

        if c in alphabet:
            position = alphabet.find(c)
            new_position = (position - key) % 26
            new_character = alphabet[new_position]
            decrypted_message += new_character
        else:
            decrypted_message += c

    print("\nDecrypting your message...\n")
    sleep(2) # give an appearance of doing something complicated
    print("Stand by, almost finished...\n")
    sleep(2) # more of the same
    print("Your decrypted message is:\n")
    print(decrypted_message)

decrypt()
Enter fullscreen mode Exit fullscreen mode

4. Algorithm ROT 13 Cipher

4.1 Definition

​ ROT 13 cipher refers to the abbreviated form Rotate by 13 places. It is a special case of Caesar Cipher in which shift is always 13. Every letter is shifted by 13 places to encrypt or decrypt the message.

ROT13 Algorithm Process

5. Let's Cipher

5.1 Installing the library

pip -m install cryptography
Enter fullscreen mode Exit fullscreen mode

5.2 Testing the library

import cryptography
Enter fullscreen mode Exit fullscreen mode

5.3 Generating a key

from cryptography.fernet import Fernet as fn

test_key = fn.generate_key()
print(test_key)
file = open('test_key.key', 'wb')
file.write(test_key)
file.close()
Enter fullscreen mode Exit fullscreen mode

5.4 Encrypting a message

from cryptography.fernet import Fernet as ft

message = input("\n Veuillez entrer le message que vous souhaiter crypter: \n").encode()

file = open('test_key.key', 'rb')
key = file.read()

f = ft(key)
encrypted_message = f.encrypt(message)
print("\n", encrypted_message)
file.close()
Enter fullscreen mode Exit fullscreen mode

 5.5 Decrypting a Cipher

from cryptography.fernet import Fernet as ft

encypted_message = input("\n Veuillez coller le chiffrement à décrypter: \n\t").encode()

file = open('test_key.key', 'rb')
key = file.read()
f = ft(key)
decrypted_message = f.decrypt(encypted_message)
print("\n ", decrypted_message)
file.close()
Enter fullscreen mode Exit fullscreen mode

6. Bonus

6.1 Generating a Key From A Password

​ If you want to base your key of a string that the user can input or some other form of input, you can create a key using this input.

import base64
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

password_provided = "password" # This is input in the form of a string
password = password_provided.encode() # Convert to type bytes
salt = b'salt_' # CHANGE THIS - recommend using a key from os.urandom(16), must be of type bytes
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000,
    backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(password)) # Can only use kdf once
Enter fullscreen mode Exit fullscreen mode

6.2 Encrypting and Decrypting Files

​ We can also encrypt files using this method since files can be read as bytes. Simply open the file, read the bytes, encrypt the data and the write them out to a new file. To encrypt:

from cryptography.fernet import Fernet
key = b'' # Use one of the methods to get a key (it must be the same when decrypting)
input_file = 'test.txt'
output_file = 'test.encrypted'

with open(input_file, 'rb') as f:
    data = f.read()

fernet = Fernet(key)
encrypted = fernet.encrypt(data)

with open(output_file, 'wb') as f:
    f.write(encrypted)

# You can delete input_file if you want
Enter fullscreen mode Exit fullscreen mode

And then to decrypt a file:

from cryptography.fernet import Fernet
key = b'' # Use one of the methods to get a key (it must be the same as used in encrypting)
input_file = 'test.encrypted'
output_file = 'test.txt'

with open(input_file, 'rb') as f:
    data = f.read()

fernet = Fernet(key)
encrypted = fernet.decrypt(data)

with open(output_file, 'wb') as f:
    f.write(encrypted)

# You can delete input_file if you want
Enter fullscreen mode Exit fullscreen mode

video

💖 💪 🙅 🚩
samcodesign
Sam

Posted on March 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related