# Encryption and decryption of a file in Python – Rot 13 algorithm

In this tutorial, you will learn how to do encryption and decryption of a file using Python. Using cryptography we will learn about encryption and decryption of a file in Python.

## Cryptography:

Cryptography is the process of protecting data during communication using some algorithms. Generally, the meaning of cryptography was crypt means “vault” and graphy means “writing”. In a word, cryptography means protecting our data by encryption and decryption.
Encryption: In cryptography, encryption is the process of encoding our message or data into the scripted format, where only the authorized can understand it. The encoded data is called ciphertext.
Decryption: In cryptography, decryption is the process of decoding the encoded message back into the normal text format.

In cryptography, there are many algorithms. Some of them are:

• Rot 13 algorithm
• Data encryption standard algorithm (DES)
• Caesar cipher algorithm
• Triple DES algorithm

## Rot 13 algorithm in Python

Rot13 is a letter substitution cipher algorithm where it replaces the 13th alphabet letter after it.

Example of rot13 encryption algorithm:

```# rot13 encryption algorithm
f=open("file.txt","r")
f.close()
m2=""
a_m=[chr(i) for i in range(97,110)] # list of alphabets from a to m
n_z=[chr(i) for i in range(110,123)] #list of alphabets from n to z
for i in s:
if(i in a_m):
m2+=n_z[a_m.index(i)]
elif(i in n_z):
m2+=a_m[n_z.index(i)]
else:
m2+=i
f.close()
f=open("ecc.txt","w+")
for i in range(len(m2)):
f.write(m2[i])
f.close()

```

In the above program,

• In the first line of our script, we opened the file using the open() method and stored its contents in s using the read() method.
• As in the next line, a_m defines the list of alphabets from a to m and n_z defines the list of alphabets from n to z.
• Using for loop we solved the rot13 encryption algorithm in the above script.
• Finally, we open a new file and we store the encrypted contents into that new file and close the file.

#### Example of rot13 decryption algorithm:

```#rot13 decryption algorithm
f=open("ecc.txt","r")
f.close()
a_m=[chr(i) for i in range(97,110)] #list of alphabets from a to m
n_z=[chr(i) for i in range(110,123)]#list of alphabets from n to z
d2=""
for i in s:
if(i in a_m):
d2+=n_z[a_m.index(i)]
elif(i in n_z):
d2+=a_m[n_z.index(i)]
else:
d2+=i
f=open("dcc.txt","w+")
for i in range(len(d2)):
f.write(d2[i])
f.close()
```

In the above program,

• In the first line of our script, we opened the file using the open() method and stored its contents in s using the read() method.
• As in the next line, a_m defines the list of alphabets from a to m and n_z defines the list of alphabets from n to z.
• Using for loop we solved the rot13 decryption algorithm in the above script.
• Finally, we open a new file and store the decrypted contents into that new file and close the file.