99 lines
2.9 KiB
Python
Executable File
99 lines
2.9 KiB
Python
Executable File
#!/usr/bin/python3
|
|
import sys, getopt, os
|
|
|
|
def encrypt(string,key):
|
|
lowerstr=string.lower()
|
|
print("Encrypting "+lowerstr+" with key "+key)
|
|
strnums = []
|
|
keynums = []
|
|
resultnums = []
|
|
resultstring = ""
|
|
for c in lowerstr:
|
|
strnums.append(ord(c)-97)
|
|
print(strnums)
|
|
for c in key:
|
|
keynums.append(ord(c)-97)
|
|
print(keynums)
|
|
keypointer=0
|
|
for n in strnums:
|
|
resultnums.append((n+keynums[keypointer])%26)
|
|
keypointer = (keypointer+1) % (len(key))
|
|
print(resultnums)
|
|
for c in resultnums:
|
|
resultstring = resultstring+chr(c+97)
|
|
print(resultstring)
|
|
|
|
def decrypt(string,key):
|
|
lowerstr=string.lower()
|
|
print("Decrypting "+lowerstr+" with key "+key)
|
|
strnums = []
|
|
keynums = []
|
|
resultnums = []
|
|
resultstring = ""
|
|
for c in lowerstr:
|
|
strnums.append(ord(c)-97)
|
|
print(strnums)
|
|
for c in key:
|
|
keynums.append(ord(c)-97)
|
|
print(keynums)
|
|
keypointer=0
|
|
for n in strnums:
|
|
resultnums.append((n-keynums[keypointer])%26)
|
|
keypointer = (keypointer+1) % (len(key))
|
|
print(resultnums)
|
|
for c in resultnums:
|
|
resultstring = resultstring+chr(c+97)
|
|
print(resultstring)
|
|
|
|
def trigraphcount(string):
|
|
distances = {}
|
|
for i in range(0,len(string)-2):
|
|
trigraph = string[i:i+3]
|
|
index = 0
|
|
while index < len(string):
|
|
index = string.find(trigraph, index)
|
|
if index == -1:
|
|
break
|
|
print(trigraph+' found at', index)
|
|
if not trigraph in distances and index!=i:
|
|
distances[trigraph] = index - i
|
|
index += 3
|
|
#print(distances)
|
|
print(sorted(distances.items(), key=lambda x: x[1]))
|
|
|
|
def lettercount(string,dist):
|
|
letters = {}
|
|
for i in range(0,len(string)-dist,dist):
|
|
print(string[i:i+dist])
|
|
for c in string:
|
|
if c in letters:
|
|
letters[c] = letters[c]+1
|
|
else:
|
|
letters[c] = 1
|
|
print(letters)
|
|
|
|
def main(argv):
|
|
key = ""
|
|
try:
|
|
opts, args = getopt.getopt(argv,"hk:e:d:t:l:",["key=","encrypt=","decrypt=","trigraphs=","lettercount="])
|
|
except getopt.GetoptError:
|
|
print(os.path.basename(__file__)+' -k <key> -e <plain text>')
|
|
print(os.path.basename(__file__)+' -k <key> -d <encrypted text>')
|
|
sys.exit(2)
|
|
for opt, arg in opts:
|
|
if opt == '-h':
|
|
print(os.path.basename(__file__)+' -k <key> -e <plain text>')
|
|
print(os.path.basename(__file__)+' -k <key> -d <encrypted text>')
|
|
sys.exit()
|
|
elif opt in ("-k", "--key"):
|
|
key = arg
|
|
elif opt in ("-e", "--encrypt"):
|
|
encrypt(arg,key)
|
|
elif opt in ("-d", "--decrypt"):
|
|
decrypt(arg,key)
|
|
elif opt in ("-t", "--trigraphs"):
|
|
trigraphcount(arg)
|
|
elif opt in ("-l", "--lettercount"):
|
|
lettercount(arg,int(key))
|
|
if __name__ == '__main__':
|
|
main(sys.argv[1:]) |