Optimized & refactorized code.

This commit is contained in:
Mikolaj Lubiak 2022-05-22 18:07:02 +02:00
parent c1ef1f15e7
commit cbf49c2119
2 changed files with 15 additions and 29 deletions

View File

@ -1,18 +1,17 @@
from rot import decrypt as dec
from rot import chars
from rot import rot
from sys import argv
from collections import Counter
def brkc(m: str, f: str, x: int):
def breakRot(m: str, f: str, x: int):
t=tuple(open(f).read().splitlines()[:x])
decm=[]
for i in range(1, len(chars)):
decmsg=dec(m, i)
print(f"{i}: {decmsg}")
poss=[]
for i in range(1, 26):
msg=rot(m, -i)
print(f"{i}: {msg}")
for x in t:
if x.upper() in decmsg:
decm.append(decmsg)
return Counter(decm)
if x.upper() in msg.upper():
poss.append(msg)
return Counter(poss)
if __name__ == "__main__":
try:
@ -23,4 +22,4 @@ if __name__ == "__main__":
a=input("Give encoded text to break: ")
b=input("Give filename of file which contains wordlist: ")
c=int(input("Type how many words to read from the wordlist ('-1'=every): "))
print(brkc(a, b, c))
print(breakRot(a, b, c))

23
rot.py Normal file → Executable file
View File

@ -1,23 +1,10 @@
#!/usr/bin/env python3
#!/usr/bin/env python3.10
from string import ascii_uppercase as chars
from string import ascii_lowercase as lc, ascii_uppercase as uc
from sys import argv
def encrypt(s: str, i: int):
enc=""
for x in range(len(s)):
for y in range(len(chars)):
if s[x].upper() == chars[y]:
enc+=chars[(y+i)%len(chars)]
return enc
def decrypt(s: str, i: int):
dec=""
for x in range(len(s)):
for y in range(len(chars)):
if s[x].upper() == chars[y]:
dec+=chars[(y-i)%len(chars)]
return dec
def rot(m: str, n: int):
return m.translate(m.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n]))
if __name__ == "__main__":
try:
@ -26,4 +13,4 @@ if __name__ == "__main__":
except IndexError:
a=input("Give text to encode/decode: ")
b=int(input("Type how many shifts do you want to do: "))
print(f"Encrypted: {encrypt(a, b)}\nDecrypted: {decrypt(a, b)}")
print(f"Text: {rot(a, b)}")