def main(): caesar_cipher = CaesarCipher() parser.parse_args(namespace=caesar_cipher) # Logging configuration if caesar_cipher.verbose is True: log_level = logging.DEBUG log_format = "%(asctime)s - %(levelname)s: %(message)s" else: log_level = logging.INFO log_format = "%(message)s" logging.basicConfig(level=log_level, format=log_format) # Non-required arguments and error conditions. if caesar_cipher.offset: caesar_cipher.offset = int(caesar_cipher.offset) if caesar_cipher.offset is False and caesar_cipher.decode is True: raise CaesarCipherError("Message cannot be decoded without " "selecting an offset. Please try " "again with -o switch.") if caesar_cipher.encode is True and caesar_cipher.decode is True: raise CaesarCipherError("Please select to encode or encode a message, " "not both.") # Required arguments. if caesar_cipher.decode is True: logging.info("Decoded message: {0}".format(caesar_cipher.decoded)) elif caesar_cipher.crack is True: logging.info("Cracked message: {0}".format(caesar_cipher.cracked)) elif caesar_cipher.encode is True: logging.info("Encoded message: {0}".format(caesar_cipher.encoded)) else: logging.error("Please select a message to encode, decode or " "crack. For more information, use --help.")
def generaterandomstring(): #defining function # blank = "" #assigning blank ,count,sum count = 0 sum = 0 for i in range(0, 100): #to loop the same program from 0 to 100 rand = random.randint( 65, 122) #taking a random variable from 65 to 122 for A to z rando = random.randint(0, 30) ch = chr(rand) #converting asci value to alphabet define1 = CaesarCipher( ch, offset=rando) #passing charater and displace to orignal function logic1 = function.caeser_cipher(ch, rando) #passingto made fuction a = define1.encoded #calling the funtion b = logic1 print("DEFINE", a) print("made", b) blank = blank + ch #adding each charcter to form a string if (a == b): count = count + 1 #if original and made equal incarease the count print(count) # average = (count + sum) # sum = average # avg = sum / 10 # print("So avearage is:", avg, "%") print(blank) #print whole sting cipher = CaesarCipher(blank, offset=rando) #pass whole string print(cipher.encoded) output = function.caeser_cipher(blank, rando) print(output) print("Accuracy=", count, "%")
def check_caesar(workout_id, submission, check): # Submission is the plaintext cipher sent from student # Cipher_list is the data that is stored in Datastore key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) # data is a dict list that is passed back to page as JSON object status = workout['assessment']['questions'] data = { 'cipher1': { 'cipher': workout['container_info']['cipher_one']['cipher'], 'status': status[0]['complete'] }, 'cipher2': { 'cipher': workout['container_info']['cipher_two']['cipher'], 'status': status[1]['complete'] }, 'cipher3': { 'cipher': workout['container_info']['cipher_three']['cipher'], 'status': status[2]['complete'] }, } # Cipher list is what we compare submissions to cipher_list = [] # Decode Stored Ciphers and append to a plaintext list decoded = workout['container_info']['cipher_one']['cipher'] plaintext = CaesarCipher( decoded, offset=workout['container_info']['cipher_one']['key']).decoded cipher_list.append(plaintext) decoded2 = workout['container_info']['cipher_two']['cipher'] plaintext2 = CaesarCipher( decoded2, offset=workout['container_info']['cipher_two']['key']).decoded cipher_list.append(plaintext2) decoded3 = workout['container_info']['cipher_three']['cipher'] plaintext3 = CaesarCipher( decoded3, offset=workout['container_info']['cipher_three']['key']).decoded cipher_list.append(plaintext3) # Check if submission exists within cipher_list and update status and call publish_status if correct if check == 1 and submission in cipher_list: data['cipher1']['status'] = True workout_key = workout['assessment']['questions'][0]['key'] publish_status(workout_id, workout_key) elif check == 2 and submission in cipher_list: data['cipher2']['status'] = True workout_key = workout['assessment']['questions'][1]['key'] publish_status(workout_id, workout_key) elif check == 3 and submission in cipher_list: data['cipher3']['status'] = True workout_key = workout['assessment']['questions'][2]['key'] publish_status(workout_id, workout_key) return data
def decode(): code = request.args.get('code') try: cipher = CaesarCipher(code, offset=14).decoded link = base64.b64decode(cipher.encode('ascii')) flash(u"Giải mã URL thành công!", 'success') flash(link.decode('ascii'), 'link') except: flash("Giải mã URL thất bại!", 'fail') return render_template('link.html')
class AffineCipher(): c = CaesarCipher() m = MultiplicativeCipher() # 仿射密码加密 def Encrypt(self, messages, key1, key2): return self.c.Encrypt(self.m.Encrypt(messages, key1), key2) # 仿射密码解密 def Decrypt(self, messages, key1, key2): return self.m.Decrypt(self.c.Decrypt(messages, key2), key1) # 仿射密码测试 def test(self): messages = 'Hello, Cryptography!' key1 = 25 key2 = 17 t1 = a.Encrypt(messages, key1, key2) t2 = a.Decrypt(t1, key1, key2) print(t1+'\n'+t2) # 仿射密码攻击 def attack(self, messages): print('attack:', messages) for i in range(26): for j in range(26): try: print(self.Decrypt(messages, i, j), 'key1 =', i, 'key2 =', j) except: pass
def encodeURL(link): encoded = base64.b64encode(link.encode('ascii')) ciphertext = CaesarCipher(encoded.decode('ascii'), offset=14).encoded result = "https://mp3zing.download/redirector?code=" + ciphertext return result
def ajax_calculate_caesar(workout_id): # Returns deciphered message encrypted_message = request.get_json() key = int(encrypted_message['key']) message = str(encrypted_message['ciphertext']) plaintext = CaesarCipher(message, offset=key).decoded return jsonify({'plaintext': plaintext})
def hello_world(method, key): urls=[] for url_list in app.url_map.iter_rules(): urls.append(url_list.rule) for abc in range(26): cipher = CaesarCipher(method,offset= abc).encoded print(cipher + url_list.rule) if cipher== url_list.rule.strip("/"): print("yes") method= cipher key = CaesarCipher(key, offset=abc).encoded print(key) print(method) return pod(method,key= key) else: continue return str([a for a in urls])
def generateRandomString(): strings = '' for i in range(1, 100): raand = random.randint(65, 123) strint = chr(raand) strings = strings + strint print(strings) ciphers = CaesarCipher(strings, offset=2) print(ciphers.encoded) caesar_cipher(strings, 2)
def main(): ans = True fileName = getFileName() cc = CaesarCipher(fileName) while ans: unused_variable = os.system('clear') print("Caeser-Cipher encryption by DC") print(""" 1.Encrypt file 2.Decrypt file 3.Exit """) ans = input("What would you like to do? ") if ans == "1": cc.encondeFile() print("File was encrypted with success") time.sleep(2) elif ans == "2": cc.decodeFile() print("File was decrypted with success") time.sleep(2) elif ans == "3": ans = False elif ans != "": print("\n Not Valid Choice Try again")
def generate_random_string(counter): # defining function for generating random string from random integer values concatenated_string = "" # initialize empty variable for concatenated string for integer in range(1, 10): # loop for integer where integer is from 1 to 10 random_number = (random.randint(65, 90)) or (random.randint(96, 122)) # generating random number using random str_int = chr(random_number) # converting random number to character and assigning it to variable concatenated_string = concatenated_string + str_int # adding the converted strings cipher = CaesarCipher(concatenated_string, offset=counter) # calling library function and passing variables encoded_cipher = cipher.encoded # calling encoded function and assigning it to a variable own_cipher = CaeserCipher.caesar_cipher(concatenated_string, counter) # calling own function and passing variables(arguments) print( "The Caesar Function Result::" + encoded_cipher + " And the written caesar Result::" + own_cipher) # printing the result if encoded_cipher == own_cipher: # comparing both outputs from library function and own function return True # returning true else: # else return False # returning false
def set_ciphers(workout_id): key = ds_client.key('cybergym-workout', workout_id) workout = ds_client.get(key) result = [] clear_text = [ 'Something goes to say about how an orange tastes like its color.', 'Nothing like Java in the morning.', 'Popping Shells with Powershell.', 'In security, each minute standing still is another year going backwards.', 'Aggressively flips open flip phone: "Try hacking me now, buddy"', 'Help! How do I exit VIM?', 'Security by obscurity', 'Disappointed a firewall isn\'t an actual wall of fire', 'Before anything else, getting ready is the secret of success. - Henry Ford', 'You can observe a lot by just watching. - Yogi Berra', 'The Future ain\'t what it used to be. - Yogi Berra', 'Servers are going down at midnight', 'The true definition of a keyboard warrior should be a Cybersecurity expert.', 'Planted 5 O.MG cables in target office', 'You\'re being followed. Run.', 'The bird is in the sky.', 'Nothing hurts more than a missing one ; in 10000 lines of code', 'Hey Google? How do I vaccinate my computer?', 'For each coat of paint, a room gets that much smaller.', ] for pos in range(len(clear_text)): key = random.randrange(1, 25) cipher_string = CaesarCipher(clear_text[pos], offset=key).encoded cipher = { 'key': key, 'cipher': cipher_string, } result.append(cipher) # Selects 3 unique ciphers from list cipher_list = random.sample(result, k=3) workout['container_info']['cipher_one'] = cipher_list[0] workout['container_info']['cipher_two'] = cipher_list[1] workout['container_info']['cipher_three'] = cipher_list[2] ds_client.put(workout) return cipher_list
def predict(): query = request.form['cipher'] model = load_model('model.h5') count_test={} for i in range(1,27): count_test[i]=0 for letter in query: if letter.isalpha(): count_test[ord(letter)-97+1] = count_test.get(ord(letter)-97+1, 0) + 1 temp_list=[] for key,value in count_test.items(): temp_list.append(value) test_array = np.array(temp_list) test_array = test_array.reshape(1,26) key = (np.argmax(model.predict(test_array))+1) d= CaesarCipher(query,offset=key) decoded_string = d.decoded return render_template('display.html', string = query , key = key, decoded_string = decoded_string)
def solve(bomb: Bomb, display: str = None): cprint('Caesar Cipher', 'yellow', attrs=['reverse']) offset = 0 if bomb.serial_has_vowel(): offset -= 1 offset += bomb.batteries if bomb.serial_last_digit() % 2 == 0: offset += 1 if 'CAR' in bomb.get_all_indicators(): offset += 1 if 'PARALLEL' in bomb.get_all_ports() and 'NSA' in bomb.lit_indicators: offset = 0 cprint('Offset: ' + str(offset), 'green') if display: cipher = CaesarCipher(display, offset=offset) cprint(cipher.encoded, 'cyan')
def crack_caesar(cipher): charset = 'abcdefghijklmnopqrstuvwxyz' def rot(cipher, shift): trans = charset[shift:] + charset[:shift] plaintext = '' for c in cipher: p = charset.find(c) if p == -1: plaintext += c else: plaintext += trans[p] return plaintext from caesarcipher import CaesarCipher results = [] for i in range(0, len(charset)): plain = rot(cipher, i) entropy = CaesarCipher().calculate_entropy(plain) results.append((entropy, plain)) bestscore, plaintext = sorted(results)[0] return plaintext
def test_encode_decode_consistent(self): message = "The quick brown fox jumps over the lazy dog." setup_cipher = CaesarCipher(message, encode=True, offset=14) encoded_message = setup_cipher.encoded test_cipher = CaesarCipher(encoded_message, decode=True, offset=14) self.assertEquals(message, test_cipher.decoded)
import random import base64 from caesarcipher import CaesarCipher flag = "hackgt{how_does_encoding_work}" current = flag for i in range(15): if bool(random.randint(0, 1)): print 'encode' current = base64.b64encode(current) else: print 'shift' current = CaesarCipher(current, 13).encoded print current num = 0 print '' print 'start' while num < 15: try: print 'decode' current = base64.b64decode(current) num += 1 except: print 'shift' break
sortedLetters = sorted(dict4Checksum.items(), key=operator.itemgetter(1)) revDict = dict() for letter, number in sortedLetters: if revDict.get(number) is not None: revDict[number].append(letter) else: revDict[number] = [letter] for aNumber in revDict.keys(): revDict[aNumber].sort() theLetters = [] #print(revDict) while len(theLetters) < 5: maxIndex = max(revDict.keys()) theLetters.append(revDict[maxIndex][0]) revDict[maxIndex].pop(0) if len(revDict.get(maxIndex)) == 0: revDict.pop(maxIndex) if checksumLetters == theLetters: idNum = sum(int(id[i]) * 10**(len(id) - i - 1) for i in range(len(id))) totalSum += idNum #print(id) print(idNum) cipher = CaesarCipher(theString) #, offset = idNum%26) print(cipher.cracked) # grep the result! print(totalSum)
def caesar_letter_shift(string, o): cipher = CaesarCipher(string, offset=o) return cipher.decoded
#!/usr/bin/python import sys from caesarcipher import CaesarCipher frase = sys.argv[1] crc8total = sys.argv[2] # En este script únicamente ejecuto el cifrado césar mediante # la llamada al método de cifrado de la librería CaesarCipher cipher = CaesarCipher(frase.lower(), offset=int(crc8total)) # Y devuelvo el texto encriptado a Node JS print(str(cipher.encoded))
def test_encode_with_known_offset(self): message = "Twilio" test_cipher = CaesarCipher(message, encode=True, offset=1) self.assertEquals(test_cipher.encoded, "Uxjmjp")
def test_encode_decode_persistence(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, encode=True, offset=14) test_cipher.encoded self.assertEquals(message, test_cipher.decoded)
# ./requirements.txt import emoji print(emoji.emojize("\n\n:sparkles: Beginning Execution :sparkles:\n\n")) # ./src/src_module.py import src_module # ./src/example_package/ex_package import ex_package # ./included/code/caesarcipher.zip from caesarcipher import CaesarCipher cc = CaesarCipher() # ./include/code/included_folderA/included_module.py import included_module print( f"\n\nWhat does the module say?\n {included_module.the_module_says()}\n\n" ) # ./include/include_assets.txt with open(SparkFiles.get("sagely.txt")) as art_file: print(f"\nSage says: {art_file.read()}\n\n") # ./include/include_code.txt import my_module
def test_decode_long_phrase_with_known_offset(self): message = "AOL XBPJR IYVDU MVE QBTWZ VCLY AOL SHGF KVN." test_cipher = CaesarCipher(message, decode=True, offset=7) self.assertEquals(test_cipher.decoded, "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.")
def test_decode_with_offset_greater_than_alphabet_length(self): message = "VJG SWKEM DTQYP HQZ LWORU QXGT VJG NCBA FQI." test_cipher = CaesarCipher(message, decode=True, offset=28) self.assertEquals(test_cipher.decoded, "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.")
def test_all_offsets(self): message = "The quick brown fox jumps over the lazy dog." for i in range(0, 100): test_cipher = CaesarCipher(message, encode=True, offset=i) test_cipher.encoded self.assertEquals(message, test_cipher.decoded)
def test_decode_with_arbitrary_alphabet(self): message = "Kfj rzbad mytpo ltu szenw tijy kfj cvqg xth." alphabet = 'ueyplkizjgncdbqshoaxmrwftv' test_cipher = CaesarCipher(message, offset=7, alphabet=alphabet) self.assertEquals('The quick brown fox jumps over the lazy dog.', test_cipher.decoded)
def test_calculate_entropy_zero_offset(self): message = "The quick brown fox jumps over the lazy dog." test_cipher = CaesarCipher(message, crack=True) confirmed_entropy_value = 179.14217305030957 test_entropy_value = test_cipher.calculate_entropy(message) self.assertEquals(confirmed_entropy_value, test_entropy_value)
def test_decode_with_known_offset(self): message = "UXJMJP" test_cipher = CaesarCipher(message, encode=True, offset=1) self.assertEquals(test_cipher.decoded, "TWILIO")
cifrado = str(json_res['cifrado']) decifrado = str(json_res['decifrado']) resumo_criptografico = str(json_res['resumo_criptografico']) print("numero_casas: ", numero_casas) print("token : ",token) print("cifrado : ",cifrado) print("decifrado: ",decifrado) print("resumo_criptografico: ", resumo_criptografico) print(" ") from caesarcipher import CaesarCipher cipher = CaesarCipher(str(cifrado),offset=int(numero_casas)) decifrado = cipher.decoded print("numero_casas: ", numero_casas) print("token : ",token) print("cifrado : ",cifrado) print("decifrado: ",decifrado) import hashlib resumo_criptografico = hashlib.sha1(str(decifrado).encode('utf-8')).hexdigest() print("resumo_criptografico",resumo_criptografico) print(" ") class cjc():
def test_decode_with_very_large_offset(self): message = "RFC OSGAI ZPMUL DMV HSKNQ MTCP RFC JYXW BME." test_cipher = CaesarCipher(message, decode=True, offset=10008) self.assertEquals(test_cipher.decoded, "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.")