Introduction To Data Encryption With Python
Tags: python, cryptography, cybersecurity
Published: 2020-03-08 20:35:41



> ***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](https://media.giphy.com/media/BemKqR9RDK4V2/giphy.gif)

## 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](https://en.wikipedia.org/wiki/Interpreted_language), [high-level](https://en.wikipedia.org/wiki/High-level_programming_language), [general-purpose](https://en.wikipedia.org/wiki/General-purpose_programming_language) [programming language](https://en.wikipedia.org/wiki/Programming_language). Created by [Guido van Rossum](https://en.wikipedia.org/wiki/Guido_van_Rossum) and first released in 1991, Python's design philosophy emphasizes [code readability](https://en.wikipedia.org/wiki/Code_readability) with its notable use of [significant whitespace](https://en.wikipedia.org/wiki/Off-side_rule). Its language constructs and [object-oriented](https://en.wikipedia.org/wiki/Object-oriented_programming) approach aim to help programmers write clear, logical code for small and large-scale projects.

```python
# 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)
```



### 2.3 Coding a Reverse Cipher Program:

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

____

```python
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)
```



## 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](https://www.tutorialspoint.com/cryptography_with_python/images/algorithm_caesar_cipher.jpg)

--------------

```python
#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))
```

#### 3.2 Getting the key

------------

```python
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))
```



#### 3.3 Hacking the CAESAR cipher using the Key

-----------------

```python
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()
```



## 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](https://www.tutorialspoint.com/cryptography_with_python/images/rot.jpg)



<iframe src="https://giphy.com/embed/3oEjHWbXcpeKhTktXi" width="480" height="440" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/producthunt-coding-hacking-hacker-time-3oEjHWbXcpeKhTktXi"></a></p>



## 5. Let's Cipher

### 5.1 Installing the library

```sh
pip -m install cryptography
```

-------------



### 5.2 Testing the library

```python
import cryptography
```

--------------



### 5.3 Generating a key

```python
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()
```

------



### 5.4 Encrypting a message

```python
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()
```

------



### 5.5 Decrypting a Cipher

```python
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()
```

----------



## 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.

```python
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
```

### 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:

```python
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
```

And then to **decrypt** a file:

```python
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
```
![video](https://media.giphy.com/media/dkuZHIQsslFfy/giphy.gif)