def edit_fast(cipher, newtext): counter = Crypto.gen_aes_stream_counter_mt19973(seed); text = Crypto.decrypt_aes( cipher, key, AES.MODE_CTR, counter=counter) text = newtext counter = Crypto.gen_aes_stream_counter_mt19973(seed); return Crypto.encrypt_aes(text, key, AES.MODE_CTR, counter=counter)
def __init__(self, host, port, conf_key, auth_key): crypt = Crypto() listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.bind( (host, int(port))) # this socket is bound to my port 9876 listen_socket.listen(1) # specify the "backlog" for this socket while True: # create the input list read_list = [listen_socket, sys.stdin] + self.connected_clients (ready_list, _, _) = select.select(read_list, [], []) for ready in ready_list: if ready is listen_socket: conn, addr = ready.accept() self.connected_clients += [conn] elif ready == sys.stdin: msg = sys.stdin.readline() msg = crypt.encrypt(msg, conf_key, auth_key) self.shout(listen_socket, msg) else: data = ready.recv(1024) if len(data) == 0: self.connected_clients.remove(ready) else: decrypt_data = crypt.decrypt(data, conf_key, auth_key) print(decrypt_data) self.shout(ready, decrypt_data.rstrip())
def edit(cipher, offset, newtext): counter = Crypto.gen_aes_stream_counter_mt19973(seed); text = Crypto.decrypt_aes( cipher, key, AES.MODE_CTR, counter=counter) text = text[:offset] + newtext + text[offset + 1:] counter = Crypto.gen_aes_stream_counter_mt19973(seed); return Crypto.encrypt_aes(text, key, AES.MODE_CTR, counter=counter)
def __init__(self, file_name, loop): """ Default constructor @param file_name: Name of the file to send @param loop: Asyncio Loop to use """ self.file_name = file_name self.loop = loop self.chunk_count = 0 self.last_pos = 0 self.symetric_ciphers = ['ChaCha20', 'AES', '3DES'] self.cipher_modes = ['CBC', 'ECB', 'GCM'] self.digest = ['SHA384', 'SHA256', 'SHA512', 'MD5', 'BLAKE2'] self.state = STATE_CONNECT # Initial State self.buffer = '' # Buffer to receive data chunks self.choosen_cipher = None self.choosen_mode = None self.choosen_digest = None self.crypto = Crypto(self.choosen_cipher, self.choosen_mode, self.choosen_digest) self.encrypted_data = ''
def test_break_random_access_read_write(self): """Challenge 25""" f = open('data/25.txt') data = f.read() f.close() key = 'YELLOW SUBMARINE' known = Crypto.decrypt_aes(base64.b64decode(data), key, AES.MODE_ECB) seed = 23232232; def edit(cipher, offset, newtext): counter = Crypto.gen_aes_stream_counter_mt19973(seed); text = Crypto.decrypt_aes( cipher, key, AES.MODE_CTR, counter=counter) text = text[:offset] + newtext + text[offset + 1:] counter = Crypto.gen_aes_stream_counter_mt19973(seed); return Crypto.encrypt_aes(text, key, AES.MODE_CTR, counter=counter) def edit_fast(cipher, newtext): counter = Crypto.gen_aes_stream_counter_mt19973(seed); text = Crypto.decrypt_aes( cipher, key, AES.MODE_CTR, counter=counter) text = newtext counter = Crypto.gen_aes_stream_counter_mt19973(seed); return Crypto.encrypt_aes(text, key, AES.MODE_CTR, counter=counter) counter = Crypto.gen_aes_stream_counter_mt19973(seed); cipher = Crypto.encrypt_aes(known, key, AES.MODE_CTR, counter=counter) text = edit_fast(cipher, cipher) # replacing text with cipher is same is decrypting cipher. #for i in range(len(cipher)): # text += edit(cipher, i, cipher[i])[i] self.assertEqual(known, text)
def test_get_latest_price(self): id = 'btc' currency = 'usd' responses.add(responses.GET, f'{TICKER_API_URL}/coins/list', json=[{ 'id': 'btc', 'symbol': 'BITCOIN' }, { 'id': 'doge', 'symbol': 'DOGE' }], status=200) c = Crypto() responses.add(responses.GET, f'{TICKER_API_URL}/simple/price/' + f'?ids={id}&vs_currencies={currency}', json=mock_price_response(id, currency, 512345.0), status=200) self.assertEqual(c.get_latest_price([id], currency), 'BITCOIN:$512,345 ') id = 'doge' currency = 'usd' responses.add(responses.GET, f'{TICKER_API_URL}/simple/price/' + f'?ids={id}&vs_currencies={currency}', json=mock_price_response(id, currency, 0.223432), status=200) self.assertEqual(c.get_latest_price([id], currency), 'DOGE:$0.223432 ')
def __init__(self): self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie = Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() # self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() # self.tw = Twimega() # self.motivate = Motivate() self.shortenedurl = Urlshortener() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() print("done init") self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl", "movie", "currency", "holiday", "lyrics" ]
def test_padding(self): """Challenge 9""" text = "YELLOW SUBMARINE" expected = "YELLOW SUBMARINE\x04\x04\x04\x04" self.assertEqual(expected, Crypto.pad_pkcs7(text, 20)) text = "1234567890123456" self.assertEqual(text + '\x10' * 16, Crypto.pad_pkcs7(text, 16))
def has_valid_padding(cipher, init_vector): """Checks if cipher has valid padding.""" try: Crypto.decrypt_aes(cipher, key, AES.MODE_CBC, init_vector) except ValueError: return False return True
def __init__(self): self.client = zulip.Client(site="https://chunkzz.zulipchat.com/api/") self.subscribe_all() self.chatbot = ChatBot( "Omega", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() self.tw = Twimega() self.motivate = Motivate() self.shortenedurl = Urlshortener() self.hacknews = Hackernews() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl" ]
def __init__(self, host, port, conf_key, auth_key): crypt = Crypto() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, int(port))) while True: # client has typed somethin [sys.stdin] # server sends a message [s] inputs = [sys.stdin, s] read, trash1, trash2 = select.select(inputs, [], []) for sock in read: if sock == s: # if sock is server, check for data data = sock.recv(1024) # write data to terminal decrypt_data = crypt.decrypt(data, conf_key, auth_key) print(decrypt_data) # otherwise client is trying to send a message else: # send server message msg = sys.stdin.readline() msg = crypt.encrypt(msg, conf_key, auth_key) s.send(msg)
def test_ecb_or_cbc_mode(self): """Challenge 11""" text = open('data/plaintext.txt').read() for _ in range(20): cipher, mode = Crypto.oracle_encryption(text) expected = True if mode == AES.MODE_ECB else False self.assertEqual(expected, Crypto.is_aes_ecb_cipher(cipher))
def __init__(self, target_path: str, backup_path: str, password: str): if not op.isdir(target_path): raise Exception() self.crypto = Crypto(password) self.file_iterator = FileItter(target_path) self.files = self.file_iterator.itter_files(target_path) self.directories = self.file_iterator.itter_directories() self.temp_folder = tempfile.TemporaryDirectory() self.backup_path = backup_path self.target_path = target_path self.temp_path = self.temp_folder.name pathlib.Path(backup_path).mkdir(parents=True, exist_ok=True) # creates backup folder self.backup_zip = zipfile.ZipFile(self.temp_path + "\\backup.zip", mode='w', compression=zipfile.ZIP_STORED, allowZip64=True) self.backup_zip_path = self.backup_zip.filename self.main_config_dict = dict()
def matchYubikey(sharesTable, prompt): """ Prompts for a device to be inserted and ensures that device matches some device associated with an encrypted sharefile by matching against the pubkeyfingerprint. Continues prompting until a yubikey is inserted that matches some entry in the shares manifest """ while True: # Read the pubkey fingerprint for the inserted device Crypto.promptDeviceInsertion(msg=prompt) ok, pkfp = Crypto.readPubkeyFingerprint() if not ok: raise RuntimeError("Failed to read pubkey fingerprint") # Find the right sharefile for this key # TODO: When we index shares by pubkey fingerprint this is # much simpler # if pkfp not in shareManifest["shares"]: for key, entry in sharesTable.items(): if entry["pubkeyFingerprint"] == pkfp: return entry["coeff"], entry["encryptedShareFile"] print("This device doesn't match any shares")
def get_therapydata(userName, templateName, resultDate): data = "" query = Therapy.all() cipher_text = Crypto.encrypt(userName) query.filter('userName ='******'templateName = ',templateName).filter('resultDate',resultDate).fetch(limit=None) object = query.get() if object: data = { 'userName' : Crypto.decrypt(object.userName), 'templateName' : object.templateName, 'resultDate' : object.resultDate, 'version': object.version, 'resultRecall': Therapy.getData(object.resultRecall), 'resultTrace': Therapy.getData(object.resultTrace), 'resultTrack': Therapy.getData(object.resultTrack), 'resultRecreate': Therapy.getData(object.resultRecreate) } result = {'status': "success", 'message': "Found therapy data", 'data': data} else: result = {'status': "error", 'message': "Data is not found.", 'data': ""} return result
def exposed_gen_key(self, fid, chunk): cryptObj = Crypto(fid, 'ks') key = cryptObj.gen_key(chunk) if keymenu.push(fid, key): return key else: return None
def recover(self, bundleDir=DEFAULT_BUNDLE_DIR): """ Recover a secret from a bundle of encrypted shares. """ # Load the manifest files. shareManifest = ShareManifest.load(bundleDir) deviceManifest = DeviceManifest.load(bundleDir) # TODO: Verify the shareManifest contain the expected contents: k, n, etc shares = {} shareMatcher = identifyShares( sharesTable=shareManifest.shares, k=shareManifest.k) # Process k Yubikeys that match share files for coeff, sharefile, pkfp in shareMatcher: # Find the device so we can get it's PIN for decryption device = deviceManifest.findDevice(pubkeyFingerprint=pkfp) exitOnFail(device is not None, msg=f"Failed to find device in manifest file with " "pubkeyFingerprint={pkfp}") # Decrypt the sharenand store the result ok, result = Crypto.decrypt( ctxtfile=f"{bundleDir}/{sharefile}", pin=device["operationsPin"]) exitOnFail(ok) shares[coeff] = result # Recover the secret print(Crypto.recoverSecret(shares))
def test_crypto1(self): a = "teststringshowingnumbersdontwork123789$%!#" c = Crypto("MANCHESTERBLUFF") b = c.encrypt(a) self.assertEqual(b, "FEFVZXJBRXTSIBNZGAWTFWKWUPYNBTDKXNTUJLBPVH") d = c.decrypt(b) self.assertEqual(d, "TESTSTRINGSHOWINGNUMBERSDONTWORKKLMQRSXYUW")
def test_crypto2(self): a = "ATTACKATDAWN" c = Crypto("MANCHESTERBLUFF") b = c.encrypt(a) self.assertEqual(b, "MTGCJOSMHRXY") d = c.decrypt(b) self.assertEqual(d, "ATTACKATDAWN")
def test_cbc_using_ecb(self): """Challenge 10""" cipher = base64.b64decode(open("data/10.txt").read()) key = "YELLOW SUBMARINE" text = Crypto.decrypt_cbc_using_ecb(cipher, key) self.assertEqual(open('data/plaintext.txt').read(), text) self.assertEquals(cipher, Crypto.encrypt_cbc_using_ecb(text, key))
def __init__(self, signal): """ Default constructor """ self.signal = signal self.state = 0 self.file = None self.file_name = None self.file_path = None self.storage_dir = storage_dir self.last_pos = 0 self.new_key = False self.buffer = '' self.peername = '' self.symetric_ciphers = ['ChaCha20', 'AES', '3DES'] self.cipher_modes = ['CBC', 'ECB', 'GCM'] self.digest = ['SHA384', 'SHA256', 'SHA512', 'MD5', 'BLAKE2'] self.choosen_cipher = None self.choosen_mode = None self.choosen_digest = None self.crypto = Crypto(self.choosen_cipher, self.choosen_mode, self.choosen_digest) self.encrypted_data = '' self.decrypted_data = []
def test_detect_aes_ecb_cipher(self): """Challenge 8""" ciphers = Crypto.get_lines("data/8.txt") num_detected = 0 for cipher in ciphers: if Crypto.is_aes_ecb_cipher(binascii.unhexlify(cipher)): num_detected += 1 self.assertEqual(1, num_detected)
def test_break_if_iv_is_same_as_key(self): """Challenge 27""" key = Crypto.gen_random_key(16) iv = key oracle = lambda c: Crypto.decrypt_aes(c, key, AES.MODE_CBC, iv) cipher = Crypto.encrypt_aes("X"*48, key, AES.MODE_CBC, iv) self.assertEquals(key, Crypto.extract_key_if_key_is_same_as_key(cipher, oracle))
def has_admin(cipher): """Checks if cipher has admin.""" counter = Crypto.gen_aes_stream_counter_mt19973(3453243) text = Crypto.decrypt_aes(cipher, key, AES.MODE_CTR, counter=counter) return text.find(';admin=true;') != -1
def test_break_if_iv_is_same_as_key(self): """Challenge 27""" key = Crypto.gen_random_key(16) iv = key oracle = lambda c: Crypto.decrypt_aes(c, key, AES.MODE_CBC, iv) cipher = Crypto.encrypt_aes("X" * 48, key, AES.MODE_CBC, iv) self.assertEquals( key, Crypto.extract_key_if_key_is_same_as_key(cipher, oracle))
def test_aes_ecb_decryption(self): """Challenge 12""" data = Crypto.get_lines('data/12.txt')[0] target = base64.b64decode(data) quote = lambda text: text oracle, _, _ = Crypto.generate_aes_oracle('', target, AES.MODE_ECB, quote) text = Crypto.decrypts_aes_ecb_byte_wise(oracle) self.assertEqual(target, text)
def test_break_rng_stream_cipher(self): """Challenge 24""" seed_str = Crypto.gen_random_key(2) seed = ord(seed_str[0]) << 8 | ord(seed_str[1]) mt_cipher = MT19937Cipher(seed) prefix = Crypto.gen_random_key(23) text = 'A' * 14 cipher = mt_cipher.encrypt(prefix + text) self.assertEquals(seed, Crypto.break_rng_stream_cipher(cipher, text))
def edit(cipher, offset, newtext): counter = Crypto.gen_aes_stream_counter_mt19973(seed) text = Crypto.decrypt_aes(cipher, key, AES.MODE_CTR, counter=counter) text = text[:offset] + newtext + text[offset + 1:] counter = Crypto.gen_aes_stream_counter_mt19973(seed) return Crypto.encrypt_aes(text, key, AES.MODE_CTR, counter=counter)
def edit_fast(cipher, newtext): counter = Crypto.gen_aes_stream_counter_mt19973(seed) text = Crypto.decrypt_aes(cipher, key, AES.MODE_CTR, counter=counter) text = newtext counter = Crypto.gen_aes_stream_counter_mt19973(seed) return Crypto.encrypt_aes(text, key, AES.MODE_CTR, counter=counter)
def test_break_rng_stream_cipher(self): """Challenge 24""" seed_str = Crypto.gen_random_key(2) seed = ord(seed_str[0]) << 8 | ord(seed_str[1]) mt_cipher = MT19937Cipher(seed) prefix = Crypto.gen_random_key(23) text = 'A'*14 cipher = mt_cipher.encrypt(prefix + text) self.assertEquals(seed, Crypto.break_rng_stream_cipher(cipher, text))
def __init__(self, data, media_source, key=None): self.data = data.encode('utf-8') # Absolute path in Media Source self.media_source = media_source self.key = key # Size of key is 128-bit self.crypto = Crypto(self.key) if self.key == None: self.key = self.crypto.getKey()
def readtext(self): img = Image.open(str(self.img_obj)) passwd = self.read_text.text() steg = steganography.Steganography(img) msg = steg.decode_image() decr = Crypto(passwd, enc_msg=msg) end_msg = decr.decrypt() self.inserted_text.setText(end_msg)
def __init__(self, backup_path: str, restore_path: str, password: str): self.backup_path = backup_path self.restore_path = restore_path pathlib.Path(restore_path).mkdir( parents=True, exist_ok=True) # create restore directory self.tempfile = tempfile.TemporaryDirectory() self.crypto = Crypto(password)
def post(self): """ Registration form to register a new user Login form to sign in to the website. Logout form to logout from the website. Also does the validation of all fields during registration Once logged in, redirects to Main Page. """ self.uname = str(self.request.get("username")) self.pwd = str(self.request.get("password")) if self.uname and self.uname != "": # If user name is provided and defined, encrypts it for checking/writing to database # Also uses it for cookie to retrieve user data # Encryption is needed for security self.encrypted_uname = Crypto.encrypto_wo_salt(self.uname) else: self.encrypted_uname = None if self.request.get("signup"): self.disname = str(self.request.get("dispname")) self.verify = str(self.request.get("verify")) self.email = str(self.request.get("email")) self.errors = validate_signupform( uname=self.uname, pwd=self.pwd, disname=self.disname, verify=self.verify, email=self.email ) if self.errors: self.render("signup.html", username=self.uname, email=self.email, **self.errors) else: # once validation goes through, a new entity is created in Users Kind with # encrypted username and salt encrypted password (hashlib and hmac alogorithms # used) Users.register_newuser( disname=self.disname, usrname=self.encrypted_uname, pwd=Crypto.encrypto(self.pwd), email=self.email ) self.response.headers.add_header( "Set-Cookie", "user_id = {username}".format(username=self.encrypted_uname) ) # providing 1 seconds for datastore to get updated time.sleep(DATASTORE_LATENCY) self.redirect("/mainpage") elif self.request.get("login"): # validates if user login and password are correct, if authenticated, sets cookie # and redirects to Welcome Page errors = validate_loginform(uname=self.encrypted_uname, pwd=self.pwd) if errors: self.render("signup.html", username=self.uname, **errors) else: self.response.headers.add_header( "Set-Cookie", "user_id = {username}".format(username=self.encrypted_uname) ) self.redirect("/mainpage") elif self.request.get("logout"): # Logs out, unset the cookie and re-direct to SingUp Page self.response.headers.add_header("Set-Cookie", "user_id = {username}".format(username="")) self.redirect("/signup")
def test_break_aes_ctr_fixed_nonce2(self): """Challenge 20""" block_size = 16 quote = lambda t: t counter = lambda: chr(25) * block_size aes_ctr, _ = Crypto.generate_aes_oracle('', '', AES.MODE_CTR, quote, block_size, counter) texts = [base64.b64decode(l) for l in open('data/20.txt').readlines()] ciphers = [aes_ctr(text) for text in texts] expected = FrequencyAnalyzer.get_repeating_xor(ciphers[0], texts[0])[:block_size] actual = Crypto.break_aes_ctr_with_fixed_nonce(ciphers, block_size) self.assertEquals(expected, actual)
def test_prefix_aes_ecb_decryption(self): """Challenge 14""" prefix = Crypto.gen_random_key(18) target = "This is the target" quote = lambda text: text oracle, _, _ = Crypto.generate_aes_oracle(prefix, target, AES.MODE_ECB, quote) self.assertEqual(target, Crypto.decrypts_aes_ecb_byte_wise(oracle)) target = "A" * 16 oracle, _, _ = Crypto.generate_aes_oracle(prefix, target, AES.MODE_ECB, quote) self.assertEqual(target, Crypto.decrypts_aes_ecb_byte_wise(oracle))
def test_cbc_bit_flipping(self): """Challenge 16""" prefix = "comment1=cooking%20MCs;userdata=" suffix = ";comment2=%20like%20a%20pound%20of%20bacon" oracle, key, _ = Crypto.generate_aes_oracle(prefix, suffix, AES.MODE_CBC, urllib.quote) def has_admin(cipher): """Checks if cipher has admin.""" text = Crypto.decrypt_aes(cipher, key, AES.MODE_CBC) return text.find(';admin=true;') != -1 self.assertTrue(Crypto.flip_cipher_to_add_admin(oracle, has_admin))
def test_break_aes_ctr_fixed_nonce2(self): """Challenge 20""" block_size = 16 quote = lambda t: t counter = lambda: chr(25)*block_size aes_ctr, _ = Crypto.generate_aes_oracle( '', '', AES.MODE_CTR, quote, block_size, counter) texts = [base64.b64decode(l) for l in open('data/20.txt').readlines()] ciphers = [aes_ctr(text) for text in texts] expected = FrequencyAnalyzer.get_repeating_xor( ciphers[0], texts[0])[:block_size] actual = Crypto.break_aes_ctr_with_fixed_nonce(ciphers, block_size) self.assertEquals(expected, actual)
def test_ctr_bit_flipping(self): """Challenge 26""" prefix = "comment1=cooking%20MCs;userdata=" suffix = ";comment2=%20like%20a%20pound%20of%20bacon" counter = Crypto.gen_aes_stream_counter_mt19973(3453243); oracle, key = Crypto.generate_aes_oracle( prefix, suffix, AES.MODE_CTR, urllib.quote, 16, counter=counter) def has_admin(cipher): """Checks if cipher has admin.""" counter = Crypto.gen_aes_stream_counter_mt19973(3453243); text = Crypto.decrypt_aes(cipher, key, AES.MODE_CTR, counter=counter) return text.find(';admin=true;') != -1 self.assertTrue(Crypto.flip_cipher_to_add_admin_ctr(oracle, has_admin))
def test_hex_to_base64(self): """Challenge 1""" expected, hex_str = Crypto.get_lines('data/1.txt') ascii_str = binascii.unhexlify(hex_str) # b2a_base64 appends a new line to result actual = binascii.b2a_base64(ascii_str)[:-1] self.assertEqual(expected, actual)
def get_entities(self): entities = [] data = { 'version':"", 'userName' : "", 'templateName' : "", 'resultDate' : "", 'resultRecall': "", 'resultTrace': "", 'resultTrack': "", 'resultRecreate': "" } try: objects = Therapy.all().order('userName').fetch(limit=None) if objects: for object in objects: data = { 'version': object.version, 'userName' : Crypto.decrypt(object.userName), 'templateName' : object.templateName, 'resultDate' : object.resultDate, 'resultRecall': Therapy.getData(object.resultRecall), 'resultTrace': Therapy.getData(object.resultTrace), 'resultTrack': Therapy.getData(object.resultTrack), 'resultRecreate': Therapy.getData(object.resultRecreate) } entities.append(data) except: result = {'status': "error", 'message': "Therapy data is not available" } return entities
def post(self): """ Gets title and concept from the form Validates all the fields, if there are no errors, adds to content to Concepts Kind """ ADMIN = [Crypto.encrypto_wo_salt("cranticumar")] if self.get_current_user().username in ADMIN: title = self.request.get("title") concept = self.request.get("concept") if title == "" or concept == "": # If there are errors, renders it back with errors self.render("addcontent.html", error="Please add both title and Concept", contentadd=True) else: # gets the current last/recently added concept (concept with last field set to True) prnt = Concepts.query(Concepts.last == True).get() if not prnt is None: # create an entity with last field set to true and parent field set to recently added entity's key tmp = Concepts(concept=generate_htmlstring(title, concept), title=title, parent=prnt.key, last=True) # as there can be only one recently added concept, setting previous last concept entity last field to False prnt.last = False # committing the preivous recently/last added concept changes prnt.put() else: # If this is the first time concept being added, entity creation happens without parent field tmp = Concepts(concept=generate_htmlstring(title, concept), title=title, last=True) # Commiting post to datastore tmp.put() self.redirect("/addcontent") else: self.render("addcontent.html", error="You are not admin to post the content", contentadd=True)
def test_break_single_byte_xor(self): """Challenge 3""" expected = "Cooking MC's like a pound of bacon" hex_str = Crypto.get_lines('data/3.txt')[0] cipher = binascii.unhexlify(hex_str) text, _ = FrequencyAnalyzer.break_single_byte_xor(cipher) self.assertEqual(expected, text)
def test_break_aes_padding_leak(self): """Challenge 17""" quote = lambda text: text _, key, init_vector = Crypto.generate_aes_oracle( '', '', AES.MODE_CBC, quote) def has_valid_padding(cipher, init_vector): """Checks if cipher has valid padding.""" try: Crypto.decrypt_aes(cipher, key, AES.MODE_CBC, init_vector) except ValueError: return False return True lines = [base64.b64decode(l) for l in open('data/17.txt').readlines()] for line in lines: cipher = Crypto.encrypt_aes(line, key, AES.MODE_CBC, init_vector) self.assertEqual(line, Crypto.break_aes_using_padding_leak( cipher, init_vector, has_valid_padding))
def update(userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate): query = Therapy.all() query.filter('userName ='******'templateName = ',templateName).filter('resultDate',resultDate).fetch(limit=None) object = query.get() if object: if object.resultRecall == resultRecall and object.resultTrace == resultTrace and object.resultTrack == resultTrack and object.resultRecreate == resultRecreate: return else: object.version = object.version + 1 Therapy.add_version(object.version, userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate)
def test_mt19937_seed(self): """Challenge 22""" num = Crypto.gen_random_number() timenow = int(time()) found = False for seed in range(timenow-1000, timenow): if MT19937RNG(seed).next() == num: found = True break self.assertTrue(found)
def receive_raw_data(self, print_progress): # get size of incoming data data_size = int(self._receive_data_by_protocol()) # get data data = "" progress_percent = 0 while len(data) < data_size: data += self._receive_data_by_protocol(buffer_size=consts.MAX_SENT_DATA_SIZE) if progress_percent: # print progress of data transfer progress_percent = self._print_transmission_progress_percent(data_size, len(data), progress_percent) return Crypto.decrypt_data(data)
def test_md4_length_extension(self): """Challenge 30""" orig_message = 'comment1=cooking%20MCs;userdata=foo;comment2=%20like' \ '%20a%20pound%20of%20bacon' # this is not known to attacker. key = Crypto.gen_random_key(43) suffix = ';admin=true;' orig_hash = md4(key + orig_message) forged_message = MD4Hash.pad(key + orig_message) + suffix forged_hash = md4(forged_message) validate = lambda h: h == forged_hash self.assertTrue(extend_md4(orig_hash, orig_message, suffix, validate))
def test_sha_length_extension(self): """Challenge 29""" orig_message = 'comment1=cooking%20MCs;userdata=foo;comment2=%20like' \ '%20a%20pound%20of%20bacon' # this is not known to attacker. key = Crypto.gen_random_key(100) suffix = ';admin=true;' orig_sha = sha1(key + orig_message) forged_message = Sha1Hash.pad(key + orig_message) + suffix forged_sha = sha1(forged_message) validate = lambda sha: sha == forged_sha self.assertTrue(extend_sha1(orig_sha, orig_message, suffix, validate))
def add_version(version, userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate): try: entity = Therapy( version=long(version), userName=Crypto.encrypt(userName), templateName=templateName, resultDate=resultDate, resultRecall=resultRecall, resultTrace=resultTrace, resultTrack=resultTrack, resultRecreate=resultRecreate) entity.put() except: result = {'status': "error", 'message': "Save of Therapy data is unsuccessful. Please try again."}
def send_raw_data(self, data, print_progress): data = Crypto.encrypt_data(data) data_size = len(data) # inform other side of incoming data size if not self._send_data_by_protocol(data_size): return False # data size failed # send data progress_percent = 0 for i in xrange(0, data_size, consts.MAX_SENT_DATA_SIZE): data_chunk = data[i: i + consts.MAX_SENT_DATA_SIZE] self._send_data_by_protocol(data_chunk) if print_progress: # print progress of data transfer sent_data_size = data_size if i + consts.MAX_SENT_DATA_SIZE > data_size else i + consts.MAX_SENT_DATA_SIZE # if all data has been sent.. progress_percent = self._print_transmission_progress_percent(data_size, sent_data_size, progress_percent) return True
def test_aes_ctr_encryption(self): """Challenge 18""" counter = Crypto.gen_aes_stream_counter_simple() key = "YELLOW SUBMARINE" cipher = base64.b64decode("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLX" +\ "zhPweyyMTJULu/6/kXX0KSvoOLSFQ==") text = "Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby " self.assertEqual(text, Crypto.decrypt_aes( cipher, key, AES.MODE_CTR, counter=counter)) # another test key = Crypto.gen_random_key(16) text = "Let there be light!" counter = Crypto.gen_aes_stream_counter_simple() cipher = Crypto.encrypt_aes(text, key, AES.MODE_CTR, counter=counter) counter = Crypto.gen_aes_stream_counter_simple() self.assertEqual(text, Crypto.decrypt_aes( cipher, key, AES.MODE_CTR, counter=counter))
def post(self): """ Handles forms with method post Fetches the user name and post and adds it to UserPosts Kind in datastore as an entity. """ if self.request.get("login"): self.uname = str(self.request.get("username")) self.pwd = str(self.request.get("password")) if self.uname and self.uname != "": # If user name is provided and defined, encrypts it for checking/writing to database # Also uses it for cookie to retrieve user data # Encryption is needed for security self.encrypted_uname = Crypto.encrypto_wo_salt(self.uname) errors = validate_loginform(uname=self.encrypted_uname, pwd=self.pwd) if errors: self.render("mainpage.html", username=self.uname, **errors) else: self.response.headers.add_header( "Set-Cookie", "user_id = {username}".format(username=self.encrypted_uname) ) self.redirect("/mainpage") if self.request.get("logout"): # unsets user_id cookie self.response.headers.add_header("Set-Cookie", "user_id = {username}".format(username="")) # redirects to mainpage self.redirect("/mainpage") if self.request.get("post"): self.usr = self.get_current_user() self.post = self.request.get("comment") if self.post and self.display_name: new_post = Posts(post=self.request.get("comment"), user=self.usr.dispname if self.usr else None) new_post.put() userposts.append(new_post) self.render("mainpage.html") else: self.render("mainpage.html", posterror="Null Comments are not allowed")
def add(userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate): result = {} try: if userName != "": #Check if the therapy data is new data isNew = True object = Therapy.get_therapydata(userName, templateName, resultDate) if object['data'] != "": isNew = False if isNew: version = 0 entity = Therapy( version=long(version), userName=Crypto.encrypt(userName), templateName=templateName, resultDate=resultDate, resultRecall=resultRecall, resultTrace=resultTrace, resultTrack=resultTrack, resultRecreate=resultRecreate) entity.put() result={'status': "add successful", 'message': "Added new therapy data into Datastore: user name: " + userName + ", template name: " + templateName + ", result date: " + resultDate} else: Therapy.update(userName, templateName, resultDate, resultRecall, resultTrace, resultTrack, resultRecreate) result={'status': "update successful", 'message': "Updated therapy data for user name: " + userName + ", template name: " + templateName + ", result date: " + resultDate} else: result = {'status': "error", 'message': "Please provide user name."} except: result = {'status': "error", 'message': "Save of Therapy data is unsuccessful. Please try again."} return result
def validate_signupform(**kw): """ Validates sign up form while registration for correctness of the details """ errors = dict() password_elist = list() if not (kw.get("uname") and re.match("^[a-z0-9_\.]{5,20}$", kw.get("uname"))): errors["error_username"] = "******" elif Users.get_by_username(Crypto.encrypto_wo_salt(kw.get("uname"))): # If username (each username has its own encrypted version) already exists in database, # this sets an error errors["error_username"] = "******" if not (kw.get("disname") and re.match("^[a-zA-Z]{3,20}$", kw.get("disname"))): errors["error_dispname"] = "That is an invalid name" if not (kw.get("pwd") and re.match("^.{5,10}$", kw.get("pwd"))): password_elist.append("Character Limit of 5 (min) - 10 (max)") if not (re.match(".*[a-z].*", kw.get("pwd"))): password_elist.append("Password must contain atleast 1 small alphabet") if not (re.match(".*[A-Z].*", kw.get("pwd"))): password_elist.append("Password must contain atleast 1 Capital Letter") if not (re.match(".*[0-9].*", kw.get("pwd"))): password_elist.append("Password must contain atleast 1 number") if password_elist: errors["error_password"] = password_elist if not (kw.get("verify") and kw.get("verify") == kw.get("pwd")): errors["error_verify"] = "Passwords did not match" if kw.get("email"): if not re.match("^[\S]+@[\S]+\.[\S]+$", kw.get("email")): errors["error_email"] = "Not a valid email address" return errors
def login(cls, usrname, pwd): # helps validating if user entity already exists usr = cls.get_by_username(usrname) if usr and Crypto.decrypto(pwd, usr.password): return usr
def test_aes_decryption_ecb_mode(self): """Challenge 7""" cipher = base64.b64decode(open("data/7.txt").read()) key = 'YELLOW SUBMARINE' text = Crypto.decrypt_aes(cipher, key, AES.MODE_ECB) self.assertEqual(open('data/plaintext.txt').read(), text)
def test_break_repeating_xor(self): """Challenge 6""" cipher = base64.b64decode(open("data/6.txt").read()) text, key = Crypto.break_repeating_xor(cipher) self.assertEqual("Terminator X: Bring the noise", key) self.assertEqual(open('data/plaintext.txt').read(), text)