Пример #1
0
    def msg_received_get(addlist):


        for x in addlist:
             if x[11].startswith(("msg=", "bmsg=", "enc=msg=", "enc=bmsg=")) and x[3] == address:
                #print(x[11])

                connections.send(s, "aliasget", 10)
                connections.send(s, x[2], 10)

                msg_address = connections.receive(s,10)[0][0]

                if x[11].startswith("enc=msg="):
                    msg_received_digest = x[11].lstrip("enc=msg=")
                    try:
                        #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8")

                        (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_digest)
                        private_key = RSA.import_key(open("privkey.der").read())
                        # Decrypt the session key with the public RSA key
                        cipher_rsa = PKCS1_OAEP.new(private_key)
                        session_key = cipher_rsa.decrypt(enc_session_key)
                        # Decrypt the data with the AES session key
                        cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                        msg_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")

                    except:
                        msg_received_digest = "Could not decrypt message"

                elif x[11].startswith("enc=bmsg="):
                    msg_received_digest = x[11].lstrip("enc=bmsg=")
                    try:
                        msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8")

                        #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8")
                        (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_digest)
                        private_key = RSA.import_key(open("privkey.der").read())
                        # Decrypt the session key with the public RSA key
                        cipher_rsa = PKCS1_OAEP.new(private_key)
                        session_key = cipher_rsa.decrypt(enc_session_key)
                        # Decrypt the data with the AES session key
                        cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                        msg_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")

                    except:
                        msg_received_digest = "Could not decrypt message"


                elif x[11].startswith("bmsg="):
                    msg_received_digest = x[11].lstrip("bmsg=")
                    try:
                        msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8")
                    except:
                        msg_received_digest = "Could not decode message"
                elif x[11].startswith("msg="):
                    msg_received_digest = x[11].lstrip("msg=")


                msg_received.insert(INSERT, ((time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(x[1])))) + " From " + msg_address.lstrip("alias=") + ": " + msg_received_digest) + "\n")
Пример #2
0
    def msg_sent_get():

        for row in c.execute("SELECT recipient,openfield,timestamp FROM transactions WHERE address = ? AND (openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ?) ORDER BY timestamp DESC;", (address,) + ("msg=" + '%',) + ("bmsg=" + '%',) + ("enc=msg=" + '%',) + ("enc=bmsg=" + '%',)):
            try:
                # get alias
                c2.execute("SELECT openfield FROM transactions WHERE openfield LIKE ? AND address = ? ORDER BY block_height ASC, timestamp ASC LIMIT 1;", ("alias=" + '%', row[0],))  # asc for first entry
                msg_recipient = c2.fetchone()[0]
                # get alias
            except:
                msg_recipient = row[0]

            if row[1].startswith("enc=msg="):
                msg_sent_digest = row[1].lstrip("enc=msg=")
                try:
                    #msg_sent_digest = key.decrypt(ast.literal_eval(msg_sent_digest)).decode("utf-8")
                    (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_sent_digest)
                    private_key = RSA.import_key(open("privkey.der").read())
                    # Decrypt the session key with the public RSA key
                    cipher_rsa = PKCS1_OAEP.new(private_key)
                    session_key = cipher_rsa.decrypt(enc_session_key)
                    # Decrypt the data with the AES session key
                    cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                    msg_sent_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")

                except:
                    msg_sent_digest = "Could not decrypt message"

            elif row[1].startswith("enc=bmsg="):
                msg_sent_digest = row[1].lstrip("enc=bmsg=")
                try:
                    msg_sent_digest = base64.b64decode(msg_sent_digest).decode("utf-8")
                    #msg_sent_digest = key.decrypt(ast.literal_eval(msg_sent_digest)).decode("utf-8")
                    (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_sent_digest)
                    private_key = RSA.import_key(open("privkey.der").read())
                    # Decrypt the session key with the public RSA key
                    cipher_rsa = PKCS1_OAEP.new(private_key)
                    session_key = cipher_rsa.decrypt(enc_session_key)
                    # Decrypt the data with the AES session key
                    cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
                    msg_sent_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8")
                except:
                    msg_sent_digest = "Could not decrypt message"

            elif row[1].startswith("bmsg="):
                msg_sent_digest = row[1].lstrip("bmsg=")
                try:
                    msg_sent_digest = base64.b64decode(msg_sent_digest).decode("utf-8")
                except:
                    msg_received_digest = "Could not decode message"

            elif row[1].startswith("msg="):
                msg_sent_digest = row[1].lstrip("msg=")

            msg_sent.insert(INSERT, ((time.strftime("%Y/%m/%d,%H:%M:%S", time.gmtime(float(row[2])))) + " To " + msg_recipient.replace("alias=", "") + ": " + msg_sent_digest) + "\n")
Пример #3
0
    def setUp(self):
        file_in = open(pycryptodome_filename(
                        "Crypto.SelfTest.Signature.test_vectors.wycheproof".split("."),
                        "rsa_signature_test.json"), "rt")
        tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            key = RSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                assert False
            assert group['type'] == "RSASigVer"
            
            for test in group['tests']:
                tv = TestVector()
                
                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
Пример #4
0
    def clean(self, *args, **kwargs):

        if self.public_key:

            # Validate the public key format
            try:
                pubkey = RSA.import_key(self.public_key)
            except ValueError:
                raise ValidationError({
                    'public_key': "Invalid RSA key format."
                })
            except:
                raise ValidationError("Something went wrong while trying to save your key. Please ensure that you're "
                                      "uploading a valid RSA public key in PEM format (no SSH/PGP).")

            # Validate the public key length
            pubkey_length = pubkey.size_in_bits()
            if pubkey_length < settings.SECRETS_MIN_PUBKEY_SIZE:
                raise ValidationError({
                    'public_key': "Insufficient key length. Keys must be at least {} bits long.".format(
                        settings.SECRETS_MIN_PUBKEY_SIZE
                    )
                })
            # We can't use keys bigger than our master_key_cipher field can hold
            if pubkey_length > 4096:
                raise ValidationError({
                    'public_key': "Public key size ({}) is too large. Maximum key size is 4096 bits.".format(
                        pubkey_length
                    )
                })

        super(UserKey, self).clean()
Пример #5
0
    def __init__(self, rsa_key_path=None):
        super(PycryptodomeAuthSigner, self).__init__()

        if rsa_key_path:
            with open(rsa_key_path + '.pub', 'rb') as rsa_pub_file:
                self.public_key = rsa_pub_file.read()

            with open(rsa_key_path, 'rb') as rsa_priv_file:
                self.rsa_key = RSA.import_key(rsa_priv_file.read())
Пример #6
0
    def cipher(cls, key):
        """Create a Cipher for a public or private key.

        This just wraps some hard-to-remember Crypto code.

        :param key: A string containing the key.

        :return: A Cipher object which will support either
        encrypt() (public key) or decrypt() (private key).
        """
        return PKCS1_OAEP.new(RSA.import_key(key))
Пример #7
0
def decrypt(encrypted):

    (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(encrypted)
    private_key = RSA.import_key(open("privkey.der").read())
    # Decrypt the session key with the public RSA key
    cipher_rsa = PKCS1_OAEP.new(private_key)
    session_key = cipher_rsa.decrypt(enc_session_key)
    # Decrypt the data with the AES session key
    cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce)
    decrypted = cipher_aes.decrypt_and_verify(ciphertext, tag)
    return decrypted
def generate_token(data, rsa_key_string):
    rsaKey = RSA.import_key(rsa_key_string)

    session_key = get_random_bytes(16)

    # Encrypt the session key with the public RSA key
    cipher_rsa = PKCS1_OAEP.new(rsaKey)
    encrypted_session_key = cipher_rsa.encrypt(session_key)

    # Encrypt the data with the AES session key
    cipher_aes = AES.new(session_key, AES.MODE_EAX)
    ciphertext, tag = cipher_aes.encrypt_and_digest(data.encode())

    result = encrypted_session_key + cipher_aes.nonce + tag + ciphertext

    return base64.b64encode(result).decode()
Пример #9
0
 def encrypt(self, file_path, output_file_path):
     if not self.public_key_path:
         print('Please set public_key_path!')
     else:
         with open(output_file_path, 'wb') as out_file:
             public_file = open(self.public_key_path)
             recipient_key = RSA.import_key(
                 public_file.read())
             session_key = get_random_bytes(16)
             cipher_rsa = PKCS1_OAEP.new(recipient_key)
             out_file.write(cipher_rsa.encrypt(session_key))
             cipher_aes = AES.new(session_key, AES.MODE_EAX)
             public_file.close()
             with open(file_path, 'rb') as f:
                 data = f.read()
             cipher_text, tag = cipher_aes.encrypt_and_digest(data)
             out_file.write(cipher_aes.nonce)
             out_file.write(tag)
             out_file.write(cipher_text)
def verify_and_decrypt_token(data, rsa_key_string):
    private_key = RSA.import_key(rsa_key_string)

    decoded_bytes = base64.b64decode(data)

    enc_session_key = decoded_bytes[0:private_key.size_in_bytes()]
    nonce = decoded_bytes[private_key.size_in_bytes():private_key.size_in_bytes()+16]
    tag = decoded_bytes[private_key.size_in_bytes() + 16:private_key.size_in_bytes() + 32]
    ciphertext = decoded_bytes[private_key.size_in_bytes() + 32:]

    # Decrypt the session key with the public RSA key
    cipher_rsa = PKCS1_OAEP.new(private_key)
    session_key = cipher_rsa.decrypt(enc_session_key)

    # Decrypt the data with the AES session key
    cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
    data = cipher_aes.decrypt_and_verify(ciphertext, tag)

    return data.decode()
Пример #11
0
 def decrypt(self, file_path, output_file_path):
     if not self.code:
         print('Please set password first!')
     elif not self.private_key_path:
         print('Please set private_key_path!')
     else:
         with open(file_path, 'rb') as file:
             private_file = open(self.private_key_path)
             private_key = RSA.import_key(
                 private_file.read(),
                 passphrase=self.code)
             enc_session_key, nonce, tag, cipher_text = [file.read(x)
                                                         for x in (private_key.size_in_bytes(), 16, 16, -1)]
             cipher_rsa = PKCS1_OAEP.new(private_key)
             session_key = cipher_rsa.decrypt(enc_session_key)
             cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
             data = cipher_aes.decrypt_and_verify(cipher_text, tag)
             private_file.close()
         with open(output_file_path, 'wb') as f:
             f.write(data)
Пример #12
0
    def add_tests(self, filename):
        comps = "Crypto.SelfTest.Signature.test_vectors.wycheproof".split(".")
        with open(pycryptodome_filename(comps, filename), "rt") as file_in:
            tv_tree = json.load(file_in)

        class TestVector(object):
            pass
        self.tv = []

        for group in tv_tree['testGroups']:
            key = RSA.import_key(group['keyPem'])
            hash_name = group['sha']
            if hash_name == "SHA-512":
                hash_module = SHA512
            elif hash_name == "SHA-384":
                hash_module = SHA384
            elif hash_name == "SHA-256":
                hash_module = SHA256
            elif hash_name == "SHA-224":
                hash_module = SHA224
            elif hash_name == "SHA-1":
                hash_module = SHA1
            else:
                raise ValueError("Unknown hash algorithm: " + hash_name)
            assert group['type'] == "RSASigVer"
            
            for test in group['tests']:
                tv = TestVector()
                
                tv.id = test['tcId']
                tv.comment = test['comment']
                for attr in 'msg', 'sig':
                    setattr(tv, attr, unhexlify(test[attr]))
                tv.key = key
                tv.hash_module = hash_module
                tv.valid = test['result'] != "invalid"
                tv.warning = test['result'] == "acceptable"
                self.tv.append(tv)
Пример #13
0
 def test_import_key(self):
     """Verify that import_key is an alias to importKey"""
     key = RSA.import_key(self.rsaPublicKeyDER)
     self.failIf(key.has_private())
     self.assertEqual(key.n, self.n)
     self.assertEqual(key.e, self.e)
Пример #14
0
def executeCommand(command):
    # print(command)
    isForDeposit = False

    # secure command option
    if command[0] == 't':
        isSecure = True
        # OP_GET_READY_FOR_DEPOSIT
        if command[2] == 'v':
            isForDeposit = True
    else:
        isSecure = False
        if command[0] == 'r':
            isForDeposit = True

    split_command = command.split(" ")
    #print(split_command)

    # commnad's last string means message sender 
    user = split_command[-1]

    if isSecure:
        # remove 't ' from command
        command = " ".join(split_command[1:-1])
    else:
        command = " ".join(split_command[:-1])

    # encode command
    command = command.encode('utf-8')

    # encryption using RSA
    try:
        with open("../key/private_key_{}.pem".format(user), "rb") as f:
            sk = RSA.import_key(f.read())
        with open("../key/public_key_{}.pem".format(user), "rb") as f:
            vk = RSA.import_key(f.read())
    except:
        print("no user key")
        exit()

    if isForDeposit:
        pubkey = (vk.n).to_bytes(384, 'little')
        pubkey_hex = pubkey.hex()
        # print(pubkey_hex)
        message = command + b" " + pubkey
    else:
        hash = SHA256.new(command)
        # print(hash.digest().hex())
        sig = pkcs1_15.new(sk).sign(hash)
        message = command + b" " + sig

        try:
            pkcs1_15.new(vk).verify(hash, sig)
        except:
            print("bad signature")
            exit()

    if isSecure:
        # execute secure_command
        return secure_command(message, user)
    else:
        return message
from Crypto.PublicKey import RSA

# secret_code = "Unguessable" # which is wrong
secret_code = "This is Abel's secret"
encoded_key = open("d4rsa_key.bin", "rb").read()
key = RSA.import_key(encoded_key, passphrase=secret_code)

print(key.publickey().exportKey())
Пример #16
0
 def test_encryption(self):
     publickey = RSA.import_key(self.predefined_public)
     encrypted = self.cryptapi.encrypt_with_rsa_key(publickey, self.text)
     self.assertIsNotNone(encrypted)
Пример #17
0
from Crypto.PublicKey import RSA
from sympy.ntheory.factor_ import totient, factorint
from decimal import Decimal

def egcd(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q, r = b//a, b%a
        m, n = x-u*q, y-v*q
        b,a, x,y, u,v = a,r, u,v, m,n
        gcd = b
    return gcd, x, y

if __name__ == '__main__':
    f = open("./bin/joan.marc.pastor_pubkeyRSA_pseudo.pem")
    key = RSA.import_key(f.read())
    f.close()

    n = key.n
    e = key.e

    # totient() implementation: https://docs.sympy.org/latest/_modules/sympy/ntheory/factor_.html#totient
    phiN = totient(n)
    gcd, a, b = egcd(e, phiN)
    if (a >= 0): 
        d = a
    else:
        d = a + phiN

    key = RSA.construct((n, e, d), consistency_check=False)
    f = open("./out/RSAprivateKey.pem", "wb")
Пример #18
0
 def load_private_key(self, path):
     if os.path.isfile(path):
         self.private_key = RSA.import_key(self.__read_key(path))
     else:
         self.private_key = RSA.import_key(path)
     self.signing_key = PKCS1_v1_5.new(rsa_key=self.private_key)
Пример #19
0
def deal_with_client(conn, addr):
    """Handles a single client connection."""
    try:
        client_id = None
        while client_id is None:
            ready = select.select([conn], [], [], 5)
            if ready[0]:
                msg = conn.recv(BUFSIZ)
                msg = parse_message(msg.decode('ASCII'))
                if msg in clients.keys():
                    conn.sendall(
                        get_message(
                            'Username already in use. Please use another').
                        encode('ASCII'))
                else:
                    client_id = msg

        conn.sendall(get_message(client_id).encode('ASCII'))
        prefix = './s_keys/' + client_id + '_'
        getKeys(prefix)
        private_key = loadPrivateKey(prefix + 'private.pem')
        public_key = loadPublicKey(prefix + 'public.pem')
        ready = select.select([conn], [], [])
        if ready[0]:
            conn.recv(BUFSIZ)
        conn.sendall(open(prefix + 'public.pem').read().encode('ASCII'))
        client_key = None
        while client_key is None:
            ready = select.select([conn], [], [], 10)
            if ready[0]:
                msg = conn.recv(BUFSIZ)
                client_key = msg
        client_key_file = client_key.decode('ASCII')
        client_key = RSA.import_key(client_key_file)
        room_request = None
        clients[client_id] = [addr, conn, room_request, client_key_file]

        while True:
            my_data = clients.get(client_id)
            my_requests = my_data[2]
            if my_requests is not None:
                ready = select.select([], [conn], [], 10)
                if ready[1]:
                    conn.sendall(
                        encrypt_message(client_key,
                                        "/*-*/c_k/*+*/" + str(my_requests)))
                    my_data[2] = None
                    clients[client_id] = my_data
                    continue

            ready = select.select([conn], [], [], 5)
            if ready[0]:
                msg = conn.recv(BUFSIZ)
                if len(msg) == 0:
                    conn.close()
                    continue
                msg = decrypt_message(private_key, msg)
                action = client_requests(msg)

                if action is None:
                    conn.sendall(
                        encrypt_message(client_key, "Error on communication"))
                    continue

                if action == 'refresh':
                    conn.sendall(encrypt_message(client_key, get_list()))
                    continue
                if action == 'room':
                    ready = select.select([conn], [], [], 5)
                    if ready[0]:
                        msg = conn.recv(BUFSIZ)
                        msg = decrypt_message(private_key, msg)
                        m_list = msg.split('\n')

                        target_data = clients.get(m_list[0], 'error')
                        if target_data == 'error':
                            conn.sendall(
                                encrypt_message(client_key, 'ID not found'))
                            continue
                        manage_room(m_list, client_id, private_key)
                        continue
                if action == 'file_up':
                    f_info = msg.replace("/*-*/send_file/*+*/", "")
                    f_info = f_info.split("/*-*/")
                    get_socket = socket_request()
                    get_thread = threading.Thread(target=save_file,
                                                  args=(f_info, get_socket,
                                                        client_key))
                    get_thread.start()
                    conn.sendall(
                        encrypt_message(
                            client_key, "/*-*/p_num/*+*/" +
                            str(get_socket.getsockname()[1])))
                    continue

                if action == 'file_down':
                    f_name = msg.replace("/*-*/get_file/*+*/", "")
                    send_socket = socket_request()
                    send_thread = threading.Thread(target=send_file,
                                                   args=(f_name, send_socket,
                                                         client_key))
                    send_thread.start()
                    conn.sendall(
                        encrypt_message(
                            client_key, "/*-*/p_num/*+*/" +
                            str(send_socket.getsockname()[1])))
                    continue

    except (ConnectionError, ValueError):
        try:
            del clients[client_id]
            print(client_id + " has left the app")
            del_path = prefix + 'private.pem'
            delete_file(del_path)
            del_path = prefix + 'public.pem'
            delete_file(del_path)
        except NameError:
            pass
        except KeyError:
            print("Connection closed with anonymous client")
            pass
    except Exception as ex:
        traceback.print_exc()
Пример #20
0
def main(port, addr, name, password):
    server_address = addr
    server_port = port
    client_name = name
    client_passwd = password
    print(client_name, password)

    if server_port < 1024 or server_port > 65535:
        client_logger.critical(
            f'Попытка запуска сервера с указанием неподходящего порта {server_port} сервера.'
            f'Допустимы адреса с 1024 до 65535.')
        sys.exit(1)
    # Создаём клиентокое приложение
    client_app = QApplication(sys.argv)

    #Если имя пользователя не было указано в командной строке то запросим его
    start_dialog = UserNameDialog()
    if not client_name or not client_passwd:
        client_app.exec_()
        # Если пользователь ввёл имя и нажал ОК, то сохраняем ведённое и удаляем объект, инааче выходим
        if start_dialog.ok_pressed:
            client_name = start_dialog.client_name.text()
            client_passwd = start_dialog.client_passwd.text()
        else:
            sys.exit(0)

    # Записываем логи
    client_logger.info(
        f'Запущен клиент с парамертами: адрес сервера: {server_address} , порт: {server_port}, имя пользователя: {client_name}'
    )
    # Загружаем ключи с файла, если же файла нет, то генерируем новую пару.
    #dir_path = os.path.dirname(os.path.realpath(__file__))
    dir_path = os.getcwd()
    key_file = os.path.join(dir_path, f'{client_name}.key')
    if not os.path.exists(key_file):
        keys = RSA.generate(2048, os.urandom)
        with open(key_file, 'wb') as key:
            key.write(keys.export_key())
    else:
        with open(key_file, 'rb') as key:
            keys = RSA.import_key(key.read())

    keys.publickey().export_key()
    # Создаём объект базы данных
    database = ClientDatabase(client_name)

    # Создаём объект - транспорт и запускаем транспортный поток
    try:
        transfer = ClientTransfer(server_port, server_address, database,
                                  client_name, client_passwd, keys)
    except ServerError as error:
        print(error.text)
        sys.exit(1)
    transfer.setDaemon(True)
    transfer.start()

    # Удалим объект диалога за ненадобностью
    del start_dialog
    # Создаём GUI
    main_window = ClientMainWindow(database, transfer, keys)
    main_window.make_connection(transfer)
    main_window.setWindowTitle(f'Чат Программа alpha release - {client_name}')
    client_app.exec_()

    # Раз графическая оболочка закрылась, закрываем транспорт
    transfer.transfer_shutdown()
    transfer.join()
Пример #21
0
 def test_negative_2(self):
     key = RSA.import_key(self.rsa_key)
     h = SHA256.new(self.msg)
     verifier = pss.new(key, salt_bytes=1000)
     tag = bytearray(self.tag)
     self.assertRaises(ValueError, verifier.verify, h, tag)
Пример #22
0
 def test_positive_1(self):
     key = RSA.import_key(self.rsa_key)
     h = SHA256.new(self.msg)
     verifier = pss.new(key)
     verifier.verify(h, self.tag)
Пример #23
0
 def filter_rsa(group):
     return RSA.import_key(group['keyPem'])
Пример #24
0
def get_private_key(filepath, password="******"):
    return RSA.import_key(open(filepath).read(), passphrase=password)
Пример #25
0
def rsaEncryptionOaepSha1ToBase64(publicKeyPem, message):
    rsaPublicKey = RSA.import_key(publicKeyPem)
    plaintext = message.encode("ascii")
    cipher = PKCS1_OAEP.new(rsaPublicKey)
    ciphertext = cipher.encrypt(plaintext)
    return base64Encoding(ciphertext)
Пример #26
0
def sig_gen(n_all, k, userlist):

    k_all = k
    # 读取Uk的私钥
    private_key = RSA.import_key(
        open('db/pem/private_key' + '_U' + str(k) + '.pem', "rb").read())
    d = private_key.d

    # 从文件中读取公钥
    Ln = []  # 公钥N
    Le = []  # 公钥e
    for i in userlist:
        public_key = RSA.import_key(
            open('db/pem/public_key' + '_U' + str(i) + '.pem').read())
        Ln.append(public_key.n)
        Le.append(public_key.e)
        if k == i:
            k = len(Ln) - 1
    n = len(userlist)  # 新的环的长度
    with open('db/n.json', 'w') as f:
        f.write(str(n))

    # 第一步计算关联标签e_
    phi_n = (private_key.p - 1) * (private_key.q - 1)
    ak = random.randrange(1, phi_n)
    while gmpy2.gcd(ak, phi_n) != 1:
        ak = random.randrange(1, phi_n)
    r = random.randrange(1, phi_n)
    while gmpy2.gcd(r, phi_n) != 1:
        r = random.randrange(1, phi_n)

    ak, r = get_akr(n_all, k_all, ak, r)

    ak_1 = InvMod(ak, phi_n)
    e_ = MulMod(ak_1, r, phi_n)

    # 第二步计算c_(k+1)
    u = random.randrange(1, Ln[k])
    v = random.randrange(1, Ln[k])
    # 要签名的内容
    with open('db/message.txt', 'r') as f:
        m = f.read()
    # 公钥集合
    listL = Ln + Le
    strL = [str(i) for i in listL]
    L = '\n'.join(strL)
    with open('db/L.txt', 'w') as file_object:
        file_object.write(L)

    s = [0 for x in range(0, n)]
    s_ = [0 for x in range(0, n)]
    z = [0 for x in range(0, n)]
    z_ = [0 for x in range(0, n)]
    c = [0 for x in range(0, n + 1)]  # 0~n,包含边界
    c[k + 1] = hash_my(L, e_, m, u, v)  # 当前用户后一个
    z[k] = u
    z_[k] = v
    for i in range(k + 1, n):
        s[i] = random.randrange(1, Ln[i])
        s_[i] = random.randrange(1, Ln[i])
        z[i] = c[i] + gmpy2.powmod(s[i], Le[i], Ln[i])
        z_[i] = c[i] + gmpy2.powmod(s_[i], e_, Ln[i])
        c[i + 1] = hash_my(L, e_, m, z[i], z_[i])
        # c[i+1] = hash_my(L, e_, m, c[i]+gmpy2.powmod(s[i], Le[i], Ln[i]), c[i]+gmpy2.powmod(s_[i], e_, Ln[i]))
    c[0] = c[n]
    for i in range(0, k):
        s[i] = random.randrange(1, Ln[i])
        s_[i] = random.randrange(1, Ln[i])
        z[i] = c[i] + gmpy2.powmod(s[i], Le[i], Ln[i])
        z_[i] = c[i] + gmpy2.powmod(s_[i], e_, Ln[i])
        c[i + 1] = hash_my(L, e_, m, z[i], z_[i])
        # c[i+1] = hash_my(L, e_, m, c[i]+gmpy2.powmod(s[i], Le[i], Ln[i]), c[i]+gmpy2.powmod(s_[i], e_, Ln[i]))
    r_1 = InvMod(r, phi_n)
    s[k] = gmpy2.powmod(u - c[k], d, Ln[k])
    s_[k] = gmpy2.powmod(v - c[k], ak * r_1, Ln[k])

    # 合并生成签名
    sigma = []
    sigma = [c[0]] + s + s_ + [e_] + [r]
    str_sigma = [str(i) for i in sigma]  # 每个元素转化为字符串
    out_str_sigma = '\n'.join(str_sigma)
    # with open('sigma_U'+str(k)+'.txt', 'w') as file_object:
    with open('db/sigma.txt', 'w') as file_object:
        file_object.write(out_str_sigma)
        print('签名生成完成')
Пример #27
0
def demo(options):
    global RSA_KEY_SIZE, INITIAL_MESSAGE_FILE, SHARED_MESSAGE_FILE, BOB_OUTPUT_FILE
    alicekey = None
    bobkey = None
    print("Starting alice's key")
    if options.alicekeyfile is None:  #generate a key for RSA
        alicekey = RSA.generate(RSA_KEY_SIZE)
    else:
        alicefile = open(options.alicekeyfile, "rb").read()
        alicekey = RSA.import_key(alicefile)
        #alicepublic = alicekey.publickey()
        #print(alicepublic.export_key())
        #print(alicekey)
    print("Starting bob's key")
    if options.bobkeyfile is None:  #generate a key pair for RSA
        bobkey = RSA.generate(RSA_KEY_SIZE)
    else:
        bobfile = open(options.bobkeyfile, "rb").read()
        bobkey = RSA.import_key(bobfile)
        #bobpublic = alicekey

    alice = Alice(alicekey)
    bob = Bob(bobkey)
    alice.setRecieverPublic(bobkey.publickey())
    bob.setSenderPublic(alicekey.publickey())

    firstAlice = "aliceMessagePlaintext.bin"
    print("MESSAGE PLAINTEXT - ALICE WRITTEN TO {0}".format(firstAlice))
    message = alice.convertForRSA()
    firstAliceFile = open(firstAlice, "wb")
    firstAliceFile.write(message)
    firstAliceFile.close()
    #print("Press any key to proceed")
    #input()

    secondAlice = "aliceMessageCiphertext.bin"
    print("MESSAGE CIPHERTEXT - ALICE WRITTEN TO {0}".format(secondAlice))
    ciphertext = alice.encryptRSA()
    secondAliceFile = open(secondAlice, "wb")
    secondAliceFile.write(ciphertext)
    secondAliceFile.close()
    #print("Press any key to proceed")
    #input()

    firstBob = "bobMessagePlaintext.bin"
    print("MESSAGE PLAINTEXT - BOB WRITTEN TO {0}".format(firstBob))
    plaintext = bob.decryptRSA(ciphertext)
    firstBobFile = open(firstBob, "wb")
    firstBobFile.write(plaintext)
    firstBobFile.close()
    #print("Press any key to proceed")
    #input()

    secondBob = "bobMessageCiphertext.bin"
    print("MESSAGE CIPHERTEXT - BOB WRITTEN TO {0}".format(secondBob))
    ciphertext = bob.encryptRSA()
    secondBobFile = open(secondBob, "wb")
    secondBobFile.write(ciphertext)
    secondBobFile.close()
    #print("Press any key to proceed")
    #input()

    thirdAlice = "aliceMessagePlaintext2.bin"
    print("MESSAGE PLAINTEXT - ALICE WRITTEN TO {0}".format(thirdAlice))
    plaintext = alice.decryptRSA(ciphertext)
    thirdAliceFile = open(thirdAlice, "wb")
    thirdAliceFile.write(plaintext)
    thirdAliceFile.close()
    #print("Press any key to proceed")
    #input()

    print("START SYMMETRIC ENCRYPTION")
    inputplaintext = open(INITIAL_MESSAGE_FILE, "rb")
    plaintext = inputplaintext.read()
    alice.startRC4(plaintext, SHARED_MESSAGE_FILE)
    inputplaintext.close()

    print("BOB DECODE")
    inputciphertext = open(SHARED_MESSAGE_FILE, "rb")
    ciphertext = inputciphertext.read()
    bob.startRC4(ciphertext, BOB_OUTPUT_FILE)
    inputciphertext.close()
Пример #28
0
    def data_received(self, data: bytes):
        filepath = None
        ext = None
        images = ['.png', '.jpg', '.gif', 'jpeg']

        try:
            pack = pickle.loads(data)
            if type(pack) != dict:
                raise Exception
        except Exception:
            self.data.append(data)
            try:
                pack = pickle.loads(b''.join(self.data))
                self.data.clear()
            except pickle.UnpicklingError:
                return
        if pack['state'] == 1:
            self.public = pack['public']
            self.public = RSA.import_key(self.public)
            return

        if pack['state'] == 3 or pack['state'] == 4 or pack['state'] == 2:
            self.window.append_text(pack['message'])
            return
        if pack['state'] == 5:
            yellowtext = f'<span style=\" font-weight:600;font-size:{self.settings["font-size"]}; color:#540099;\" >'
            yellowtext += decrypt(self.private, pack['message'])
            yellowtext += "</span>"
            self.window.append_text(yellowtext)
            return

        if pack['state'] == 6:
            blue = ""
            message = decrypt(self.private, pack['message'])
            message = f'<span style=\" font-weight: 400; font-style: normal; color:{self.window.text_color}; font-size: ' \
                      f'{self.settings["font-size"]};\" >{time.strftime("%H:%M", time.localtime())}</span> ' \
                      f'<span style=\"color: {pack["color"]}; font-weight: 400; font-style: ' \
                      f'{self.settings["font"]};\">  {pack["login"]}: </span>{message} '
            blue += f'<span style=\" font-weight: 400;font-size: {self.settings["font-size"]}; ' \
                    f'font-style: italic; color: orange;\" > {message}</span>'
            self.window.append_text(blue)
            return

        if pack['state'] == 7:
            yellowtext = "<span style=\" font-weight: 600; color: #540099;\" >"
            yellowtext += decrypt(self.private, pack['message'])
            yellowtext += "</span>"
            self.window.append_text(yellowtext)
            return

        if pack['state'] == 8:
            file = decrypt_bytes(self.private, pack['attach'])
            ext = pack["fname"][pack["fname"].rfind("."):]
            if ext in images:
                pack["fname"] = f'{str(uuid.uuid4())}{ext}'
            save_bytes(b=file, file=pack["fname"])
            filepath = f'{os.getcwd()}/cache/{pack["fname"]}'

        if pack['state'] == 14:
            blue = ""
            message = decrypt(self.private, pack['message'])
            message = f'<span style=\" font-weight: 400; font-style: normal; color:{self.window.text_color}; font-size: ' \
                      f'{self.settings["font-size"]};\" >{time.strftime("%H:%M", time.localtime())}</span> ' \
                      f'<span style=\"color: {pack["color"]}; font-weight: 400; font-style: ' \
                      f'{self.settings["font"]};\">  {pack["login"]}: </span>{message} '
            blue += f'<span style=\" font-weight: 400;font-size: {self.settings["font-size"]}; ' \
                    f'font-style: italic; color: orange;\" > {message}</span>'
            file = decrypt_bytes(self.private, pack['attach'])
            ext = pack["fname"][pack["fname"].rfind("."):]
            filepath = f'{os.getcwd()}/cache/{pack["fname"]}'
            if ext in images:
                pack["fname"] = f'{str(uuid.uuid4())}{ext}'
                filepath = f'{os.getcwd()}/cache/{pack["fname"]}'
                blue += f'<br> <a href="{filepath}"><img src="{filepath}" width="200" style=' \
                        f'"position: absolute; top: 0px; right: 0px;"></a><br>'
            else:
                blue += f' ||| <a href="{filepath}">{pack["fname"]}</a>'
            save_bytes(b=file, file=pack["fname"])
            self.window.append_text(blue)
            print('private picture')
            return

        message = decrypt(self.private, pack['message'])
        message = f'<span style=\" font-weight: 400; color:{self.window.text_color}; font-size: {self.settings["font-size"]};\" >{time.strftime("%H:%M", time.localtime())}</span>' \
                  f'<span style=\"color: {pack["color"]}\">  {pack["login"]}: </span> {message}'
        message = f'<span style=\" font-size: {self.settings["font-size"]}+2px; color:{self.window.text_color};\" >' + message
        if ext in images:
            message = message + f'<br> <a href="{filepath}"><img src="{filepath}" width="200" style="' \
                                f'position: absolute; top: 0px; right: 0px;"></a><br>'
        elif filepath is not None:
            message = message + f' ||| <a href="{filepath}">{pack["fname"]}</a> '
            # TODO: Сделать ссылку на файл картинкой
        self.window.append_text(message)
Пример #29
0
 def load_keypair(self, path):
     self.__check_dir(path)
     self.private_key = RSA.import_key(self.__read_key(f'{path}/private_key.pem'))
     self.public_key = RSA.import_key(self.__read_key(f'{path}/public_key.pem'))
     self.signing_key = PKCS1_v1_5.new(rsa_key=self.private_key)
     self.verification_key = PKCS1_v1_5.new(rsa_key=self.public_key)
Пример #30
0
 def test_import_key(self):
     """Verify that import_key is an alias to importKey"""
     key = RSA.import_key(self.rsaPublicKeyDER)
     self.assertFalse(key.has_private())
     self.assertEqual(key.n, self.n)
     self.assertEqual(key.e, self.e)
Пример #31
0
 def load_public_key(self, path):
     if os.path.isfile(path):
         self.public_key = RSA.import_key(self.__read_key(path))
     else:
         self.public_key = RSA.import_key(path)
     self.verification_key = PKCS1_v1_5.new(rsa_key=self.public_key)
Пример #32
0
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP

file_in = open("encrypted_data.bin", "rb")

private_key = RSA.import_key(open("private.pem").read())

enc_session_key, nonce, tag, ciphertext = \
   [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]

# Decrypt the session key with the private RSA key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)

# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data.decode("utf-8"))
    def Start_sever(self):
        global Custom_set, clients_list_show, id_list, clients, Run, PubKey, PriKey, sockets_list, show_print
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind(
            (Custom_set['Settings']['ip'], Custom_set['Settings']['port']))
        server_socket.listen()
        sockets_list = [server_socket]
        clients = {}
        clients_list_show.clear()
        Run = True
        self.Generate_Key()
        log.info('Listening for connections on {}:{}...'.format(
            Custom_set['Settings']['ip'], Custom_set['Settings']['port']))
        self.textEditor.append(
            '[ INFO ] Listening for connections on {}:{}...'.format(
                Custom_set['Settings']['ip'], Custom_set['Settings']['port']))
        self.textEditor.moveCursor(QtGui.QTextCursor.End)
        self.actionStart.setEnabled(False)
        self.actionStop.setEnabled(True)

        while True:
            if Run == False:
                break
            read_sockets, _, exception_sockets = select.select(
                sockets_list, [], sockets_list)
            for notified_socket in read_sockets:
                if notified_socket == server_socket:
                    client_socket, client_address = server_socket.accept()
                    user = self.receive_message(client_socket)
                    if user is False:
                        continue
                    sockets_list.append(client_socket)
                    clients[client_socket] = user
                    message = PubKey
                    message_header = f"{len(message):<{HEADER_LENGTH}}".encode(
                        'utf-8')
                    client_socket.send(user['header'] + user['data'] +
                                       message_header + message)

                    message_header = client_socket.recv(HEADER_LENGTH)
                    if not len(message_header):
                        print('Connection closed by the Client')
                    message_length = int(
                        message_header.decode('utf-8').strip())
                    message = client_socket.recv(message_length)
                    PubKey_cliet = message

                    log.info(
                        'Accepted new connection from {}:{}, username: {}'.
                        format(*client_address, user['data'].decode('utf-8')))
                    self.textEditor.append(
                        '[ INFO ] Accepted new connection from {}:{}, username: {}'
                        .format(*client_address, user['data'].decode('utf-8')))
                    self.textEditor.moveCursor(QtGui.QTextCursor.End)
                    clients_list_show[id_list] = {
                        'sock': client_socket,
                        'addres': client_address,
                        'PubKey': PubKey_cliet,
                        'data': user['data'].decode('utf-8')
                    }
                    id_list = id_list + 1
                else:
                    message = self.receive_message(notified_socket)
                    if message is False:
                        log.info('Closed connection from: {}'.format(
                            clients[notified_socket]['data'].decode('utf-8')))
                        self.textEditor.append(
                            '[ INFO ] Closed connection from: {}'.format(
                                clients[notified_socket]['data'].decode(
                                    'utf-8')))
                        self.textEditor.moveCursor(QtGui.QTextCursor.End)
                        kry_copy = tuple(clients_list_show.keys())
                        for k in kry_copy:
                            if clients_list_show[k]['sock'] == notified_socket:
                                del clients_list_show[k]

                        sockets_list.remove(notified_socket)
                        del clients[notified_socket]
                        continue

                    msg = message['data']
                    # decryptor = PKCS1_OAEP.new(PriKey)
                    # decrypted = decryptor.decrypt(msg)

                    user = clients[notified_socket]

                    # log.debug(f'Received message from {user["data"].decode("utf-8")}: {decrypted.decode("utf-8")}')
                    # self.textEditor.append(f'[ DEBUG ] Received message from {user["data"].decode("utf-8")}: {decrypted.decode("utf-8")}')
                    if show_print == True:
                        self.textEditor.append(
                            f'[ CHAT ] Message from {user["data"].decode("utf-8")}: {msg.decode("utf-8")}'
                        )
                        self.textEditor.moveCursor(QtGui.QTextCursor.End)
                    for client_socket in clients:
                        if client_socket != notified_socket:
                            for y in clients_list_show:
                                if clients_list_show[y][
                                        'sock'] == client_socket:
                                    PubKey_ex = RSA.import_key(
                                        clients_list_show[y].get('PubKey'))
                                    # encryptor = PKCS1_OAEP.new(PubKey_ex)
                                    # encrypted = encryptor.encrypt(decrypted)
                                    message_header = f"{len(msg):<{HEADER_LENGTH}}".encode(
                                        'utf-8')
                                    client_socket.send(user['header'] +
                                                       user['data'] +
                                                       message_header + msg)

            for notified_socket in exception_sockets:
                sockets_list.remove(notified_socket)
                del clients[notified_socket]

        for x in sockets_list:
            sockets_list[x].close()
        sockets_list.clear()
        clients.clear()
        id_list = 0

        log.info('Closed Sever Service')
        self.textEditor.append('[ INFO ] Closed Sever Service')
        self.actionStart.setEnabled(True)
        self.actionStop.setEnabled(False)
        return 0
Пример #34
0
def cargar_RSAKey_Privada(fichero, password):
    key_cifrada = open(fichero, "rb").read()
    key = RSA.import_key(key_cifrada, passphrase=password)
    return key
Пример #35
0
	def decryptUserCredentials(file):
		priKey = RSA.import_key(open('keys/user/pass_private.pem').read())
		return decrypt(file, priKey)
Пример #36
0
icKO95pcPRhmfzuqfhEu/d/ZYjabao95baBHcrRxEbXZtjg88KVXKg==
-----END RSA PRIVATE KEY-----
"""

c_defs = """
int monty_pow(const uint8_t *base,
               const uint8_t *exp,
               const uint8_t *modulus,
               uint8_t       *out,
               size_t len,
               uint64_t seed);
"""

_raw_montgomery = load_pycryptodome_raw_lib("Crypto.Math._montgomery", c_defs)

key = RSA.import_key(rsa_pem)
message = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
SIZE = key.size_in_bytes()

# -----------------------------------------------------------------
start = time.time()
for x in range(ITER):
	result_cpython = pow(message, key.d, key.n)
end = time.time()
print("CPython =", end-start)

# -----------------------------------------------------------------
base_b = long_to_bytes(message, SIZE)
exp_b = long_to_bytes(key.d, SIZE)
modulus_b = long_to_bytes(key.n, SIZE)
out = create_string_buffer(SIZE)
Пример #37
0
	def decryptMsg(self, filename):
		priKey = RSA.import_key(open('keys/user/enc_private.pem').read())
		return decrypt(filename, priKey)
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

data = b"Behind every successful man there's a lot u unsuccessful years. "


file_out = open("d6_encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("d3public.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
file_out.write(cipher_rsa.encrypt(session_key))

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext) ]
Пример #39
0
from Crypto.Cipher import AES, PKCS1_OAEP


# Get file to decrypt
user_encrypted_file = raw_input("\n\nFILE INPUT\nEnter file to decrypt:")
with open(user_encrypted_file, 'rb') as in_file:
    received_msg = pickle.load(in_file)

# received_msg = transmitted_message
print "Received message: " + str(received_msg)
encrypted_session_key, received_aad, received_ciphertext, received_tag, received_nonce = received_msg[0], received_msg[1], received_msg[2], received_msg[3], received_msg[4]

# Get RSA private key
rsa_private_key = raw_input("Enter private key to decrypt with:")
private_key = "rsa_private_key1.pem"
private_key = RSA.import_key(open(rsa_private_key).read())

# Decrypt the session key with the RSA private key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(encrypted_session_key)
print "Decryption Key: " + str(session_key)

# Validate MAC and decrypt
# If MAC validation fails, ValueError exception will be thrown
cipher = AES.new(session_key, AES.MODE_GCM, received_nonce)
cipher.update(received_aad)
try:
    decrypted_data = cipher.decrypt_and_verify(received_ciphertext, received_tag)
    print "\nMAC validated: Data was encrypted with a seesion key that was encrypted with private key used for decryption"
    print "\nAuthenticated AAD: " + str(received_aad)
    # print "Decrypted sensitive data: " + str(decrypted_data)
Пример #40
0
async def decrypt_pub_key(data: bytes, key: bytes):
    recipient_key = RSA.import_key(key)
    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    decrypted_data = cipher_rsa.decrypt(data)
    return decrypted_data
Пример #41
0
def main():
    '''
    Main method. Loops forever until killed
    '''
    args = get_args()
    port = args.port
    ip = args.ip

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.setblocking(0)
    server.bind((ip, port))
    server.listen(5)

    inputs = [server]
    outputs = []
    msg_queues = {}
    n_users = 0
    user_connect_time = {}

    #Dictionaries containing buffered messages and message state variable
    #Key for each is a socket object
    msg_buffers = {}
    recv_len = {}
    msg_len = {}
    usernames = {}
    unverified_usernames = {}
    symmetric_keys = {}
    ciphers = {}

    while inputs:

        #if 60 seconds are up no username yet, disconnect the client
        users = list(user_connect_time)
        for s in users:
            if (time.time() - user_connect_time[s]) > TIMEOUT:

                LNP.send(s, '', "EXIT")

                inputs.remove(s)
                outputs.remove(s)
                n_users -= 1
                del user_connect_time[s]

        readable, writable, exceptional = select.select(
            inputs, outputs, inputs)

        for s in readable:

            ###
            ### Processing server connection requests
            ###
            if s is server:

                connection, client_addr = s.accept()
                connection.setblocking(0)

                if n_users < MAX_USR:

                    #ciphers[s] = None

                    public_key = ''
                    with open('rsa_public.pem', 'r') as public_key_file:
                        public_key = public_key_file.read()
                        public_key.replace("\n", "").replace("\r", "")
                    LNP.send(connection, public_key)  # send public key

                    time.sleep(.005)

                    LNP.send(connection, '', "ACCEPT")

                    #set up connnection variables
                    inputs.append(connection)
                    outputs.append(connection)
                    n_users += 1
                    user_connect_time[connection] = time.time()

                    if args.debug:
                        print("        SERVER: new connection from " +
                              str(client_addr))

                else:  #>100 users
                    LNP.send(connection, '', "FULL")
                    connection.close()

                    if args.debug:
                        print("        SERVER: connection from " +
                              str(client_addr) + " refused, server full")

###
### Processing client msgs
###
            else:

                msg_status = None
                if s in ciphers:
                    msg_status = LNP.recv(s, msg_buffers, recv_len, msg_len,
                                          ciphers[s])
                else:
                    msg_status = LNP.recv(s, msg_buffers, recv_len, msg_len,
                                          None)

                if msg_status == "MSG_CMPLT":

                    msg = LNP.get_msg_from_queue(s, msg_buffers, recv_len,
                                                 msg_len)

                    if args.debug:
                        print("        receieved " + str(msg) + " from " +
                              str(s.getpeername()))

                    if s not in symmetric_keys:
                        # decode symmetric key using server private key
                        enc_session_key = base64.b64decode(msg.encode())

                        private_key = RSA.import_key(
                            open("rsa_private.pem").read())
                        cipher_rsa = PKCS1_OAEP.new(private_key)
                        symmetric_key = cipher_rsa.decrypt(enc_session_key)
                        symmetric_keys[s] = symmetric_key

                        # make cipher and store it
                        tempkey = SHA.new(symmetric_key).digest()
                        cipher_server = ARC4.new(tempkey)
                        ciphers[s] = cipher_server

#Username exists for this client, this is a message
                    elif s in usernames:
                        pvt_user = is_private(msg, usernames)
                        msg = "> " + usernames[s] + ": " + msg
                        if pvt_user:
                            private_queue(msg, msg_queues, pvt_user, usernames)
                        else:
                            broadcast_queue(msg, msg_queues, exclude=[s])

                    elif s not in unverified_usernames:
                        unverified_usernames[s] = msg
                        LNP.send(s, '', "NEED-CERTIFICATE")

#no username yet, this message is a username
                    else:
                        username_status = is_username(unverified_usernames[s],
                                                      usernames, msg)

                        LNP.send(s, '', username_status)

                        if username_status == "USERNAME-ACCEPT":
                            usernames[s] = unverified_usernames[s]
                            del user_connect_time[s]
                            msg_queues[s] = queue.Queue()
                            msg = "User " + usernames[s] + " has joined"
                            print("        SERVER: " + msg)
                            broadcast_queue(msg, msg_queues)

                        else:  #invalid username
                            user_connect_time[s] = time.time()
                            msg = None
                            del unverified_usernames[s]

###
### Closing connection with client
###
                elif msg_status == "NO_MSG" or msg_status == "EXIT":

                    # if args.debug:
                    #     print("        SERVER: " + msg_status +
                    #           ": closing connection with " + str(s.getpeername()))

                    outputs.remove(s)
                    inputs.remove(s)
                    if s in writable:
                        writable.remove(s)
                    if s in msg_queues:
                        del msg_queues[s]

#load disconnect message into msg_queues
                    if s in usernames:
                        for sock in msg_queues:
                            msg_queues[sock].put("User " + usernames[s] +
                                                 " has left")
                        del usernames[s]

                    if s in user_connect_time:
                        del user_connect_time[s]

#If user sent disconnect message need to send one back
                    if msg_status == "EXIT":
                        LNP.send(s, '', "EXIT")

                    n_users -= 1
                    s.close()

        #Send messages to clients
        for s in writable:

            if s in msg_queues:

                try:
                    next_msg = msg_queues[s].get_nowait()

                except queue.Empty:
                    next_msg = None

                if next_msg:
                    if args.debug:
                        print("        sending " + next_msg + " to " +
                              str(s.getpeername()))
                    LNP.send(s, next_msg, None, ciphers[s])

        #Remove exceptional sockets from the server
        for s in exceptional:

            if args.debug:
                print("        SERVER: handling exceptional condition for " +
                      str(s.getpeername()))

            inputs.remove(s)
            #if s in outputs:
            outputs.remove(s)
            del msg_queues[s]
            del usernames[s]
            s.close()
Пример #42
0
def loadPrivateKey(path):
    private_key = RSA.import_key(open(path).read())
    return private_key
Пример #43
0
 def import_key(extern_key, passphrase=None):
     return RSA.import_key(extern_key, passphrase)
Пример #44
0
def loadPublicKey(path):
    receiver_key = RSA.import_key(open(path).read())
    return receiver_key
Пример #45
0
def cargar_RSAKey_Publica(fichero):
    keyFile = open(fichero, "rb").read()
    key_pub = RSA.import_key(keyFile)
    return key_pub
Пример #46
0
def get_user_public_key(public_key):
    key = RSA.import_key(b64decode(public_key.publickey))

    return key
Пример #47
0
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP

# https://pycryptodome.readthedocs.io/en/latest/src/examples.html#encrypt-data-with-aes
file_in = open("d6_encrypted_data.bin", "rb")

private_key = RSA.import_key(open("d3private.pem").read())

enc_session_key, nonce, tag, ciphertext = \
   [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]

# Decrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)

# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print('data=',data)
Пример #48
0
#!/usr/local/bin/python3.8
from Crypto.PublicKey import RSA

def sign(sk, m):
	mp, dq = m % sk.q, sk.d % (sk.q - 1)
	mq, dp = m % sk.p, sk.d % (sk.p - 1)
	s1 = pow(mq, dq, sk.q)
	s2 = pow(mp, dp, sk.p)
	h = (sk.u * (s1 - s2)) % sk.q
	s = (s2 + h * sk.p) % sk.n
	return s

if __name__ == "__main__":

	with open('sk.pem','r') as fp:
		sk = RSA.import_key(fp.read())

	while True:
		print("What do you want me to sign?")
		try:
			m = int(input(">>> "))
			print(sign(sk, m))
		except:
			break
Пример #49
0
def room_maker(room_socket, member_list, priv):
    members_data = {}
    room_socket.listen(len(member_list))
    for _ in member_list:
        try:
            member_socket, member_address = room_socket.accept()
            member = None
            while member is None:
                ready = select.select([member_socket], [], [])
                if ready[0]:
                    member = member_socket.recv(BUFSIZ).decode('ASCII')
            member_key = clients.get(member)[3]

            members_data[member] = [
                member_socket, member_key,
                threading.Lock()
            ]
        except ConnectionError:
            # Add cuando todos se desconectan cerrar
            print("Someone left a room. No connection with that user is set.")
        except:
            traceback.print_exc()
            continue
    exchanged = False
    try:
        exchange_keys(members_data)
        exchanged = True
    except:
        traceback.print_exc()

    while exchanged and len(members_data) > 1:
        try:
            res = [
                members_data.get(sub)[0] for sub in list(members_data.keys())
            ]
            ready = select.select(res, [], [], 5)
            if ready[0]:
                for writer in ready[0]:
                    for _ in range(len(member_list) - 1):
                        errorconn = writer
                        msg = writer.recv(BUFSIZ)
                        if len(msg) == 0:
                            raise ConnectionError
                        destination = msg.decode('ASCII')
                        ready = select.select([writer], [], [])
                        if ready[0]:
                            enc_msg = writer.recv(BUFSIZ)
                            # mac inicio
                            ready = select.select([writer], [], [])
                            if ready[0]:
                                tag = writer.recv(BUFSIZ)
                            # mac final
                            if len(enc_msg) == 0:
                                raise ConnectionError
                            broadcast(members_data, [destination],
                                      [enc_msg, tag])

        except (ConnectionError, ConnectionResetError):
            print("Someone left a room. Removing that user from list.")
            errorconn.close()
            for member in members_data:
                if errorconn in members_data[member]:
                    del members_data[member]
                    member_list.remove(member)
                    print(member + " left the room")
                    # broadcast(members_data, member_list, (member + " left the room").encode('ASCII'))
                    for m_remaining in members_data:
                        rem = members_data[m_remaining]
                        # print(rem)
                        # bye_msg = encrypt_message(RSA.import_key(rem[1]), (member + " left the room"))
                        remc = rem[0]
                        # ready = select.select([remc], [remc], [])
                        # if not ready[0] and ready[1]:
                        #     broadcast(members_data, [m_remaining], [bye_msg])
                        bye_msg = encrypt_message(RSA.import_key(rem[1]),
                                                  ("/*-*/s_l/*+*/" + member))
                        ready = select.select([remc], [remc], [])
                        if not ready[0] and ready[1]:
                            broadcast(members_data, [m_remaining], [bye_msg])
                    break
            # traceback.print_exc()
        except:
            traceback.print_exc()
            continue
    try:
        room_socket.close()
        raise Exception
    except:
        del members_data
        print("Room closed")
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP

code = 'nooneknows'

with open('/path/to/encrypted_data.bin', 'rb') as fobj:
    private_key = RSA.import_key(
        open('/path_to_private_key/my_rsa_key.pem').read(),
        passphrase=code)

    enc_session_key, nonce, tag, ciphertext = [ fobj.read(x)
                                                for x in (private_key.size_in_bytes(),
                                                16, 16, -1) ]

    cipher_rsa = PKCS1_OAEP.new(private_key)
    session_key = cipher_rsa.decrypt(enc_session_key)

    cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
    data = cipher_aes.decrypt_and_verify(ciphertext, tag)

print(data)