def AffineCracker(ctext, ngram): fitness = ngram_score(ngram) max_key = break_affine(ctext, fitness) print('\033[1;32m[+]\033[0m Best candidate with key (a,b) = ' + str(max_key[1]) + ':') print(Affine(max_key[1][0], max_key[1][1]).decipher(ctext))
def break_affine(ctext, fitness): ctext = re.sub('[^A-Z]', '', ctext.upper()) scores = [] for i in [1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25]: scores.extend([(fitness.score(Affine(i, j).decipher(ctext)), (i, j)) for j in range(0, 25)]) return max(scores)
def break_affine(ctext): # make sure ciphertext has all spacing/punc removed and is uppercase ctext = re.sub('[^A-Z]', '', ctext.upper()) # try all posiible keys, return the one with the highest fitness scores = [] for i in [1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25]: scores.extend([(fitness.score(Affine(i, j).decipher(ctext)), (i, j)) for j in range(0, 25)]) return max(scores)
with open(archivo, encoding="utf8") as f2: contenido = f2.readlines() for linea in contenido: linea = linea.strip().upper() if linea == '': continue limpio = regex.sub('', linea) for claro in re.findall('.{%d}' % CARACTERES_FIX, limpio): salida = '' lista_claro = list(claro) for caracter in lista_claro: salida = salida + str(ord(caracter)) + ',' for a in AFIN_A: for b in AFIN_B: salida2 = '' cifrado = Affine(a, b).encipher(claro) lista_cifrado = list(cifrado) for caracter in lista_cifrado: salida2 = salida2 + str(ord(caracter)) + ',' ###aff = (a * 100) + b aff = b print(salida + salida2 + str(aff), file=f) # xxx #print(salida2 + salida + str(aff), file=f) total_lineas = total_lineas + 1 print('Total de registros: ' + str(total_lineas)) print('Proceso finalizado.')
from pycipher import Affine encode = Affine(a=5, b=9).encipher('defend the east wall of the castle') print("加密结果:" + encode) decode = Affine(a=5, b=12).decipher('RgYDMllaKzGC') print("解密结果:" + decode) # 注意大小写
def encrypt(keycodeLines, encryptionDirection, plaintextContents): for i in range(len(keycodeLines)): #Iterate over the keycode. if (encryptionDirection == "encrypt"): splitLine = keycodeLines[i].split() else: splitLine = keycodeLines[len(keycodeLines) - 1 - i].split( ) #This ensures that if the encryption direction is set to decrypt, that this for loop reads the keycode.txt from end to beginning. # print("Line " + str(i) + " is " + keycodeLines[i] + " and the split line is: " + str(splitLine)) # This was an old debugging line that may be useful in the future. if (splitLine[0] == "caesar"): if (int(splitLine[1]) > 25 or int(splitLine[1]) < 1): print("Keycode line: " + str(i + 1) + ": Caesar shift detected on keycode line " + str(i) + " attempting to shift by value " + splitLine[1] + ".") sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Caesar shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Caesar(int( splitLine[1])).encipher(plaintextContents) else: plaintextContents = Caesar(int( splitLine[1])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Caesar shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "vigenere"): if (type(splitLine[1] != str)): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Vigenère shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Vigenere( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Vigenere( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Vigenère shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print("Keycode line: " + str(i + 1) + ": Vigenère shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "porta"): if (type(splitLine[1] != str)): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Porta cipher detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Porta( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Porta( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Vigenère shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print("Keycode line: " + str(i + 1) + ": Vigenère shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "adfgx"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": ADFGX cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": ADFGX cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = ADFGX( splitLine[1], splitLine[2]).encipher(plaintextContents) else: plaintextContents = ADFGX( splitLine[1], splitLine[2]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": ADFGX ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif ( splitLine[0] == "adfgvx" ): #The first argument is the keysquare, and the second argument is the keyword. if ( len(splitLine[1]) != 36 ): # This makes sure that the keysquare's length is exactly 36. print( "Keycode line: " + str(i) + ": ADFGVX cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long, but is instead " + str(len(splitLine[1])) + " characters long.") sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": ADFGVX cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = ADFGVX( splitLine[1], splitLine[2]).encipher(plaintextContents) else: plaintextContents = ADFGVX( splitLine[1], splitLine[2]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": ADFGVX ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "affine"): if ((int(splitLine[2]) < 1) or (int(splitLine[2]) > 25)): print( "Keycode line: " + str(i + 1) + ": Affine cipher detected on keycode line " + str(i) + " attempting to use b value outside of the range of 1-25.") sys.exit() elif ((int(splitLine[1]) == 13) or (int(splitLine[1]) % 2 != 1) or (int(splitLine[1]) > 25) or (int(splitLine[1]) < 1)): print( "Keycode line: " + str(i + 1) + ": Affine cipher detected on keycode line " + str(i) + " attempting to use an a value outside of the range of 1-25, that is even, or that is 13, all of which are not permitted." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Affine cipher detected with an a value of " + splitLine[1] + " and a b value of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Affine( int(splitLine[1]), int(splitLine[2])).encipher(plaintextContents) else: plaintextContents = Affine( int(splitLine[1]), int(splitLine[2])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Affine ciphered " + originalPlaintext + " by value a " + splitLine[1] + " and value b " + splitLine[2] + " with a result of " + plaintextContents + ".") elif ( splitLine[0] == "autokey" ): #TODO: The autokey cipher actually doesn't have any requirements for the key, but will be configured to set off a ton of warnings assuming the config flags allow for it. originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Autokey cipher detected with an key of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Autokey( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Autokey( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Autokey ciphered " + originalPlaintext + " by key of " + splitLine[1] + " for a result of " + plaintextContents + ".") elif (splitLine[0] == "atbash"): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Autokey cipher detected.") if (encryptionDirection == "encrypt"): plaintextContents = Affine(25, 25).encipher(plaintextContents) else: plaintextContents = Affine(25, 25).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Atbash ciphered " + originalPlaintext + " for a result of " + plaintextContents + ".") elif (splitLine[0] == "beaufort"): if (type(splitLine[1] == str)): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Beaufort shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Beaufort( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Beaufort( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Beaufort shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print("Keycode line: " + str(i + 1) + ": Beaufort shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "bifid"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": Bifid cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Bifid cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Bifid(splitLine[1], int( splitLine[2])).encipher(plaintextContents) else: plaintextContents = Bifid(splitLine[1], int( splitLine[2])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Bifid ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "coltrans"): if (type(splitLine[1] != str) ): # Check that the encryption key is a string. originalPlaintext = plaintextContents if (debug): print( "Keycode line: " + str(i + 1) + ": Columnar transposition shift detected with an argument of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = ColTrans( splitLine[1]).encipher(plaintextContents) else: plaintextContents = ColTrans( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Columnar transposition shifted " + originalPlaintext + " by " + splitLine[1] + " with a result of " + plaintextContents + ".") else: print( "Keycode line: " + str(i + 1) + ": Columnar transposition shift detected on keycode line " + str(i) + " attempting to use key that is not a string.") elif (splitLine[0] == "foursquare"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Foursquare cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() elif (len(splitLine[2]) != 25): print( "Foursquare cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (debug): print("Foursquare cipher detected with a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + ".") if (encryptionDirection == "encrypt"): plaintextContents = Foursquare( key1=splitLine[1], key2=splitLine[2]).encipher(plaintextContents) else: plaintextContents = Foursquare( key1=splitLine[1], key2=splitLine[2]).decipher(plaintextContents) if (debug): print("Foursquare ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " and a keyword of " + splitLine[2] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "playfair"): if ( len(splitLine[1]) != 25 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": Playfair cipher detected on keycode line " + str(i) + " attempting to use keysquare that is not 25 characters long." ) sys.exit() else: originalPlaintext = plaintextContents if (encryptionDirection == "encrypt"): plaintextContents = Playfair( splitLine[1]).encipher(plaintextContents) else: plaintextContents = Playfair( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Playfair ciphered " + originalPlaintext + " by a keysquare of " + splitLine[1] + " with a result of " + plaintextContents + ".") elif ( splitLine[0] == "railfence" ): #TODO: Fix this so that it throws an error if the key is a bad length relative to the plaintext. if (splitLine[1].isdigit() == False): print("Keycode line: " + str(i + 1) + ": Railfence cipher detected on keycode line " + str(i) + " with a non-numerical key.") sys.exit() elif ( int(splitLine[1]) < 1 ): # This makes sure that the keysquare's length is exactly 25. print("Keycode line: " + str(i + 1) + ": Railfence cipher detected on keycode line " + str(i) + " attempting to use a key less than 0.") sys.exit() else: originalPlaintext = plaintextContents if (encryptionDirection == "encrypt"): plaintextContents = Railfence(int( splitLine[1])).encipher(plaintextContents) else: plaintextContents = Railfence(int( splitLine[1])).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Railfence ciphered " + originalPlaintext + " by a key of " + splitLine[1] + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "rot13"): originalPlaintext = plaintextContents if (debug): print("Keycode line: " + str(i + 1) + ": Rot13 cipher detected.") if (encryptionDirection == "encrypt"): plaintextContents = Rot13().encipher(plaintextContents) else: plaintextContents = Rot13().decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Rot13 ciphered " + originalPlaintext + " with a result of " + plaintextContents + ".") elif (splitLine[0] == "simplesub"): if ( len(splitLine[1]) != 26 ): # This makes sure that the keysquare's length is exactly 25. print( "Keycode line: " + str(i + 1) + ": Simple substitution cipher detected on keycode line " + str(i) + " attempting to use key that is not 26 characters long.") sys.exit() else: originalPlaintext = plaintextContents if (debug): print( "Keycode line: " + str(i + 1) + ": Simple substitution cipher detected with a key of " + splitLine[1] + ".") if (encryptionDirection == "encrypt"): plaintextContents = SimpleSubstitution( splitLine[1]).encipher(plaintextContents) else: plaintextContents = SimpleSubstitution( splitLine[1]).decipher(plaintextContents) if (debug): print("Keycode line: " + str(i + 1) + ": Simple substitution ciphered " + originalPlaintext + " by a key of " + splitLine[1] + " with a result of " + plaintextContents + ".") if (i == (len(keycodeLines) - 1)): # print(plaintextContents) #A debug catch that you may find useful later. return plaintextContents
# this code cracks the affine cipher import re from ngram_score import ngram_score fitness = ngram_score('quadgrams.txt') # load our quadgram statistics from pycipher import Affine def break_affine(ctext): # make sure ciphertext has all spacing/punc removed and is uppercase ctext = re.sub('[^A-Z]', '', ctext.upper()) # try all posiible keys, return the one with the highest fitness scores = [] for i in [1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25]: scores.extend([(fitness.score(Affine(i, j).decipher(ctext)), (i, j)) for j in range(0, 25)]) return max(scores) # example ciphertext ctext = 'QUVNLAUVILZKVZZZVNHIVQUFSFZHWZQLQHQLJSNLAUVI' max_key = break_affine(ctext) print 'best candidate with key (a,b) = ' + str(max_key[1]) + ':' print Affine(max_key[1][0], max_key[1][1]).decipher(ctext)
print("\nError for 'a'.\nEnter a value in the range [1,26]\n") continue b=int(input("b (Value b for key) : ")) if( b<1 or 26<b ): print("\nError for 'b'.\nEnter a value in the range [1,26]\n") continue print("Key : (%d,%d)" %(a,b)) plain=input("Plain Text : ") cipher='' for letter in plain: if letter not in string.ascii_letters: cipher += letter else: cipher += Affine(a,b).encipher(letter) print("Cipher Text :",cipher) print("---------------------------------") if( mode == '2'): a=int(input("a (Value a for key) : ")) if( a<1 or 26<a ): print("\nError for 'a'.\nEnter a value in the range [1,26]\n") continue b=int(input("b (Value b for key) : ")) if( b<1 or 26<b ): print("\nError for 'b'.\nEnter a value in the range [1,26]\n") continue print("Key : (%d,%d)" %(a,b))
if check(tmp): ans = tmp except: print("### Not rot16 ###") #atbash try: tmp = str.translate(cipher_string, atbash) if check(tmp): ans = tmp except: print("### Not atbash ###") #affine try: tmp = Affine(a, b).decipher(cipher_string) if "DOGECTF" in tmp: tmp = tmp[0:7] + '{' + tmp[7:] + '}' if check(tmp): ans = tmp except: print("### Not affine ###") #railfence try: tmp = decryptRailFence(cipher_string, k) if check(tmp): ans = tmp except: print("### Not affine ###")
1-encrypt \n2-decrtpt """) choise = input('Choise: ') if choise == 1 or choise == '1': plaintext = str(input("\033[97mYour Secret Text :\033[91m ")) words = plaintext.split(" ") key1 = int( input( "\033[97mchoise the first key ! like:[0,1,2,3,4,..] default=1 ! :\033[91m " )) key2 = int( input( "\033[97mchoise the first key ! like:[0,1,2,3,4,..] default=1 ! :\033[91m " )) i = 0 for i in range(len(words)): cipher = Affine(a=key1, b=key2).encipher(words[i]) cipher = cipher.lower() print(cipher, sep=' ', end=" ") else: cipher = str(input("\033[97mYour Text : ")) words = cipher.split(" ") key1 = int(input("\033[97mThe first key that you encrypt with :\033[91m ")) key2 = int( input("\033[97mThe second key that you encrypt with :\033[91m ")) i = 0 for i in range(len(words)): plaintext = Affine(a=key1, b=key2).decipher(words[i]) plaintext = plaintext.lower() print(plaintext, sep=' ', end=" ") print("\033[0m ")
def affineencode(importx, infilepath, outfilepath, inputformat, export, raw, a, b): a = int(a) b = int(b) if importx == 'file': f = open(infilepath, 'r') raw = f.read() f.close() elif importx == 'print': raw = raw else: print('\033[1;31m[-]\033[0m Unknown error.') return False inp = raw if inputformat == 'base64': iput = base64.b64decode(inp) elif inputformat == 'raw': iput = inp elif inputformat == 'base32': iput = base64.b32decode(inp) elif inputformat == 'base16': iput = base64.b16decode(inp) elif inputformat == 'base58': iput = base58.b58decode(inp) elif inputformat == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'hex': iput = inp.decode('hex') elif inputformat == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'binary': iput = text_from_bits(inp) else: print('\033[1;31m[-]\033[0m Unknown error.') return False output = Affine(a, b).encipher(iput) if export == 'file': f = open(outfilepath, 'w') f.write(output) f.close() return True elif export == 'print': return output else: print('\033[1;31m[-]\033[0m Unknown error.') return False
from pycipher import Affine for i in range(1, 25): for i2 in range(0, 25): try: s = Affine(a=i, b=i2).decipher("myjd{ij_fkwizq}") if "actf" in s.lower(): print(s) except Exception: pass