def _handle_get_user_info(self, request_user_info, connection, user_info_msg): target_user_name, send_time = user_info_msg.split(SEPARATOR) if not self._check_timestamp(connection, send_time): return target_user_info = self._find_user_info_by_name(target_user_name) if target_user_info is not None: key_between_client = Utils.generate_symmetric_key() timestamp_to_expire = time.time() + 1000 ticket = request_user_info.user_name + SEPARATOR1 + \ key_between_client + SEPARATOR1 + \ str(timestamp_to_expire) ticket_signature = Crypto.sign(self.pri_key, ticket) target_pubkey = target_user_info.rsa_pub_key user_info_msg = UserInfoRes( target_user_info.ip, target_user_info.port, key_between_client, ticket, ticket_signature, Crypto.serialize_pub_key(target_pubkey)) self._send_sym_encrypted_msg_to_client(connection, request_user_info, user_info_msg) else: connection.sendall( Message.dumps( MessageType.RES_FOR_INVALID_REQ, 'The user <' + target_user_name + '> is offline!'))
def _handle_conn_start(self, conn_start_msg): ticket = conn_start_msg.ticket ticket_signature = conn_start_msg.ticket_signature if not Crypto.verify_signature(self.server_pub_key, ticket, ticket_signature): return src_user_name, sec_session_key, timestamp_to_expire = ticket.split( SEPARATOR1) if src_user_name != conn_start_msg.user_name or float( timestamp_to_expire) < time.time(): return src_user_info = UserInfo() src_user_info.address = (conn_start_msg.ip, conn_start_msg.port) src_user_info.pub_key = Crypto.deserialize_pub_key( conn_start_msg.pub_key) src_user_info.sec_key = sec_session_key src_user_info.info_known = True self.online_list[conn_start_msg.user_name] = src_user_info # send connection back message to the initiator c3_nonce = conn_start_msg.c3_nonce src_user_info.c4_nonce = Utils.generate_nonce() iv = Utils.generate_iv() conn_back_msg = ConnBackMsg( self.user_name, iv, Crypto.symmetric_encrypt(src_user_info.sec_key, iv, str(c3_nonce)), src_user_info.c4_nonce, time.time()) self._send_encrypted_msg_to_user(src_user_info, MessageType.CONN_USER_RES, conn_back_msg)
def client(public_key, private_key, info_pass): client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_sock.connect(('127.0.0.1', 53210)) client_sock.sendall(public_key.exportKey(format='PEM')) data = client_sock.recv(256) # Send session key session_key = Crypto.decrypt_message(data, private_key) # decrypt this key print(Crypto.encrypt_message_aes(info_pass, session_key, client_sock)) data = client_sock.recv(10000000) nonce = client_sock.recv(16) tag = client_sock.recv(16) photo = Crypto.decrypt_message_aes(data, tag, session_key, nonce) # rows это готовое фото data_2 = client_sock.recv(10000) # добавил nonce_2 = client_sock.recv(16) # добавил tag_2 = client_sock.recv(16) # добавил 05.06 hash = Crypto.decrypt_message_aes(data_2, tag_2, session_key, nonce_2) # hash client_sock.close() print('Received', photo) with open("D://project//Course_work//venv//Photo1.jpg", "wb") as f: f.write(photo) f.close() return photo, hash
def __init__(self, ip, port, pub_key_file): self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.recv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.client_sock = None # user name for this chat client self.user_name = None # chat server ip, port and public key self.server_ip = ip self.server_port = port self.server_pub_key = Crypto.load_public_key(pub_key_file) # generate rsa key pair self.rsa_pri_key, self.rsa_pub_key = Crypto.generate_rsa_key_pair() # generate dh key pair self.dh_pri_key, self.dh_pub_key = Crypto.generate_dh_key_pair() # shared dh key self.shared_dh_key = None # chat client ip and port, used to receive messages self.client_ip = Utils.get_local_ip() self.client_port = Utils.get_free_port() # online-users known to the chatclient self.online_list = dict() # start socket for receiving messages self._start_recv_sock() # start commandline interactive mode cmd.Cmd.__init__(self)
def _re_login(self): print 'Server broken down or reset, please try to re-login!' self.client_sock.close() self.user_name = None self.rsa_pri_key, self.rsa_pub_key = Crypto.generate_rsa_key_pair() self.dh_pri_key, self.dh_pub_key = Crypto.generate_dh_key_pair() self.shared_dh_key = None self.login()
def _send_text_msg(self, msg, receiver_info): iv = Utils.generate_iv() sec_key = receiver_info.sec_key text_msg = TextMsg( self.user_name, Crypto.asymmetric_encrypt(receiver_info.pub_key, iv), Crypto.symmetric_encrypt(sec_key, iv, msg), Crypto.sign(self.rsa_pri_key, msg), time.time()) self._send_encrypted_msg_to_user(receiver_info, MessageType.TEXT_MSG, text_msg)
def _handle_client_auth_end(self, client_address, data): user_info = self.login_users[client_address] iv, encrypted_c2_nonce = data.split(SEPARATOR) received_c2_nonce = Crypto.symmetric_decrypt( user_info.secret_key, Crypto.asymmetric_decrypt(self.pri_key, iv), encrypted_c2_nonce) if received_c2_nonce != str(user_info.temp_nonce): return False, 'The nonce encrypted with the session key is wrong!' auth_end_res_msg = str(long(received_c2_nonce) + 1) return True, auth_end_res_msg
def _send_sym_encrypted_msg_to_server(self, message_type, msg): send_time = time.time() iv = Utils.generate_iv() plain_msg = msg + SEPARATOR + str(send_time) encrypted_msg = Crypto.symmetric_encrypt(self.shared_dh_key, iv, plain_msg) final_msg = Message.dumps( message_type, Crypto.asymmetric_encrypt(self.server_pub_key, iv) + SEPARATOR + encrypted_msg) self.client_sock.sendall(final_msg)
def test_is_csr(self): private = Crypto.generate_private_key('testKey.pem') details = { 'country': 'Se', 'region': 'Skane', 'city': 'stockholm', 'org': 'someCo', 'hostname': 'somesite.com' } csr = Crypto.create_csr(private, details) self.assertIsInstance( csr, Crypto.x509.CertificateSigningRequest) # Is it a csr?
def test_imported_certificate(self): private = Crypto.generate_private_key('testKey.pem') details = { 'country': 'Se', 'region': 'Skane', 'city': 'stockholm', 'org': 'someCo', 'hostname': 'somesite.com' } cert = Crypto.generate_self_signed_cert(private, 'testSelfSigned.pem', details, 10) self.assertIsInstance(Crypto.import_certificate('testSelfSigned.pem'), Crypto.x509.Certificate)
def _auth_start(self, solved_challenge, user_name, password): c1_nonce = Utils.generate_nonce() msg = AuthStartMsg(user_name, password, Crypto.serialize_pub_key(self.rsa_pub_key), Crypto.serialize_pub_key(self.dh_pub_key), self.client_ip, self.client_port, c1_nonce) msg_str = Utils.serialize_obj(msg) encrypted_msg_str = Crypto.asymmetric_encrypt(self.server_pub_key, msg_str) full_msg = solved_challenge + SEPARATOR + encrypted_msg_str auth_start_msg = Message.dumps(MessageType.AUTH_START, full_msg) self.client_sock.sendall(auth_start_msg) auth_start_response = self.client_sock.recv(MAX_MSG_SIZE) return c1_nonce, auth_start_response
def _handle_auth_start_response(self, expected_c1_nonce, auth_start_response): tpe, data = Message.loads(auth_start_response) if tpe == MessageType.RES_FOR_INVALID_REQ: print data return False, None, None decrypted_auth_start_response = Crypto.asymmetric_decrypt( self.rsa_pri_key, data) res_obj = Utils.deserialize_obj(decrypted_auth_start_response) server_dh_key, c1_nonce, c2_nonce = res_obj.dh_pub_key, res_obj.c1_nonce, res_obj.c2_nonce if str(expected_c1_nonce) != str(c1_nonce): return False, None, None shared_dh_key = Crypto.generate_shared_dh_key( self.dh_pri_key, Crypto.deserialize_pub_key(server_dh_key)) return True, shared_dh_key, str(c2_nonce)
def _handle_text_msg(self, text_msg): user_name = text_msg.user_name if user_name in self.online_list and self.online_list[ user_name].connected: user_info = self.online_list[user_name] iv = Crypto.asymmetric_decrypt(self.rsa_pri_key, text_msg.iv) encrypted_msg = text_msg.encrypted_msg decrypted_msg = Crypto.symmetric_decrypt(user_info.sec_key, iv, encrypted_msg) msg_signature = text_msg.msg_signature if Crypto.verify_signature(user_info.pub_key, decrypted_msg, msg_signature): # print '\n' + MSG_PROMPT + '<From ' + ip + ':' + str(port) + ':' + user_name + ">: " + decrypted_msg print '\n' + user_name + MSG_PROMPT + decrypted_msg print self.user_name + CMD_PROMPT,
def _send_sym_encrypted_msg_to_client(connection, request_user_info, msg, include_timestamp=True): iv = Utils.generate_iv() if include_timestamp: msg.timestamp = time.time() msg = Utils.serialize_obj(msg) encrypted_res_message = Crypto.symmetric_encrypt( request_user_info.secret_key, iv, msg) send_res_msg = Message.dumps( MessageType.RES_FOR_VALID_REQ, Crypto.asymmetric_encrypt(request_user_info.rsa_pub_key, iv) + SEPARATOR + encrypted_res_message) connection.sendall(send_res_msg)
def _auth_end(self, c2_nonce): iv = Utils.generate_iv() encrypted_c2_nonce = Crypto.symmetric_encrypt(self.shared_dh_key, iv, c2_nonce) auth_end_msg = Message.dumps( MessageType.AUTH_END, Crypto.asymmetric_encrypt(self.server_pub_key, iv) + SEPARATOR + encrypted_c2_nonce) self.client_sock.sendall(auth_end_msg) validate_result, decrypted_nonce_response = self._recv_sym_encrypted_msg_from_server( False) if validate_result and long( decrypted_nonce_response) == long(c2_nonce) + 1: return True else: return False
def _handle_conn_end(self, conn_end_msg): user_info = self.online_list[conn_end_msg.user_name] decrypted_c4_nonce = Crypto.symmetric_decrypt( user_info.sec_key, conn_end_msg.iv, conn_end_msg.encrypted_c4_nonce) if str(user_info.c4_nonce) == str(decrypted_c4_nonce): user_info.connected = True
def _verify_password(self, user_name, password): if user_name not in self.all_users: return False salt, pwd_hash = self.all_users[user_name] if Crypto.generate_hash(password, salt) != pwd_hash: return False return True
def test_is_self_signed_certificate(self): private = Crypto.generate_private_key('testKey.pem') details = { 'country': 'Se', 'region': 'Skane', 'city': 'stockholm', 'org': 'someCo', 'hostname': 'somesite.com' } cert = Crypto.generate_self_signed_cert(private, 'testSelfSigned.pem', details, 10) self.assertIsInstance(cert, Crypto.x509.Certificate) # Is it a certificate? self.assertGreater( Crypto.datetime.utcnow() + Crypto.timedelta(days=10), cert.not_valid_before ) # Is validity expires after the creation plus 10 days?
def _recv_sym_encrypted_msg_from_server(self, validate_timestamp=True): encrypted_server_response = self.client_sock.recv(MAX_MSG_SIZE) tpe, data = Message.loads(encrypted_server_response) if tpe == MessageType.RES_FOR_INVALID_REQ: print data return False, data else: iv, encrypted_response_without_iv = data.split(SEPARATOR) decrypted_response = Crypto.symmetric_decrypt( self.shared_dh_key, Crypto.asymmetric_decrypt(self.rsa_pri_key, iv), encrypted_response_without_iv) if validate_timestamp: decrypted_response = Utils.deserialize_obj(decrypted_response) if not Utils.validate_timestamp(decrypted_response.timestamp): return False, None return True, decrypted_response
def _handle_conn_back(self, conn_back_msg): user_info = self.online_list[conn_back_msg.user_name] decrypted_c3_nonce = Crypto.symmetric_decrypt( user_info.sec_key, conn_back_msg.iv, conn_back_msg.encrypted_c3_nonce) if str(decrypted_c3_nonce) == str(user_info.c3_nonce): # print 'Successfully connected to the user <' + conn_back_msg.user_name + '>' user_info.connected = True iv = Utils.generate_iv() conn_end_msg = ConnEndMsg( self.user_name, iv, Crypto.symmetric_encrypt(user_info.sec_key, iv, str(conn_back_msg.c4_nonce)), time.time()) self._send_encrypted_msg_to_user(user_info, MessageType.CONN_USER_END, conn_end_msg)
def __init__(self): self.IF_CLIENT_NOT_CONNECTED = True self.ServerSocket = socket.socket() self.client_keys = {} self.client_Ips = {} self.crypto = Crypto() # self.f = open(r'\\.\pipe\myPipee', 'r+b', 0) self.GUISocket = socket.socket()
def __init__(self, host, port, private_key_file, users_info_file): self.host = host self.port = port self.pri_key = Crypto.load_private_key(private_key_file) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.all_users = self._load_users_info(users_info_file) self.login_users = dict()
def test_signature_of_certificate(self): private = Crypto.generate_private_key('testKey.pem') details = { 'country': 'Se', 'region': 'Skane', 'city': 'stockholm', 'org': 'someCo', 'hostname': 'somesite.com' } cert = Crypto.generate_self_signed_cert(private, 'testSelfSigned.pem', details, 10) try: private.public_key().verify(cert.signature, cert.tbs_certificate_bytes, Crypto.padding.PKCS1v15(), Crypto.hashes.SHA256()) except Crypto.cryptography.exceptions.InvalidSignature: self.fail('Verification of signature failed')
def solve_challenge(trunc_challenge, challenge_hash): trunc_challenge = long(trunc_challenge) guessed_challenge = trunc_challenge n = 0 while len(str(guessed_challenge)) <= 40: guessed_challenge = str(trunc_challenge + (n << 112)) if Crypto.generate_hash(guessed_challenge) == challenge_hash: return guessed_challenge n += 1
def totient(): number = int(raw_input("What number do you want the totient of: ")) factors = Crypto.factorize(number) sum=1.0 for i in factors: sum*= 1-fractions.Fraction(1,i) print(int(sum*number)) print('') print('')
def test_sign_csr(self): private = Crypto.generate_private_key('testKey.pem') details = { 'country': 'Se', 'region': 'Skane', 'city': 'stockholm', 'org': 'someCo', 'hostname': 'somesite.com' } cert = Crypto.generate_self_signed_cert(private, 'testSelfSigned.pem', details, 10) csr = Crypto.create_csr(private, details) signed_csr = Crypto.sign_csr(csr, cert, private, 10) # This should be a certificate now since it is signed. self.assertIsInstance(signed_csr, Crypto.x509.Certificate) # And not CSR anymore... self.assertNotIsInstance(signed_csr, Crypto.x509.CertificateSigningRequest)
def _connect_to_user(self, target_user_info): # start authentication process target_user_info.c3_nonce = Utils.generate_nonce() msg = ConnStartMsg(self.user_name, self.client_ip, self.client_port, Crypto.serialize_pub_key(self.rsa_pub_key), target_user_info.ticket, target_user_info.ticket_signature, target_user_info.c3_nonce, time.time()) self._send_encrypted_msg_to_user(target_user_info, MessageType.CONN_USER_START, msg)
def decryptRSAPrimes(): n = int(raw_input("What is your n: ")) factors = Crypto.factorize(n) p=factors[0] q=factors[1] totient = (p-1)*(q-1) e = int(raw_input("what is your e value: ")) d = Crypto.modinv(e,totient) message = [] count = int(raw_input("How many numbers in your message: ")) for i in range(0,count): message.append(int(raw_input("What is the next number: "))) print('') decrypt='' for i in message: decrypt += chr((i**d%n)) print(decrypt)
def test_signature_on_signed_csr(self): # Generate the first set of key. CA_private = Crypto.generate_private_key('testKey.pem') details = { 'country': 'Se', 'region': 'Skane', 'city': 'stockholm', 'org': 'someCo', 'hostname': 'somesite.com' } CA_cert = Crypto.generate_self_signed_cert(CA_private, 'testSelfSigned.pem', details, 10) # Generate the second set of keys private = Crypto.generate_private_key('testKey.pem') details = { 'country': 'Se', 'region': 'Skane', 'city': 'stockholm', 'org': 'someCo', 'hostname': 'somesite.com' } # Create and sign csr with the first key. csr = Crypto.create_csr(private, details) signed_csr = Crypto.sign_csr(csr, CA_cert, CA_private, 10) # Now signed csr is certificate but not the same cert. self.assertNotEqual(signed_csr.serial_number, CA_cert.serial_number) # Now verify the signature try: CA_private.public_key().verify(signed_csr.signature, signed_csr.tbs_certificate_bytes, Crypto.padding.PKCS1v15(), Crypto.hashes.SHA256()) except Crypto.cryptography.exceptions.InvalidSignature: self.fail('Verification of signature failed')
def _get_user_info(self, user_name): self._send_sym_encrypted_msg_to_server(MessageType.GET_USER_INFO, user_name) validate_result, user_info_obj = self._recv_sym_encrypted_msg_from_server( ) if validate_result: # print target_address user_info = self.online_list[user_name] user_info.address = (user_info_obj.ip, user_info_obj.port) user_info.sec_key = user_info_obj.sec_key user_info.pub_key = Crypto.deserialize_pub_key( user_info_obj.pub_key) user_info.ticket = user_info_obj.ticket user_info.ticket_signature = user_info_obj.ticket_signature user_info.info_known = True
def decryptRSA(): p = int(raw_input("What is your first prime: ")) q = int(raw_input("What is your second prime: ")) n = p*q totient = (p-1)*(q-1) e = int(raw_input("what is your e value: ")) d = Crypto.modinv(e,totient) message = [] count = int(raw_input("How many numbers in your message: ")) for i in range(0,count): message.append(int(raw_input("What is the next number: "))) print('') decrypt='' for i in message: decrypt += chr(i**d%n) print(decrypt)
def _handle_client_auth_start(self, client_address, data): challenge = Utils.substring_before(data, SEPARATOR) auth_start_msg = Crypto.asymmetric_decrypt( self.pri_key, Utils.substring_after(data, SEPARATOR)) auth_start_msg_obj = Utils.deserialize_obj(auth_start_msg) # if the challenge solution is wrong, return false directly if challenge != self.login_users[client_address].challenge: return False, 'Answer to the given challenge is wrong!' user_name = auth_start_msg_obj.user_name # the same user cannot login twice user_info = self._find_user_info_by_name(user_name) if user_info is not None and user_info.state == UserState.AUTHENTICATED: return False, 'The user has already logged in, please retry with another user!' # if the provided password is wrong password = auth_start_msg_obj.password if not self._verify_password(user_name, password): return False, 'The user name or password is wrong, please retry!' # set user information user_info_obj = self.login_users[client_address] user_info_obj.user_name = auth_start_msg_obj.user_name user_info_obj.ip = auth_start_msg_obj.ip user_info_obj.port = int(auth_start_msg_obj.port) user_info_obj.rsa_pub_key = Crypto.deserialize_pub_key( auth_start_msg_obj.rsa_pub_key) user_info_obj.state = UserState.VERIFIED # DH key exchange user_dh_pub_key = Crypto.deserialize_pub_key( auth_start_msg_obj.dh_pub_key) dh_pri_key, dh_pub_key = Crypto.generate_dh_key_pair() user_info_obj.secret_key = Crypto.generate_shared_dh_key( dh_pri_key, user_dh_pub_key) # compose response message c1_nonce = auth_start_msg_obj.c1_nonce c2_nonce = Utils.generate_nonce(32) user_info_obj.temp_nonce = c2_nonce serialized_dh_pub_key = Crypto.serialize_pub_key(dh_pub_key) response_obj = AuthStartRes(serialized_dh_pub_key, c1_nonce, c2_nonce) response_msg = Utils.serialize_obj(response_obj) encrypted_response_msg = Crypto.asymmetric_encrypt( user_info_obj.rsa_pub_key, response_msg) return True, encrypted_response_msg
def _listen_msg(self): while True: msg, addr = self.recv_sock.recvfrom(MAX_MSG_SIZE) if not msg: break # print 'Receive message from ', addr, ':\n', msg tpe, data = Message.loads(msg) decrypted_data = Crypto.asymmetric_decrypt(self.rsa_pri_key, data) msg_obj = Utils.deserialize_obj(decrypted_data) # if the message's timestamp is invalid if not Utils.validate_timestamp(msg_obj.timestamp): print 'Timestamp of the message from another user is invalid, drop the message!' continue if tpe == MessageType.CONN_USER_START: self._handle_conn_start(msg_obj) elif tpe == MessageType.CONN_USER_RES: self._handle_conn_back(msg_obj) elif tpe == MessageType.CONN_USER_END: self._handle_conn_end(msg_obj) elif tpe == MessageType.DIS_CONN: self._handle_disconn_msg(msg_obj) elif tpe == MessageType.TEXT_MSG: self._handle_text_msg(msg_obj)
def decode_transposed_chunks(chunks): return [Crypto.brute_single_char_xor(chunk)[0] for chunk in chunks]
print("[b] Find prime factors") print("[c] Calculate totient") print("[d] Calculate gcd") print("[e] Calculate multiplicative inverse") print("[f] Calculate entropy") print("[g] Perform a shift") print("[h] Decrypt RSA with primes") print("[i] Decrypt RSA without primes") print("[x] Exit\n>>> ") answer = raw_input() if answer == 'a': Modular_Exponent() elif answer == 'b': n = int(raw_input("What number do you want to factor: ")) print(Crypto.factorize(n)) elif answer == 'c': totient() elif answer == 'd': x = int(raw_input("Enter your first number: ")) y = int(raw_input("Enter your second number: ")) print("The gcd is: " + str(Crypto.egcd(x,y)[0])) elif answer == 'e': x = int(raw_input("Enter your number: ")) y = int(raw_input("Enter your mod: ")) print("The inverse is: " + str(Crypto.modinv(x,y))) elif answer == 'f': Crypto.entropy() elif answer == 'g': Crypto.shift() elif answer == 'h':
def problem_5(): print Crypto.xor_encode('ICE', 'Burning \'em, if you ain\'t quick and nimble\nI go crazy when I hear a cymbal')
def problem_3(): ordered_possibilities = Crypto.brute_single_char_xor('1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736') print ordered_possibilities[0]
def problem_4(): possible_ciphers = open('./4.txt', 'r').read().split() best_match = Crypto.find_xor_cipher_in_list(possible_ciphers) print str(best_match[0]).rstrip() + " : " + str(best_match[1])