def receive_key_from_alice(self): message = self.other_user_connection.get_message() if message != '': # decrypt the message decrypted_message = otos(decrypt(stoo(message), self._key, 38), 38) session_key = stoo(decrypted_message[:2]) alice_id = stoo(decrypted_message[2:7]) timestamp = decrypted_message[7:33] # quit if the message from Alice is not right if timestamp in self.timestamps or alice_id != self.other_user_id: return False self.timestamps.add(timestamp) return session_key
def parallel_crack(id, key_gen, ciphertext, range_size): print(f'Starting up worker {id}') best = '' best_score = -10000.0 best_key = None for key in tqdm(key_gen, total=range_size, position=id + 1): decrypted = utils.bytes_to_ascii(des.decrypt(ciphertext, key)) score = score_plaintext_logprob(decrypted) if score > best_score: best = decrypted best_score = score best_key = key # if (i % 10000) == 0: # print(f'worker {id} has tried {i} keys') print('Decrypted: ', best, best_score, best_key.hex())
def respond_to_test_message(self, session_key): message = self.other_user_connection.get_message() if message != '': # decrypt message decrypted_message = otos(decrypt(stoo(message), session_key)) # use the confirmation function hashed_message = User.confirm(decrypted_message) # encrypt hashed result encrypted_message = otos(encrypt(stoo(hashed_message), session_key)) # send the encrypted message to bob self.other_user_connection.send_message(encrypted_message) return True
def crack(): """ 滑块验证 :return: """ while True: _init_data = _init_slider() if _init_data: break time.sleep(random.random()) print('滑块初始化成功! ') fg_url = _init_data['slider_url'] bg_url = _init_data['captcha_url'] download_cap(fg_url, 'fg.png') download_cap(bg_url, 'bg.png') distance_all = _get_distance(fg=_init_data['slider_url'], bg=_init_data['captcha_url']) distance = int(distance_all / 1.5) print('原始值: {}, distance: {}'.format(distance_all, distance)) if not distance: return {'success': 0, 'message': '缺口距离获取失败! ', 'data': None} start_time = int(time.time() * 1000) time.sleep(random.uniform(0.01, 0.05)) trace = _generate_trace(distance, start_time) running_time = int(time.time() * 1000) - start_time # 旧方法 # new_key, act = _encrypt_trace(_init_data['k'], trace, distance) k = _init_data['k'] rid = _init_data['rid'] # 对 k 值进行 base64 解码 text = base64.b64decode(k) # 对解码后的 k 值进行 DES 解密(密钥: sshummei), 取前8位作为下一次加密的密钥 new_key = decrypt('sshummei', text)[:8] result = _slider_verify(new_key, trace, rid, running_time, distance) if result['riskLevel'] == 'PASS': return {'success': 1, 'message': '校验成功! ', 'data': rid} return {'success': 0, 'message': '校验失败! ', 'data': None}
def main(): parser = create_parser() args = parser.parse_args(sys.argv[1:]) output_file_name = args.input_file + ('.dec' if args.decrypt else '.enc') input_file = open(args.input_file, 'rb') output_file = open(output_file_name, 'wb') outputbytes = b'' if args.decrypt: outputbytes = des.decrypt(input_file.read()) else: outputbytes = des.encrypt(input_file.read()) output_file.write(outputbytes) input_file.close() output_file.close()
def exec_menu(choice): if choice == "1": key = [] print("Prosze wprowadzic nazwe pliku z kluczem - kazdy bajt klucza podaj w osobnej linii...") key_file_name = input(" >> ") print("Prosze wprowadzic nazwe pliku z tekstem...") msg_file_name = input(" >> ") with open(key_file_name, 'r') as key_file: key = [int(line.strip()) for line in key_file] with open(msg_file_name, 'r') as msg_file: msg = msg_file.read().replace('\n', ' ') print("Zaszyfrowany tekst w postaci bajtow zapisano w pliku encrypted.txt.") encrypted = encrypt(key, msg) with open('encrypted.txt', 'w') as output_file: for byte in encrypted: output_file.write("%s\n" % byte) main_menu() if choice == "2": key = [] print("Prosze wprowadzic nazwe pliku z kluczem - kazdy bajt klucza podaj w osobnej linii...") key_file_name = input(" >> ") print("Prosze wprowadzic nazwe pliku z zaszyfrowanymi bajtami...") msg_file_name = input(" >> ") with open(key_file_name, 'r') as key_file: key = [int(line.strip()) for line in key_file] with open(msg_file_name, 'r') as msg_file: msg = [int(line.strip()) for line in msg_file] print("Odszyfrowany tekst zapisano w pliku decrypted.txt.") encrypted = decrypt(key, msg) with open('decrypted.txt', 'w') as output_file: for byte in encrypted: output_file.write("%s" % byte) main_menu() if choice == "3": unit_tests.unittest.main() if choice == "0": return
def receive_key_from_kdc(self, nonce): message = self.kdc_connection.get_message() if message != '': # decrypt the message decrypted_message = otos(decrypt(stoo(message), self._key, 76), 76) # get the session key, bob_id, timestamp, nonce, and encrypted_b_message session_key = stoo(decrypted_message[:2]) bob_id = stoo(decrypted_message[2:7]) timestamp = decrypted_message[7:33] received_nonce = decrypted_message[33:38] encrypted_b_message = decrypted_message[38:] # quit if the message from the kdc is not right if timestamp in self.timestamps or bob_id != self.other_user_id or nonce != received_nonce: return False self.timestamps.add(timestamp) # send the encrypted_b_message self.other_user_connection.send_message(encrypted_b_message) return session_key
def handleLogin(self): if self.textPass.text() == des.decrypt(): self.accept() else: QMessageBox.warning(self, 'Error', 'Niepoprawne hasło')
def test_decrypt(self): for key, plain, cipher in self._test_vectors: self.assertEqual(des.decrypt(key, cipher), plain)
def testBasicEN_FIXEDKEY(self): key = [0, 252, 132, 99, 12, 3, 17, 5] plaintext = "Python is an interpreted, high-level, general-purpose programming language. " \ "It was created by Guido van Rossum and first released in 1991." ciphertext = encrypt(key, plaintext) self.assertTrue(decrypt(key, ciphertext) == plaintext)
def test_decryption(self): plaintext = bytes.fromhex('0123456789ABCDEF') key = bytes.fromhex('133457799BBCDFF1') ciphertext = bytes.fromhex('85E813540F0AB405') assert(des.decrypt(ciphertext, key) == plaintext)
def test_decrypt_multiple_blocks_cbc(self): expected = STR * 2 actual = des.decrypt(des.encrypt(STR * 2, KEY, iv=IV), KEY, iv=IV) self.assertEqual(expected, actual)
def test_decrypt_multiple_blocks_ecb(self): expected = STR * 2 actual = des.decrypt(des.encrypt(STR * 2, KEY, 'ECB'), KEY, 'ECB') self.assertEqual(expected, actual)
if __name__ == '__main__': p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f a = 0x0 b = 0x7 n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 x = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 y = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 G = Point(a, b, p, n, x, y) d1, H1 = generate_keys(n, G) print(f"First private key: {d1:x}") print(f"First public key: (x={H1.x:x}, y={H1.y:x})") d2, H2 = generate_keys(n, G) print(f"Second private key: {d2:x}") print(f"Second public key: (x={H2.x:x}, y={H2.y:x})") S1 = H2 * d1 S2 = H1 * d2 print(f"Shared key: {S1.x:x}") with open("data.txt", 'r') as file: t = file.read() k = str(S1.x) print(f"Initial text: {t} ({des.str_to_hex(t)})") encrypted = des.encrypt(k, t) print(f"Encrypted text: {des.str_to_hex(encrypted)}") decrypted = des.decrypt(k, encrypted) print(f"Decrypted text: {decrypted} ({des.str_to_hex(decrypted)})")
import des des.encrypt("raven_hr.in", "key.key") des.decrypt("raven_hr.des", "key.key")
# ~~~~~ AES ~~~~~ with open(filename, 'rb') as f: data = f.read() encrypted, key, nonce, tag = aes.encrypt(data) with open(filename + '.aes', 'wb') as f: f.write(encrypted) decrypted = aes.decrypt(encrypted, key, nonce, tag) with open(filename + '.aes.decrypted', 'wb') as f: f.write(decrypted) # ~~~~~ 3DES ~~~~~ with open(filename, 'rb') as f: data = f.read() encrypted, key, nonce = des.encrypt(data) with open(filename + '.des', 'wb') as f: f.write(encrypted) decrypted = des.decrypt(encrypted, key, nonce) with open(filename + '.des.decrypted', 'wb') as f: f.write(decrypted)
parser.add_argument('mode', metavar='[encrypt|decrypt]', choices=['encrypt', 'decrypt']) parser.add_argument('INPUT_FILE', type=Path) parser.add_argument('OUTPUT_FILE') parser.add_argument('KEY_FILE') return parser.parse_args() if __name__ == "__main__": ARGS = parse_args() with open(ARGS.KEY_FILE, 'r') as f: key = bytes.fromhex(f.read()) if ARGS.mode == 'encrypt': # Read plaintext with open(ARGS.INPUT_FILE, 'r') as f: plaintext = f.read() ciphertext = des.encrypt(ascii_to_bytes(plaintext), key) # Save ciphertext as hex with open(ARGS.OUTPUT_FILE, 'w') as f: f.write(ciphertext.hex()) elif ARGS.mode == 'decrypt': with open(ARGS.INPUT_FILE, 'r') as f: ciphertext = bytes.fromhex(f.read()) plaintext = bytes_to_ascii(des.decrypt(ciphertext, key)) print(plaintext) with open(ARGS.OUTPUT_FILE, 'w') as f: f.write(plaintext)
def test_des(): des.enrcypt("0f0f0f0f0f0f0f0f", path["out"] + "/des-crypto.txt", path["reference"]["lorem"]) des.decrypt("0f0f0f0f0f0f0f0f", path["out"] + "/des-clear.txt", path["out"] + "/des-crypto.txt")
def test_decrypt_single_block_ecb(self): expected = STR actual = des.decrypt(des.encrypt(STR, KEY, 'ECB'), KEY, 'ECB') self.assertEqual(expected, actual)
import des des_msg = ["1111"] des_key = ["11111111" + "11111111" + "11111111" + "11100111" + "11110111" + "11111111" + "11111111" + "11111111"] print("Data: " + des_msg[0]) print("DES Key: " + des_key[0]) encrypt = des.encrypt(str(des_msg[0]), str(des_key[0])) print("DES Encrypted: " + encrypt) decrypt = des.decrypt(encrypt, str(des_key[0])) print("DES Decrypted: " + decrypt)
def test_decrypt_single_block_cbc(self): expected = STR actual = des.decrypt(des.encrypt(STR, KEY, iv=IV), KEY, iv=IV) self.assertEqual(expected, actual)
import tgs import server import des from struct import * import time my_id, my_key = as_server.register() print("CLIENT_ID: {}".format(my_id)) print("CLIENT_KEY: {}".format(my_key)) print("=" * 60) print("REQUET TO AS SERVER: client_id ({})".format(my_id)) ticket_enc = as_server.get_ticket(my_id) print("as_ticket X K_c: {}\n".format(ticket_enc)) ticket = des.decrypt(ticket_enc, my_key) print("as_ticket: {}\n".format(ticket)) TGT_enc_len = ticket[0] * 256 + ticket[1] TGT_enc = ticket[2:2 + TGT_enc_len] C_TGS, = unpack("Q", ticket[2 + TGT_enc_len:]) print("K_c_tgs: {}\n".format(C_TGS)) print("TGT x K_as_tgs: {}\n".format(TGT_enc)) tm = int(time.time()) print("now: ", tm) auth = pack("QQ", my_id, tm) print("AUTH: {}\n".format(auth))
def test_decrypt_and_unpad_cbc(self): LOCAL_STR = b'linus' expected = LOCAL_STR actual = des.decrypt(des.encrypt(LOCAL_STR, KEY, iv=IV), KEY, iv=IV) self.assertEqual(expected, actual)
send = cipher + " MAC = " + mac print("Sending the ciphertext:", send) s.send(send.encode()) print() # Recieve Response data = s.recv(1024).decode("utf-8") data_no_mac = data[:data.index("M") - 1] # print(data_no_mac) if quitFlag == False: print(data) if (select == "BLUM"): msg = enc.Blum_Gold_Decrypt(n, a, b, p, q, data) elif (select == "DES"): msg = DES.decrypt(data_no_mac, key) else: # 3 DES msg = DES.decrypt3(data_no_mac, key) # Look at MAC recieved from the BANK user_mac = enc.parse_mac(data) mac = HMAC.mac(msg, key) # Get Just the Message message = msg[:msg.index("-")] # Get the TimeStamp time_msg = int(msg[msg.index("-") + 1:]) # if user said 'Quit', don't print out any message verification stuff, just exit if quitFlag == True: break
def sym_decrypt(self, key, encrypted): plain = 0 if self.sym_key_alg == "des": plain = des.decrypt(key, encrypted) return plain
def test_decrypt(self): self.assertEqual(des.decrypt(self.cipher)[:64], self.plain)