One-Time Pad Encryption - In Python

In this code, no library used and everything done by standard functions of python. Simple and easy to understand.
This code reads plain text and key from text files.
This program was written by Shooresh Sufiye. you can copy and change it, But don't forget to mention the source.

# Written by:  Shooresh Sufiye
#
f = open("plain.txt", "r")
allplain = f.read()
f.close()
print ("plain text:\n ", allplain)

f = open("plain.txt", "rb+")
kf = open ("key.txt", "rb" )
f2= open("cipher.txt", "r+")

allplain = f.read()
key =[]
key = kf.read()
#   - encrypt plain text and save into cipher.txt

for i in range(len(allplain)):
    k = chr (key[i])
    p = chr (allplain[i])
    c = chr ((ord(p)) ^ (ord(k)))
    f2.write(c)

f.close()
f2.close()
kf.close()


f2 = open("plain2.txt", "r+")
kf = open ("key.txt", "rb" )
f= open("cipher.txt", "rb+")

allplain = f.read()
key = kf.read()
#----------- decrypt cipher.txt content, and save it to plain2.txt
for i in range(len(allplain)):
    k=chr (key[i])
    p=chr (allplain[i])
    c = chr((ord(p)) ^ (ord(k)))
    f2.write(c)

f.close()
f2.close()
kf.close()

#----------- open files to see the results
f2 = open ("cipher.txt" , "r")
f = open ("plain2.txt", "r")

encoded = f2.read()
decoded = f.read()

print("\nencrypted to:\n ", encoded)
print("\ndecrypted to:\n ", decoded)

f.close()
f2.close()
input()
# END

Comments

Popular posts from this blog

RSA encryption in JAVA with custom key length