def crack_caesar(input: str) -> tuple: """Cracks the caesar cypher by computing the shift and probability of letters for every single possible shift. Arguments: input {str} -- [description] Returns: tuple -- [description] """ t = "" minprob = None minshift = 0 for shift in range(-13, 13): unshifted = caesar(input, shift) newdict = compute_probability(unshifted) prob = compare_prob(newdict, frequency_english) if minprob is None: minshift = shift minprob = prob else: if prob < minprob: minshift = shift minprob = prob return (caesar(input, minshift), minshift)
def test(key_length): if args.verbose: print(f"Testing key length {key_length}") groups = [] for n in range(1, key_length + 1): groups.append(subgroup(n, key_length)) a = ord('A') key = "" for n, group in enumerate(groups): coef = utils.coincidence_index(group) if args.all: print(f"Subgroup {n + 1} (IC: {coef})\n{group}") best_subkey = ('A', 0) for i in range(MODULE): shift = (MODULE - i)%MODULE decrypt = caesar.caesar(group, shift) frequencies = utils.most_frequent_chars(decrypt) score = utils.match_score(''.join(map(lambda x: x[0], frequencies))) subkey = chr(a + i) if args.all: print(f"Testing subkey '{subkey}' with match score {round(100 * (score/MAX_SCORE))}%") if best_subkey[1] < score: best_subkey = (subkey, score) if args.all: print(f"Best subkey is '{best_subkey[0]}' with match score {round(100 * (best_subkey[1]/MAX_SCORE))}%") key += best_subkey[0] decrypt = vigenere(text, key) return (key, decrypt) if validator.is_valid(decrypt) else FAILED
def caesar_or_vigenere(): if request.form['encryptionType'] == "caesar": rot = int(request.form['rot']) text = request.form['text'] return form.format(caesar(text, rot)) else: text = request.form['text'] key = request.form['key'] return form.format(vigenere(text, key))
def main(): print("1)Caesar\n2)Multiplication\n3)affine\n4)ubrytelig\n5)rsa\n") which_alg = input(": ") if which_alg == '1': cy_alg = caesar() elif which_alg == '2': cy_alg = multiplikasjons_cypher() elif which_alg == '3': cy_alg = affine() elif which_alg == '4': cy_alg = ubrytelige() else: cy_alg = rsa() send = sender(cy_alg) receiv = receiver(cy_alg) hack = hacker(cy_alg) while True: choos_key = input( "Choose 1 to inter your key, else choose other number: ") if choos_key == '1': key = input("your key is: ") if which_alg == '4': send.set_receiver(cy_alg, receiv, key) elif which_alg == '3': key2 = input("your second key is: ") send.set_receiver(cy_alg, receiv, (int(key),int(key2))) else: send.set_receiver(cy_alg, receiv, int(key)) else: send.set_receiver(cy_alg, receiv) receiv.set_sender(cy_alg, send) my_text = input("Your Text: ") code = send.operate_cypher(my_text) print("Cypher: " + code) decoded_code = receiv.operate_cypher(code) print("after: " + decoded_code) verify = cy_alg.verify(my_text, decoded_code) if verify: break else: print("Repeat!\n") print("hack: {} ".format(hack.hack(code)))
def test_caesar(self): for plain, cipher, shift in self.ciphers: enc = caesar(plain, 5) self.assertEqual(cipher, enc)
def create_engine(): return caesar(5)
def test_final_result(initial_string, shift, expected): assert caesar(initial_string, shift) == expected
def test_message_set_get(): mss_txt = 'message_text' obj = CeasarSipher() obj.message = mss_txt assert obj.__dict__[4] == mss_txt assert obj.message == caesar(mss_txt, 4)
def step_given_character_shift(context, shift): context.shift = int(shift) context.caesar = caesar(context.shift)
elif user == "B": username = "******" # Bob's pk choice from selected set depends on whether he is encrypting or decrypting if encrypting: useridx = 1 else: useridx = 0 else: print("User must be A or B, cannot proceed.") exit(0) # What plaintext should be encrypted msgtext = input("Message text to be processed using cipher: ") msgtext = msgtext.replace(" ", "X") # Replace spaces with X msgtext = msgtext.upper() # Force all characters to upper case # Public key is the product of the pair of private keys publickey = privatekey[keyindex][0] * privatekey[keyindex][1] # Obtain Caesar cipher using the selected private key if encrypting == True: ciphertext = caesar(msgtext, privatekey[keyindex][useridx]) else: plaintext = caesar(msgtext, -privatekey[keyindex][useridx]) if encrypting == True: print("%s therefore sends public key %s and %s as ciphertext %s" % (username, publickey, msgtext, ciphertext)) else: print("%s therefore decrypts %s as %s" % (username, msgtext, plaintext))
from caesar import caesar from vigenere import vigenere from onetimepad import one_time_pad plaintext = input("Enter Plaintext: ") # Caesar caesar(plaintext) # Vigenere vigenere(plaintext) # One Time Pad one_time_pad(plaintext)
def __init__(self): super().__init__() self.caesar = caesar()
def cipher(bot, update): message, key = update.message.text.split(",") message=list(message.lower()) caesar(message, key) message="".join(message) bot.send_message(chat_id=update.message.chat_id, text=message)
"the caeser-stream-cipher, and long enough to be \n" + "successfully be decrypted") else: try: f = open(sys.argv[1], 'r') f.seek(0) text = "\n".join(str(f.read()).splitlines()) f.close() # listing the amount of occurrences of each character occ = {'e': 0} list( map((lambda x: occ.__setitem__(x, occ.get(x, 0) + 1)), text.lower())) # the idea is that the one charakter with the highest occurence is # in German, English and French the 'e'. (m, c) = max([(occ[k], k) for k in occ.keys() if k in "abcdefghijklmnopqrstuvw"]) # Based on the assumed character 'e', # we decrypt the text and print it. print(caesar(text, ord('e') - ord(c))) except FileNotFoundError: print("Could not find File! Does it exist?") except: raise
def decode(text): return caesar.caesar(text, caesar.decode)
def decode(message): if message.startswith('con cesare'): code = [int(s) for s in message[10:].lstrip() if s.isdigit()] enc, dec = caesar(code[0]) print(message[10:].lstrip()[len(str(code[0])):]) return dec(message[10:].lstrip()[len(str(code[0])):])
def test_another_message_set(): mss_txt = 'another_message_text' obj = CeasarSipher() obj.another_message = mss_txt assert obj.__dict__[7] == mss_txt assert obj.another_message == caesar(mss_txt, 7)
def testIdentity(self): result = caesar(self.test_str, 0) self.assertEqual(self.test_str, result)
def __init__(self): super().__init__() self.caesar = caesar() self.mul = multiplikasjons_cypher()
def testRot13(self): result = caesar(self.test_str, 13) self.assertEqual("NOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLM", result)
print('Decryption...') print(rsa.decrypt(message)) else: print('That is not a proper instruction.') print('--------------------------rsa end--------------------------\n') print('Cost ' + str(end - start) + 's\n') costdic[choose] = end - start elif choose == 2: print('--------------------------caesar--------------------------\n') encryption_key = int(raw_input('What is your encryption key?\n')) message = raw_input('What would you like to encrypt?\n') start = time.clock() cipher = caesar.caesar(message, encryption_key) end = time.clock() print('ciphertext is ' + cipher + "\n") print( '--------------------------caesar end--------------------------\n') print('Cost ' + str(end - start) + 's\n') costdic[choose] = end - start elif choose == 3: print('--------------------------AES CBC--------------------------\n') moo = aes.AESModeOfOperation() cleartext = raw_input('What would you like to encrypt?\n') start = time.clock() cypherkey = [ 143, 194, 34, 208, 145, 203, 230, 143, 177, 246, 97, 206, 145, 92,
def testRot26(self): result = caesar(self.test_str, 26) self.assertEqual(self.test_str, result)
Arguments: input {str} -- [description] Returns: tuple -- [description] """ t = "" minprob = None minshift = 0 for shift in range(-13, 13): unshifted = caesar(input, shift) newdict = compute_probability(unshifted) prob = compare_prob(newdict, frequency_english) if minprob is None: minshift = shift minprob = prob else: if prob < minprob: minshift = shift minprob = prob return (caesar(input, minshift), minshift) sentence = "far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the galaxy lies a small unregarded yellow sun" x = caesar(sentence, 2) print(x) t, shift = crack_caesar(x) print("t:" + t) print("shift: %d" % shift)
def testRot52(self): result = caesar(self.test_str, 52) self.assertEqual(self.test_str, result)
date = response.json() #function converting data in sha1 def sha1(data): return hashlib.sha1(str(data).encode()).hexdigest() #function change content in file JSON def change(data, *args): for x in args: data.update(x) #variables need change decifra = caesar.caesar(date.get('cifrado'), date.get('numero_casas')) decifrado = {"decifrado": "{0}".format(decifra)} resumir = sha1(decifra) resumo = {"resumo_criptografico": "{0}".format(resumir)} #take response and save on file answer.json with open("answer.json", "w") as f: change(date, decifrado, resumo) json.dump(date, f) #with open("answer.json","w") as f: # obj = open("test.json","r") # txt = obj.read() # json.dump(txt,f) #now, this part submit file to site answer = {'answer': open("answer.json", "rb")}
def testFilter_uppercasing(self): result = caesar("abcde", 0) self.assertEqual("ABCDE", result)
def all_caesar(): msg = input("Enter string: ") print("Input String:", msg) for i in range(1, 26): caesar(msg, i)
def testFilter_stripPunctuation(self): result = caesar("it's car!",0) self.assertEqual("ITSCAR", result)
import socket import caesar with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(("localhost", 10082)) _text = input() if _text[0] == "$": data = caesar.caesar(_text) s.sendall(str(data[1:len(data)]).encode()) else: data = s.sendall(_text.encode())
def test_another_chars(another_chars, shift, expected): assert caesar(another_chars, shift) == expected
import caesar as cs import multiplicative as mp import affine as af import autokey as ak import playfer as pf import viginer as vg alpha = ' abcdefghijklmnopqrstuvwxyz' choose = input() if choose == '1': cs.caesar(alpha) if choose == '2': mp.multipl(alpha) if choose == '3': af.affine(alpha) if choose == '4': ak.autokey(alpha) if choose == '5': pf.playfer() if choose == '6': vg.viginer(alpha)
def encode(text): return caesar.caesar(text, caesar.encode)