コード例 #1
0
ファイル: test_caesar.py プロジェクト: NateV/caesar_cipher
def test_decrpyt():
    k = 3
    c = "khoor"
    assert decrypt(k,c)=="hello"

    k=3
    c="khoor khoor"
    assert decrypt(k,c)=="hello hello"

    k = 40
    c = "V"
    assert decrypt(k,c)=="h"
コード例 #2
0
def test_caesar_decrypt_upper():
    """
    Test caesar upper
    """
    assert caesar.decrypt(
        "DRO AESMU LBYGX PYH TEWZC YFOB DRO VKJI NYQ",
        10) == "the quick brown fox jumps over the lazy dog".upper()
コード例 #3
0
def test_caesar_decrypt_insane():
    """
    Test caesar insane
    """
    assert caesar.decrypt(
        "znk waoiq Hxuct lud_ pasvy ubkx znk rgFe jum?",
        500) == "the quick Brown fox_ jumps over the laZy dog?"
コード例 #4
0
def test_caesar_decrypt_zapor():
    """
    Test caesar zapor
    """
    assert caesar.decrypt(
        "the quick Brown fox_ jumps over the laZy dog?",
        -500) == "znk waoiq Hxuct lud_ pasvy ubkx znk rgFe jum?"
コード例 #5
0
ファイル: routes.py プロジェクト: ambashtalk/BreakMe
def Caesar():
  msg = ''
  output = ''
  set1 = 'opt1'
  set2 = 'opt4'
  shift = '0'
  if request.method == 'POST':
    task = request.form.get('task')
    msg = request.form.get('original-text')
    set1 = request.form.get('set1')
    set2 = request.form.get('set2')
    shift = request.form.get('shift')
    if task == 'encrypt':
      output = caesar.encrypt(msg,int(shift))
      if set1 == 'opt1':
        pass
      elif set1 == 'opt2':
        output = removeAllSpecialCharactersExcludingSpaces(output)
      elif set1 == 'opt3':
        output = removeAllSpecialCharactersIncludingSpaces(output)
    elif task == 'decrypt':
      output = caesar.decrypt(msg,int(shift))
      if set1 == 'opt1':
        pass
      elif set1 == 'opt2' :
        output = removeAllSpecialCharactersExcludingSpaces(output)
      elif set1 == 'opt3':
        output = removeAllSpecialCharactersIncludingSpaces(output)
    if set2 == 'opt4':
        pass
    elif set2 == 'opt5':
      output = output.upper()
    elif set2 == 'opt6':
      output = output.lower()
  return render_template('caesar.html', title='Caesar Cipher', msg=msg, output=output, set1=set1, set2=set2, shift=shift)
コード例 #6
0
def test(input, password):
    cprint("Input:", attrs=["bold", "underline"])
    print(input + "\n")

    cprint("Password:"******"bold", "underline"])
    print(password + "\n")

    output = caesar.encrypt(input, password)
    cprint("Output:", attrs=["bold", "underline"])
    print(output + "\n")

    revInput = caesar.decrypt(output, password)
    cprint("Reversed input:", attrs=["bold", "underline"])
    print(revInput)

    if revInput == input:
        cprint("(Correct)\n", "green")

    else:
        cprint("\nIncorrect en-/decryption!", "red")
        sys.exit(1)

    revPassword = reconstruct.reconstruct(input, output)
    cprint("Reversed password:"******"bold", "underline"])
    print(revPassword)

    if reconstruct.compare(reconstruct.convertPassword(password), revPassword):
        cprint("(Correct)", "green")

    else:
        cprint("\nIncorrect reconstruction!", "red")
        sys.exit(1)
コード例 #7
0
def main():

    print("\n\n********************* ENCODE & DECODE CIPHERED TEXT IN IMAGE *********************")

    # Initialize parser 
    parser = argparse.ArgumentParser() 

    # Adding optional argument 
    parser.add_argument("-k", "--key", help = "insert your shift key for cipher",type=int) 
    parser.add_argument("-m", "--message", help = "insert your message here")
    parser.add_argument("-e", "--encode", help = "name of the image file where we want to hide the message")
    parser.add_argument("-n", "--newimg", help = "name of the new image file where data will be hidden")
    parser.add_argument("-d", "--decode", help = "name of the image file which has the hidden message")
    parser.add_argument("-s", "--syntax", help = "Type 'python filename.py -s YES' or 'python filename.py --syntax YES'")

    
    # Read arguments from command line   

    args = parser.parse_args() 
    syntaxhelp = False
    if args.syntax:
        print("[*] To encode use the following syntax:")
        print("python filename.py -e [image name with extension] -n [new image name with extension] -k [shift key, an integer value] -m [Your string to be encoded within inverted commas]\n")
        print("[*] To decode use the following syntax:")
        print("python filename.py -d [image name with extension where the data is hidden] -k [shift key, an integer value]\n")
        syntaxhelp = True

        
    if syntaxhelp==False:
        if args.encode is None and args.decode is None:
            print("\n\n[-] No arguments were provided.")
            print("[*] Type 'python filename.py -h' or 'python filename.py --help' for help.\n\n")

        if args.encode: 
            print("[*] Encoding data in the image initiated.\n[*] Image name: % s\n" % args.encode)
            if args.key is None or args.message is None or args.newimg is None:
                print("Process terminated due to lack of arguments!")
            else:
                msg = caesar.encrypt(args.message,args.key)
                print("[+] Data ciphered successfully --------- [50%  Completed]")

                feedback = steganography.encode(args.encode,msg,args.newimg)
                if feedback==True:
                    print("[+] Encoding successful ---------------- [100% Completed]\n")
                    print("[+] The new image is saved as: % s\n" % args.newimg)

                
        if args.decode: 
            print("[*] Decoding data from the image initiated")
            print("[*] Image name: % s\n" % args.decode)
            if args.key:
                ciphermsg = steganography.decode(args.decode)
                print("[+] Decoding successful ----------------- [50%  Completed]")
                msg = caesar.decrypt(ciphermsg, args.key)
                print("[+] Data deciphered successful ---------- [100% Completed]\n")
                print("[+] The data decoded and deciphered from the image is: ",msg)
                print("[+] Task Completed")
コード例 #8
0
ファイル: main.py プロジェクト: oshlern/Crypto
def decrypt(cypher, crypt, key):
    msg = ''
    if cypher == "caesar":
        msg = caesar.decrypt(crypt, int(key))
    elif cypher == "vigenere":
        msg = vigenere.decrypt(crypt, key)
    else:
        print 'cypher not found'
        return 0
    return msg
コード例 #9
0
ファイル: crack.py プロジェクト: vanceb/STEM_Python_Crypto
def main():
    # Get the message from the user
    # Python2
    #message = raw_input("Please type the encrypted message: ")
    # Python3
    message = input("Please type the encrypted message: ")

    # Try every key in sequence
    for key in range(len(LETTERS)):
        # Print out the key and the decrypted text for the user
        print(str(key) + ": " + decrypt(key, message))
コード例 #10
0
def decrypt_tester(text, key, expected):
    '''
Function: decrypt_tester
test the output of the caesar decryption against the expected output
Params:   text     -- cipher text string
key -- integer giving cipher magnitude and direction
expected -- expected output
Returns boolean indicating proper output
'''
    print('Testing caesar decryption')
    actual = decrypt(text, key)
    return actual == expected
コード例 #11
0
def caesar_decrypt(msg, step, label):
    if msg == "":
        print("[message] is empty")
        messagebox.showinfo('Error', '[message] is empty')
        return
    elif step == "":
        print("step was not specified - decrypting without step")
        label.delete(0, END)
        label.insert(0, caesar.select_best(caesar.decrypt_smart(msg)))
    elif not step.isdigit():
        print("step parameter has to be digit")
        messagebox.showinfo('Error', 'step parameter has to be a digit')
    else:
        label.delete(0, END)
        label.insert(0, caesar.decrypt(msg, int(step)))
コード例 #12
0
def etTuBrute(raw_text):
    stats = []  #will hold the error statistics
    for c in xrange(26):
        text = caesar.decrypt(raw_text, c)  #decrypt the text with each offset

        #count the number of occurances of each unique letter
        letter_count = {}
        for i in xrange(len(text)):
            if text[i] in letter_count.keys():
                letter_count[text[i]] += 1
            elif text[i] not in letter_count.keys():
                letter_count[text[i]] = 1

        #calculate the frequency of the letters
        letter_freq = {}
        for key in letter_count.keys():
            letter_freq[key] = round(
                float(letter_count[key]) / len(text) * 100, 5)

        #count the number of occurances of digrams in the text
        digram_count = {}
        n = 0
        while n < len(text):
            if text[n:n + 2] in digram_count.keys():
                digram_count[text[n:n + 2]] += 1
            elif text[n:n + 2] not in digram_count.keys():
                digram_count[text[n:n + 2]] = 1
            n += 2

        #calculate the frequency of the digrams
        digram_freq = {}
        for key in digram_count.keys():
            digram_freq[key] = round(
                float(digram_count[key]) / len(text) / 2 * 100, 5)

        #calculate errors
        monogram_error = round(meanSquaredError(monogram_freq, letter_freq), 5)
        digram_error = round(meanSquaredError(bigram_freq, digram_freq), 5)

        print c, (monogram_error + digram_error) / 2
        stats.append((monogram_error + digram_error) /
                     2)  #track average of monogram error and digram error

    #make a prediction about which offset was used to encrypt the text
    predicted_offset, predicted_min = findMinOfList(stats)
    print "Predicted Key:", predicted_offset, "Error:", predicted_min
コード例 #13
0
def decrypt(message, key, xor=False):
    decrypted = ""
    keyString = generateKeyString(key, len(message))

    if xor:
        i = j = 0
        length = len(message)
        while i < length:
            ch = message[i:i + 2]
            ch = int(ch, 16)
            #print(ch)
            ch = format(ch ^ ord(keyString[j]), "x")
            ch = chr(int(ch, 16))
            decrypted += ch
            i += 2
            j += 1
    else:
        for i, ch in enumerate(message):
            decrypted += caesar.decrypt(ch, cs.offset(keyString[i]))

    return decrypted
コード例 #14
0
print("=================================")
print("===========CAESAR CYPER==========")
print("=================================")
print()

M = "The entire message for Caesar Cypher."
K = 'b'

print("Key:", K)
print("Message:", M)
print("Length:", len(M), "\n")

C = caesar.encrypt(M, cs.offset(K))
print("Encrypted:", C)

m = caesar.decrypt(C, cs.offset(K))
print("Decrypted:", m, end=" ")

if M == m:
    print("[success]\n")
else:
    print("[fail]\n")

print("Cracking '", C, "' with brute force...\n", sep="")
caesar.bruteForceCrack(C)

print("Cracking '", C, "' with probabilistic cracking...\n", sep="")
caesar.probabilisticCrack(C)

print("\n")
print("=================================")
コード例 #15
0
def test_caesar_decrypt_mix():
    """
    Test caesar mix
    """
    assert caesar.decrypt("dRo AesMu lbYgx pyh Tewzc YFOB DrO VkJi nyq",
                          10) == "tHe QuiCk brOwn fox Jumps OVER ThE LaZy dog"
コード例 #16
0
ファイル: crackCyphers.py プロジェクト: oshlern/Crypto
def vigenereBreak(crypt):
    print "\n\n~~~~~~~~~~~~~~~~~~~~BREAKING CAESAR~~~~~~~~~~~~~~~~~~~~~"
    for i in range(26):
        print ' '*i, caesar.decrypt(crypt, i), '\n\n'
    return 0
コード例 #17
0
def test_caesar_decrypt_lower():
    """
    Test caesar lower
    """
    assert caesar.decrypt("dro aesmu lbygx pyh tewzc yfob dro vkji nyq",
                          10) == "the quick brown fox jumps over the lazy dog"
コード例 #18
0
import caesar
import vigenere

print('1.1. ', caesar.encrypt('PREMIER EXEMPLE', 'Y'))
print('1.2. ', caesar.decrypt('MZMV CV DFULCV UV TIPGKF', 'R'))
print('1.3. ', caesar.decrypt('KNS IZ UWJRNJW JCT'))

print('2.1. ', vigenere.encrypt('CAMARCHE', 'ROI'))
print(
    '2.2. ',
    vigenere.decrypt(
        'XATBGYQBJTQVMUUEEZDDWEYEQELIPVGRWTWVROFMVVXEKRILJSGGTVFILYEFZDWEMTUEMQEUUSHTVLPAFLPRZUAMFIGNW',
        'MASTER'))
コード例 #19
0
    def test_decrypt_works(self):
        plaintext = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.lower()
        ciphertext = 'DEFGHIJKLMNOPQRSTUVWXYZABC'.lower()

        plaintext_o = decrypt(ciphertext, 3)
        self.assertEqual(plaintext, plaintext_o)
コード例 #20
0
from caesar import decrypt

shift = 5

with open('ciphertext.txt', 'r') as myfile:
    filecontents = myfile.read()

print("caesar decrypt with key %d" % (shift))
print("Input")
print("--------------------")
print(filecontents)

print("\nDecrypted output")
print("--------------------")
print(decrypt(filecontents, shift))
コード例 #21
0
import caesar

input_file = open("dane/dane_6_2.txt")
output_file = open("wyniki_6_2.txt", "w")

for line in input_file:
    eword = line.strip().split()
    eword = tuple([eword[0], int(eword[1])])

    dword = caesar.decrypt(eword[0], eword[1])
    output_file.write(f"{dword}\n")

input_file.close()
output_file.close()
コード例 #22
0
ファイル: crack.py プロジェクト: citterio/handcrypt
LETTERS = ['etaoinshrdlcumwfgypbvkjxqz']
LETTERS = ['etaoinsh']
DIGRAPHS = ['ST','NG','TH','QU']


ciphertext = """LIVITCSWPIYVEWHEVSRIQMXLEYVEOIEWHRXEXIPFEMVEWHKVSTYLXZIXLIKIIXPIJVSZEYPERRGERIM
WQLMGLMXQERIWGPSRIHMXQEREKIETXMJTPRGEVEKEITREWHEXXLEXXMZITWAWSQWXSWEXTVEPMRXRSJ
GSTVRIEYVIEXCVMUIMWERGMIWXMJMGCSMWXSJOMIQXLIVIQIVIXQSVSTWHKPEGARCSXRWIEVSWIIBXV
IZMXFSJXLIKEGAEWHEPSWYSWIWIEVXLISXLIVXLIRGEPIRQIVIIBGIIHMWYPFLEVHEWHYPSRRFQMXLE
PPXLIECCIEVEWGISJKTVWMRLIHYSPHXLIQIMYLXSJXLIMWRIGXQEROIVFVIZEVAEKPIEWHXEAMWYEPP
XLMWYRMWXSGSWRMHIVEXMSWMGSTPHLEVHPFKPEZINTCMXIVJSVLMRSCMWMSWVIRCIGXMWYMX"""

keys = {}
for ch in ascii_uppercase:
    plaintext = caesar.decrypt(ciphertext,ch).upper()
    print
    print ch,plaintext
    print
    tscore = 0
    score = 4
    for dg in DIGRAPHS:
        tscore = plaintext.count(dg)*score
        score -= 1
    keys[ch] = tscore

# print keys
# smax = max(keys.values())
# for ch,tscore in keys.iteritems():
#     if tscore == smax:
#         print caesar.decrypt(ciphertext,ch)
コード例 #23
0
ファイル: main.py プロジェクト: VanclDavid/TULITWorks
from caesar import encrypt, decrypt

if __name__ == '__main__':
    print(encrypt("ahoj blazne cos cekal?", 13))
    print(decrypt("nubw oynmar pbf prxny?", 13))
コード例 #24
0
# Brute force approch, i.e., try all possible keys

from caesar import CHSET, decrypt

C = ":òhìv..rxxzùhtzw'r,ùhtùòhzéhtzw'r'zùhuzhtv.r'v"

for k in range(len(CHSET)):
    print(k, decrypt(C, k))
コード例 #25
0
from reverse_cipher import reverse_cipher

# from caesar_cipher import (
#     caesar_cipher_encrypt,
#     caesar_cipher_decrypt,
#     caesar_cipher_hacking,
# )
from rot13_cipher import rot13_cipher_encrypt, rot13_cipher_decrypt
import atbash
import caesar

# print(reverse_cipher("message"))
# print(reverse_cipher(reverse_cipher("message")))
print("-----------------------------------------")
print(caesar.encrypt("Hola Mundo!", 9))
print("-----------------------------------------")
print(caesar.decrypt(caesar.encrypt("Hola Mundo!", 9), 9))
print("-----------------------------------------")
print("\n".join(caesar.hacking(caesar.encrypt("Hola Mundo!", 9))))
print("-----------------------------------------")
# print(caesar_cipher_decrypt(caesar_cipher_encrypt("Alfredo Poveda", 18), 18))
# print(caesar_cipher_hacking(caesar_cipher_encrypt("Alfredo Poveda", 9)))
# print(rot13_cipher_encrypt("ROT13 Algorithm"))
# print(rot13_cipher_decrypt(rot13_cipher_encrypt("ROT13 Algorithm")))
print(atbash.encrypt("Hola Mundo!"))
print("-----------------------------------------")
print(atbash.decrypt(atbash.encrypt("Hola Mundo!")))
print("-----------------------------------------")
コード例 #26
0
def main():
    '''
        PARTE I: MANIPULACION DE IMAGEN Y CAPTURA DE MENSAJE SECRETO
    '''
    img = Image.open('matroska.png')
    format = img.format
    size = img.size
    mode = img.mode

    print("Image Format: ", format, "Image Size: ", size, "Image Mode: ", mode)

    img_width = size[0]
    img_height = size[1]

    img_bitmap = img.load()

    # Convierte el archivo en blanco y negro

    print("filtering image...")
    for i in range(img_width):
        for j in range(img_height):
            old_pixel = img_bitmap[i, j]
            red = old_pixel[0]
            green = old_pixel[1]
            blue = old_pixel[2]

            new_pixel = pixel_filter(red, green, blue)

            img_bitmap[i, j] = new_pixel

    img.save('matroska-filtered.png')

    print("done...")

    message_img = cv2.imread('matroska-filtered-message.png')
    ciphered_text = message_extract(message_img)

    print("Ciphered Message: ", ciphered_text)

    ciphered_text_lines = ciphered_text.split("{!@#$%}")
    ciphered_text_lines.pop()
    ciphered_text_lines[:] = [item for item in ciphered_text_lines if item]
    length = len(ciphered_text_lines)

    for i in range(length):
        ciphered_text_lines[i] = ciphered_text_lines[i].replace(" ", "")

    print("Lines in text: ", length)
    # for line in ciphered_text_lines:
    #     print(line + "\n")

    with open("ciphered-message.txt", "w") as cFile:
        for line in ciphered_text_lines:
            cFile.write(line + "\n")
    '''
        PARTE II: PROCESO DE DESENCRIPCION DEL MENSAJE

    '''

    # text = caesar.decrypt("EXXEGOexsrgi", 4)
    # print("Decripted message: ", text)

    for key in range(1, 51):
        # print("Key: ", key)
        with open("decoded-message" + str(key) + ".txt", "w") as dFile:
            for line in ciphered_text_lines:
                text = caesar.decrypt(line, key)
                dFile.write(text + "\n")

    deciphered_text = []

    with open("decoded-message31.txt", "r") as rFile:
        line = rFile.readline()
        while line:
            deciphered_text.append(line)
            line = rFile.readline()

    length = len(deciphered_text)
    for i in range(length):
        deciphered_text[i] = deciphered_text[i].replace("X", " ")
        deciphered_text[i] = deciphered_text[i].replace("=", "")
        print(deciphered_text[i] + "\n")
コード例 #27
0
ファイル: crack.py プロジェクト: mhearne-usgs/handcrypt
import caesar

LETTERS = ['etaoinshrdlcumwfgypbvkjxqz']
LETTERS = ['etaoinsh']
DIGRAPHS = ['ST', 'NG', 'TH', 'QU']

ciphertext = """LIVITCSWPIYVEWHEVSRIQMXLEYVEOIEWHRXEXIPFEMVEWHKVSTYLXZIXLIKIIXPIJVSZEYPERRGERIM
WQLMGLMXQERIWGPSRIHMXQEREKIETXMJTPRGEVEKEITREWHEXXLEXXMZITWAWSQWXSWEXTVEPMRXRSJ
GSTVRIEYVIEXCVMUIMWERGMIWXMJMGCSMWXSJOMIQXLIVIQIVIXQSVSTWHKPEGARCSXRWIEVSWIIBXV
IZMXFSJXLIKEGAEWHEPSWYSWIWIEVXLISXLIVXLIRGEPIRQIVIIBGIIHMWYPFLEVHEWHYPSRRFQMXLE
PPXLIECCIEVEWGISJKTVWMRLIHYSPHXLIQIMYLXSJXLIMWRIGXQEROIVFVIZEVAEKPIEWHXEAMWYEPP
XLMWYRMWXSGSWRMHIVEXMSWMGSTPHLEVHPFKPEZINTCMXIVJSVLMRSCMWMSWVIRCIGXMWYMX"""

keys = {}
for ch in ascii_uppercase:
    plaintext = caesar.decrypt(ciphertext, ch).upper()
    print
    print ch, plaintext
    print
    tscore = 0
    score = 4
    for dg in DIGRAPHS:
        tscore = plaintext.count(dg) * score
        score -= 1
    keys[ch] = tscore

# print keys
# smax = max(keys.values())
# for ch,tscore in keys.iteritems():
#     if tscore == smax:
#         print caesar.decrypt(ciphertext,ch)
コード例 #28
0
ファイル: ciphers.py プロジェクト: codephile1221/project2019
from caesar import encrypt, decrypt
from playfair import playfairCipher

print("Choose a cipher:\n1) Caesar cipher\n2)Playfair cipher")
opt = input("->")
if opt == '1':
    print(
        "This is monoalphabetic substitution cipher where the given text's alphabet is shifted a given number of positions."
    )
    print("Choose an option:\n1)Encrypt text\n2)Decrypt text")
    opt = input("->")
    if opt == '1':
        text = input("Enter the text you want to encrypt:")
        key = int(input("Enter a key (between 1-25):"))
        print(f"Encypted text is {encrypt(text,key)}")
    else:
        text = input("Enter the text you want to decrypt:")
        key = int(
            input("Enter the key (Enter 0 for bruteforce/if key is unknown):"))
        print(decrypt(text, key))
else:
    print(
        "Playfair cipher is a manual symmetric encryption technique and was the first literal digram substitution cipher."
    )
    print("Choose an option:\n1)Encrypt text\n2)Decrypt text")
    opt = input("->")
    text = input("Enter text:")
    key = input("ENter the key (string):")
    print(f"result:{playfairCipher(text,key)}")
コード例 #29
0
 def test_both_work_together(self):
     plaintext = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.lower()
     for i in range(1, 100):
         c_o = encrypt(plaintext, i)
         p_o = decrypt(c_o, i)
         self.assertEqual(plaintext, p_o)
コード例 #30
0
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.')
コード例 #31
0
"""Crack password using Caesar Algorithms."""

import caesar

cracks = 0

with open('users_database.csv', 'r') as users_database:
    lines = users_database.readlines()[1:]
    for line in lines:
        email = line.split(',')[0]
        encrypted_passwd = line.split(',')[1]
        encrypted_letter = ord(encrypted_passwd[0])
        plain_letter = ord(line.split(',')[2][0])
        key = int()
        passwd = str()
        if encrypted_letter > plain_letter:
            key = encrypted_letter - plain_letter
        else:
            key = 26 - (plain_letter - encrypted_letter)
        passwd = caesar.decrypt(encrypted_passwd, key).lower()
        cracks +=1
        print "Email:", email, "| Password:"******"| Key:", key

print cracks, "passwords cracked successfully."
コード例 #32
0
 def test_decrypt_big(self):
     self.assertEqual(
         'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG',
         decrypt('QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD'))