Wednesday, January 10, 2018

otp , one-time pad

#!/usr/bin/python
import binascii
import random
import sys
import re

def genpad(padlen):
    pad = ""
    for i in range(0,padlen):
        pad +=chr(random.randint(0,255))
    return pad

def otp(text, chars):
    hextext = binascii.hexlify(text)
    xorres = ""
    n = 1
    for i,j in zip(text,chars):
        xorout = chr(int(bin(ord(i) ^ ord(j)),2))
        xorres += xorout
        n +=1
    return xorres

def deotp(text,chars):
    hextext = binascii.hexlify(text)
    xorres = ""
    n = 1
    for i,j in zip(text,chars):

        xorout = chr(int(bin(ord(i) ^ ord(j)),2))

        xorres += xorout
        n +=1
    return xorres



if sys.argv[1]=="encrypt":
    inputfile = sys.argv[2]
    padname = sys.argv[3]

    with open(inputfile) as f:
        fr = f.read()
        # print fr
        yourpad = genpad(len(fr))
        ciphertext = otp(fr,yourpad)

    with open(inputfile+".enc", "wr") as f:
        f.write(ciphertext)
        print "the encrpyted text saved in " + inputfile + ".enc"

   
    with open(padname,"wr") as f:
        f.write(yourpad)
        print "your pad is save to " + padname
        print "pls keep it."


if sys.argv[1]=="decrypt":
    inputfile = sys.argv[2]
    # output = re.sub(r"\.enc$"inputfile)
    padname = sys.argv[3]
    with open(padname,"r") as f:
        pad = f.read()

    with open(inputfile) as f:
        fr = f.read()
        secfile = otp(fr,pad)
    with open(inputfile+".dec", "wr") as f:
        f.write(secfile)
        print "the decrpyted text saved in " + inputfile + ".dec"




1- usage
- padfile, is use to save the pad
$ otp encrypt inputfile padfile

- decypt
$ opt decrypt inputfile padfile

No comments:

Post a Comment