Wednesday, November 12, 2014

Simple cipher in Python

Cipher in Python



#usr/bin/python
import os
import sys

__version__="1.0"
__author__="Marcin"
#**********************
Letters="abcdefghijklmnopqrstuvwxyz 1234567890-+*/_:;()[]{}\n'="
Letters+='",üäö$!?.<>'
Letter_dict={}
Letter_dict_2={}
u=0
for i in Letters:
    u=u+1
    Letter_dict.update({i:u})
    Letter_dict_2.update({u:i})
#print(Letter_dict)
#print("********")
#print(Letter_dict_2)
#*********************
class cipher_caesar:
    def __init__(self,key,old_t,file_=None):
        self.key=key
        self.new_t=""
        self.old_t=old_t
        if(file_ !=None):
            self.file_=file_

    def code(self,text=None):
        if text!=None:
            self.old_t=text
        if self.key!=0:
            count=1
            for i in self.old_t:
                if(int(Letter_dict[i.lower()]+self.key)1 or Letter_dict[i.lower()]-self.key==1):
                    self.new_t+=Letter_dict_2[int(Letter_dict[i.lower()]-self.key)]
                else:
                    self.new_t+=Letter_dict_2[len(Letters)-int(self.key-Letter_dict[i.lower()])]
                count+=1
        else:
            print("Ungültiger key")
        return self.new_t

def MAIN(args):
    print("")
    if(len(args)==1):
        weiter=True
        while(weiter):
            if(input("crypt:1/decrypt:2 : ")=="1"):
                text=str(input("Text:"))
                key=int(input("Key:"))
                c=cipher_caesar(key,text)
                crypted=c.code(None)
                print("crypted:",crypted)
            else:
                text=input("Text:")
                key=int(input("Key:"))
                c=cipher_caesar(key,text)
                crypted=c.decode(None)
                print("->",crypted)
                input()
                return crypted
        else:
            exit()
    else:
        file_=None
        key=""
        modus=0
        text=""
        for i in range(len(args)):
            if args[i]=="-key":
                key=int(args[i+1])
            elif args[i]=="-code":
                modus=1
            elif args[i]=="-decode":
                modus=2
            elif args[i]=="-text":
                text=str(args[i+1])
            elif args[i]=="-file":
                file_=str(args[i+1])
            else:None
        if(file_==None):
            c=cipher_caesar(key,text)
            if(modus==1):v=c.code(None)
            else:v=c.decode(None)
        else:
            if(os.path.exists(file_)):
                c=cipher_caesar(key,text,file_=file_)
                if(modus==1):v=c.code_file()
                else:v=c.decode_file()
            else:
                print("FILE DOES NO EXIST")
            
MAIN(sys.argv)

Author:Marcin

Language:Python 3.4
Description: A implementation of one of the simplest algorithms for ciphers, the caesar cipher. You can run it also in the console with args.You can crypt and decrypt files.

No comments:

Post a Comment