def multiply_ciphers(cipher1, cipher2, public_key_file):
    cipher1 = pyrsa_sq_mul.unpack_bigint(cipher1)
    cipher2 = pyrsa_sq_mul.unpack_bigint(cipher2)
    key = open(public_key_file,'r').read()
    rsakey = RSA.importKey(key)
    mult_cipher_int = (cipher1 * cipher2) % rsakey.n
    mult_cipher_str = pyrsa_sq_mul.pack_bigint(mult_cipher_int)
    return mult_cipher_str
def decrypt_RSA(private_key_file, cipher, state='sm'):
    key = open(private_key_file,'r').read()
    rsakey = RSA.importKey(key)
    if state == 'sm':
        cipher_int = pyrsa_sq_mul.unpack_bigint(cipher)
        decrypted_byte_message_int = pyrsa_sq_mul.square_multiply(cipher_int, rsakey.d, rsakey.n) 
        decrypted_byte_message_str = pyrsa_sq_mul.pack_bigint(decrypted_byte_message_int)
    elif state == 'part3':
        cipher_rsa = PKCS1_OAEP.new(rsakey)
        decrypted_byte_message_str = cipher_rsa.decrypt(cipher)
    return decrypted_byte_message_str
def encrypt_RSA(public_key_file, message, state='sm'):
    key = open(public_key_file,'r').read()
    rsakey = RSA.importKey(key)
    if state == 'sm':
        if isinstance(message, int):
            byte_message_int = message
        else:
            byte_message_int = pyrsa_sq_mul.unpack_bigint(message)
        encrypt_byte_message_int = pyrsa_sq_mul.square_multiply(byte_message_int, rsakey.e, rsakey.n) 
        encrypt_byte_message_str = pyrsa_sq_mul.pack_bigint(encrypt_byte_message_int)
    elif state == 'part3':
        cipher_rsa = PKCS1_OAEP.new(rsakey)
        encrypt_byte_message_str = cipher_rsa.encrypt(message)
    return encrypt_byte_message_str

if __name__ == "__main__":
    '''Part II: Protocol Attack - Demo encryption and decryption of RSA.'''
    HOST = '10.12.214.190'
    PORT = 8888
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((HOST, PORT))
        '''
        For the first part I am Eve
        I will impersonate Alice and send x (message), s (signature)
        Bob already has Alice's public key, public key(e)
        '''
        print('I AM EVE FOR THIS ROUND\n')
        s = 100  #2019  # 111 11100011
        x = encrypt_RSA('mykey.pem.pub', pyrsa_sq_mul.pack_bigint(s))
        print('Result of encryption with public key:\n{}\n'.format(x))
        print('Result of encryption with public key:\n{}\n'.format(
            b64encode(x)))
        # Send x length
        sock.send(len(x).to_bytes(4, 'big'))
        print('Sent x length: {}'.format(len(x)))
        # Send x
        sock.sendall(x)
        print('Sent new message x')
        # Send s
        sock.send(len(pyrsa_sq_mul.pack_bigint(s)).to_bytes(4, 'big'))
        sock.sendall(pyrsa_sq_mul.pack_bigint(s))
        print('Sent signature s: {}'.format(s))
        # Receive acknowledgement from partner
        ## Receive the length of the message