def process_playfair(mode, input_text, key, output_type, output_file): if mode == "encrypt": print ("Plaintext:\n----------------------------") print (input_text.decode('utf-8')) plaintext = input_text.decode('utf-8') plaintext = re.sub('\W', '', plaintext).upper().replace('J', 'I') ciphertext = playfair.encrypt(plaintext, key.replace(' ', '').upper()) ciphertext = ' '.join(ciphertext[i:i+5] for i in range(0,len(ciphertext),5)) print ("Ciphertext:\n----------------------------") print (ciphertext) open(output_file, 'w').write(ciphertext) elif mode == "decrypt": print ("Ciphertext:\n----------------------------") print (input_text.decode('utf-8')) ciphertext = re.sub('\W', '', input_text.decode('utf-8')).upper() plaintext = playfair.decrypt(ciphertext, key.replace(' ', '').upper()) print ("Plaintext:\n----------------------------") print (plaintext) open(output_file, 'w').write(plaintext)
def encrypt_tester(text, key, expected): ''' Function: encrypt_tester test the output of the playfair encryption against the expected output Params: text -- plain text string key -- string replacing starting letters in the pf square expected -- expected output Returns boolean indicating proper output ''' print('Testing playfair encryption') actual = encrypt(text, key) return actual == expected
def main(): """Plot relative frequency graph for Caesar, Vigenere, Hill & Playfair ciphers""" #Values inputfile = sys.argv[1] caesar_key = 3 vigenere_key = 'Vigenere' hill_key = hill.npmatrix([[6, 24, 1], [13, 16, 10], [20, 17, 15]]) playfair_key = 'Playfair key' #Plaintext plaintext = open(inputfile, 'r').read().upper() freq_plain = Counter(plaintext) e_count = freq_plain['E'] freq_plain = sorted([freq_plain[c] for c in letters], reverse=True) freq_plain = [i / float(e_count) for i in freq_plain] #Caesar caesar_text = caesar.encrypt(plaintext, caesar_key) freq_caesar = Counter(caesar_text) freq_caesar = sorted([freq_caesar[c] for c in letters], reverse=True) freq_caesar = [i / float(e_count) for i in freq_caesar] #Vigenere vigenere_text = vigenere.encrypt(plaintext, vigenere_key) freq_vigenere = Counter(vigenere_text) freq_vigenere = sorted([freq_vigenere[c] for c in letters], reverse=True) freq_vigenere = [i / float(e_count) for i in freq_vigenere] #Hill hill_text = hill.encrypt(plaintext, hill_key) freq_hill = Counter(hill_text) freq_hill = sorted([freq_hill[c] for c in letters], reverse=True) freq_hill = [i / float(e_count) for i in freq_hill] #Playfair playfair_text = playfair.encrypt(plaintext, playfair_key) freq_playfair = Counter(playfair_text) freq_playfair = sorted([freq_playfair[c] for c in letters], reverse=True) freq_playfair = [i / float(e_count) for i in freq_playfair] #Plotting linegraphs line_chart = pygal.Line(config=CustomConfig2, style=RedBlueStyle, y_title='Relative frequency') line_chart.title = 'Relative frequency for various ciphers' line_chart.add('Plaintext', freq_plain) line_chart.add('Caesar', freq_caesar) line_chart.add('Vigenere', freq_vigenere) line_chart.add('Hill', freq_hill) line_chart.add('Playfair', freq_playfair) line_chart.render_in_browser() print Counter(plaintext)
def test_encrypt(self): keyMatrix = playfair._generate_key_matrix("boa tarde") self.assertEqual("ribypvmeb", playfair.encrypt(" olay mundo ", keyMatrix)) self.assertEqual("vneajrmslw", playfair.encrypt("nicolasqj", keyMatrix)) self.assertEqual("vneajrzr", playfair.encrypt("Nicolas", keyMatrix)) self.assertEqual("yyyehtyobn", playfair.encrypt("yyydiaybom", keyMatrix)) self.assertEqual("yehtyobnyyy", playfair.encrypt("ydiaybomyyy", keyMatrix)) self.assertEqual("yyyyyyy", playfair.encrypt("yyyyyyy", keyMatrix)) self.assertEqual("yryyw", playfair.encrypt("yayy", keyMatrix)) self.assertEqual("ve,yoyeyehr!w", playfair.encrypt("no,yvyoydia!", keyMatrix))
def main(): """Plot relative frequency graph for Caesar, Vigenere, Hill & Playfair ciphers""" #Values inputfile = sys.argv[1] caesar_key = 3 vigenere_key = 'Vigenere' hill_key = hill.npmatrix([[6,24,1],[13,16,10],[20,17,15]]) playfair_key = 'Playfair key' #Plaintext plaintext = open(inputfile, 'r').read().upper() freq_plain = Counter(plaintext) e_count = freq_plain['E'] freq_plain = sorted([freq_plain[c] for c in letters], reverse=True) freq_plain = [i/float(e_count) for i in freq_plain] #Caesar caesar_text = caesar.encrypt(plaintext, caesar_key) freq_caesar = Counter(caesar_text) freq_caesar = sorted([freq_caesar[c] for c in letters], reverse=True) freq_caesar = [i/float(e_count) for i in freq_caesar] #Vigenere vigenere_text = vigenere.encrypt(plaintext, vigenere_key) freq_vigenere = Counter(vigenere_text) freq_vigenere = sorted([freq_vigenere[c] for c in letters], reverse=True) freq_vigenere = [i/float(e_count) for i in freq_vigenere] #Hill hill_text = hill.encrypt(plaintext, hill_key) freq_hill = Counter(hill_text) freq_hill = sorted([freq_hill[c] for c in letters], reverse=True) freq_hill = [i/float(e_count) for i in freq_hill] #Playfair playfair_text = playfair.encrypt(plaintext, playfair_key) freq_playfair = Counter(playfair_text) freq_playfair = sorted([freq_playfair[c] for c in letters], reverse=True) freq_playfair = [i/float(e_count) for i in freq_playfair] #Plotting linegraphs line_chart = pygal.Line(config=CustomConfig2, style=RedBlueStyle, y_title='Relative frequency') line_chart.title = 'Relative frequency for various ciphers' line_chart.add('Plaintext', freq_plain) line_chart.add('Caesar', freq_caesar) line_chart.add('Vigenere', freq_vigenere) line_chart.add('Hill', freq_hill) line_chart.add('Playfair', freq_playfair) line_chart.render_in_browser() print Counter(plaintext)
def encrypt_image(): if 'file' not in request.files: resp = jsonify({'message': 'No image in the request'}) resp.status_code = 400 return resp if 'plain_text' not in request.form: resp = jsonify({'message': 'No plain text in the request'}) resp.status_code = 400 return resp if 'key' not in request.form: resp = jsonify({'message': 'No key in the request'}) resp.status_code = 400 return resp files = request.files.getlist('file') filename = "encrypted_image.png" errors = {} success = False for file in files: if file and allowed_file(file.filename): file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) success = True else: errors["message"] = 'File type of {} is not allowed'.format( file.filename) cypher_text = encrypt(request.form.get('plain_text'), request.form.get('key')) image_file = UPLOAD_FOLDER + filename encode(cypher_text, image_file) if success: resp = jsonify({'endpoint': 'getimage'}) resp.status_code = 200 return resp else: resp = jsonify(errors) resp.status_code = 400 return resp
def hail_mary(key_matrix, plaintext, ciphertext): alpha = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] unknowns = [] for row in range(5): for col in range(5): if key_matrix[row, col] == '' or key_matrix[row, col] == ' ': unknowns.append([row, col]) key = '' for el in np.nditer(key_matrix): if str(el) == '' or str(el) == ' ': el = '?' key += str(el) for c in key: try: if alpha.index(c) >= 0: alpha.remove(c) except ValueError: continue idx = 0 idx2 = 1 cnt_idx = 1 for j in range(math.factorial(len(alpha))): for unknown in unknowns: if idx >= len(alpha): break key_matrix[unknown[0], unknown[1]] = alpha[idx] #fill rest of matrix for i in range(len(alpha) - 1): if idx2 >= len(alpha) - 1 or cnt_idx >= len(alpha) - 1: idx2 = 0 cnt_idx = 0 if alpha[i] == alpha[idx]: continue else: key_matrix[unknowns[cnt_idx][0], unknowns[cnt_idx][1]] = alpha[idx2] idx2 += 1 cnt_idx += 1 key = create_key(key_matrix) if idx == 0: b_key = key try: if encrypt(key, plaintext).lower() == ciphertext.lower(): return key except KeyError as e: continue else: for row in range(5): np.roll(key_matrix, 1) key = create_key(key_matrix) if encrypt(key, plaintext).lower() == ciphertext.lower(): return key for col in range(5): key_matrix[:, [row, col]] = key_matrix[:, [col, row]] key = create_key(key_matrix) if encrypt(key, plaintext).lower() == ciphertext.lower(): return key idx += 1 idx2 = idx + 1 cnt_idx = idx2 return b_key
def fetch(entries): # for entry in entries: # field = entry[0] # text = entry[1].get() # print('%s: "%s"' % (field, text)) # print(getKey(entries), getText(entries), entries[0][1].get(), entries[3][1].get()) res = "" if (entries[2][1].get() == "Vigenere Cipher"): if (entries[1][1].get() == "Encrypt"): res = vigenere.encryptStandard(getText(entries), getKey(entries)[0][0]) elif (entries[1][1].get() == "Decrypt"): res = vigenere.decryptStandard(getText(entries), getKey(entries)[0][0]) elif (entries[2][1].get() == "Full Vigenere Cipher"): if (entries[1][1].get() == "Encrypt"): res = vigenere.encryptFull(getText(entries), getKey(entries)[0][0], int(getKey(entries)[1][0])) elif (entries[1][1].get() == "Decrypt"): res = vigenere.decryptFull(getText(entries), getKey(entries)[0][0], int(getKey(entries)[1][0])) elif (entries[2][1].get() == "Auto Vigenere Cipher"): if (entries[1][1].get() == "Encrypt"): res = vigenere.encryptAutoKey(getText(entries), getKey(entries)[0][0]) elif (entries[1][1].get() == "Decrypt"): res = vigenere.decryptAutoKey(getText(entries), getKey(entries)[0][0]) elif (entries[2][1].get() == "Extended Vigenere Cipher"): if (entries[1][1].get() == "Encrypt"): res = vigenere.encryptExtended(getText(entries), getKey(entries)[0][0]) elif (entries[1][1].get() == "Decrypt"): res = vigenere.decryptExtended(getText(entries), getKey(entries)[0][0]) elif (entries[2][1].get() == "Playfair Cipher"): if (entries[1][1].get() == "Encrypt"): res = playfair.encrypt(getText(entries), getKey(entries)) elif (entries[1][1].get() == "Decrypt"): res = playfair.decrypt(getText(entries), getKey(entries)) elif (entries[2][1].get() == "Super Enkripsi"): if (entries[1][1].get() == "Encrypt"): res = supere.encrypt(getText(entries), getKey(entries)[0][0]) elif (entries[1][1].get() == "Decrypt"): res = supere.decrypt(getText(entries), getKey(entries)[0][0]) elif (entries[2][1].get() == "Affine Cipher"): if (entries[1][1].get() == "Encrypt"): res = affine.encrypt(getText(entries), int(getKey(entries)[0][0]), int(getKey(entries)[1][0])) elif (entries[1][1].get() == "Decrypt"): res = affine.decrypt(getText(entries), int(getKey(entries)[0][0]), int(getKey(entries)[1][0])) elif (entries[2][1].get() == "Hill Cipher"): if (entries[1][1].get() == "Encrypt"): res = hill.encrypt(getText(entries), getKey(entries)) elif (entries[1][1].get() == "Decrypt"): res = hill.decrypt(getText(entries), getKey(entries)) printResult(res)
def main(): ciphers = 'caesar (c), railfence (r), playfair (p)\ substitution (su), beale (b), straddle (st)' while True: cmd = input('encrypt, decrypt, or exit (en, de, ex)? ') # ENCRYPT while cmd == 'en': enc = input('select cipher: \n \ caesar (c), railfence (r), playfair (p) \n \ substitution (su), beale (b), straddle (st): \n') # caesar if enc == 'c': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter integer key: ') if utils.check_int(k): print(caesar.encrypt(t, int(k))) cmd = '' else: cmd = '' # railfence elif enc == 'r': t = input('enter plain text: ') k = input('enter integer key: ') if utils.check_int(k): if int(k) > 1: print(railfence.encrypt(t, int(k))) cmd = '' else: print('key must be at least 2') cmd = '' else: cmd = '' # playfair elif enc == 'p': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): print(playfair.encrypt(t, k)) pass else: print('key can only consist of latin letters') break cmd = '' # substitution elif enc == 'su': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): try: utils.check_full(k) except ValueError: print('key should bee full alphabet') break try: print(substitution.encrypt(t, k)) except ValueError: print('check errors for parameter issues') pass else: print('key can only consist of latin letters') break cmd = '' # beale elif enc == 'b': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can have letters + punctuation') break k = input('enter file name key: ') if k != '': pass s = input('enter an integer seed: ') if s != '': try: s = int(s) except ValueError: print('seed must be integer') break try: print(beale.encrypt(t, k, s)) except ValueError: print('make sure your file is correct') pass else: print('text cannot be empty') break cmd = '' # straddle elif enc == 'st': t = input('enter plain text: ') warn = 0 for x in t: if (t not in string.ascii_letters and t != '0' and t != '1' and t != ' '): warn += 1 if warn > 0: print('warning: text should include only letters, 0, or 1') if t != '': pass else: print('text cannot be empty') break alk = input('enter alpha key: ') if alk != '': pass else: print('alpha_key cannot be empty') break try: utils.check_full(alk) except ValueError: print('alpha_key must be full alphabet') break nk = input('enter 2 digit numeric key: ') if nk != '': pass if (len(nk) != 2 or not nk[0].isnumeric() or not nk[1].isnumeric() or '0' in nk): print('num_key must be a 2 digit int with unique digits') print('cannot contain 0') break adk = input('enter adding key:') if adk != '': try: print(straddle.encrypt(t, alk, nk, adk)) except ValueError: print('make sure your add key is an integer') pass else: print('input cannot be empty') break cmd = '' else: print('Please enter a valid input for a cipher.') # DECRYPT while cmd == 'de': dec = input('select cipher: \n \ caesar (c), railfence (r), playfair (p) \n \ substitution (su), beale (b), straddle (st): \n') # caesar if dec == 'c': t = input('enter cipher text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter integer key: ') if utils.check_int(k): print(caesar.decrypt(t, int(k))) cmd = '' else: cmd = '' # railfence elif dec == 'r': t = input('enter cipher text: ') k = input('enter integer key: ') if utils.check_int(k): if int(k) > 1: print(railfence.decrypt(t, int(k))) cmd = '' else: print('key must be at least 2') cmd = '' else: cmd = '' # playfair elif dec == 'p': t = input('enter cipher text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): print(playfair.decrypt(t, k)) pass else: print('text can only consist of latin letters') break cmd = '' # substitution elif dec == 'su': t = input('enter cipher text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): try: utils.check_full(k) except ValueError: print('key should be full alphabet') break try: print(substitution.decrypt(t, k)) except ValueError: print('check errors for parameter issues') pass else: print('key can only consist of latin letters') break cmd = '' # beale elif dec == 'b': t = input('enter cipher text: ') for x in t: if x != ' ': if not x.isnumeric(): print('text should consist of int literals') break if t != '': pass else: print('warning: text should only consist of integers') break k = input('enter file name key: ') if k != '': try: print(beale.decrypt(t, k)) except ValueError: print('check that your text file is correct') pass else: print('text cannot be empty') break cmd = '' # straddle elif dec == 'st': t = input('enter cipher text: ') warn = 0 for x in t: if (t not in string.ascii_letters and t != '0' and t != '1' and t != ' '): warn += 1 if warn > 0: print('warning: text should include only letters, 0, or 1') if t != '': pass else: print('text cannot be empty') break alk = input('enter alpha key: ') if alk != '': pass else: print('alpha_key cannot be empty') break try: utils.check_full(alk) except ValueError: print('alpha_key must be full alphabet') break nk = input('enter 2 digit numeric key: ') if nk != '': pass if (len(nk) != 2 or not nk[0].isnumeric() or not nk[1].isnumeric() or '0' in nk): print('num_key must be a 2 digit int with unique digits') print('cannot contain 0') break adk = input('enter adding key:') if adk != '': try: print(straddle.decrypt(t, alk, nk, adk)) except ValueError: print('make sure your add key is an integer') pass else: print('text cannot be empty') break cmd = '' else: print('Please enter a valid input for a cipher.') if cmd == 'ex': print('exit') return False elif cmd == '' or cmd == 'en' or cmd == 'de': pass else: print('Please enter a valid input of en, de, or ex.')