コード例 #1
0
def encryptDataWithPubKey(data, pubKeyFile=RSA_pubKeyFile, outFile=None):
    from Cryptodome.PublicKey   import RSA
    from Cryptodome.Random      import get_random_bytes
    from Cryptodome.Cipher      import AES, PKCS1_OAEP


    recipient_key   = RSA.import_key(open(pubKeyFile).read())
    session_key     = get_random_bytes(16)

        # Encrypt the session key with the public RSA key
    cipher_rsa      = PKCS1_OAEP.new(recipient_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)
    print ()
    print (ciphertext)
    print ()
    print (tag)
    print ()
    if outFile:
        file_out = open(outFile, "wb")
        file_out.write(cipher_rsa.encrypt(session_key))
        [ file_out.write(x) for x in (ciphertext.nonce, tag, ciphertext) ]
コード例 #2
0
    def set_active_user(self):

        try:
            self.current_chat_key = self.transport.key_request(
                self.current_chat)
            LOGGER.debug(f'Загружен открытый ключ для {self.current_chat}')
            if self.current_chat_key:
                self.encryptor = PKCS1_OAEP.new(
                    RSA.import_key(self.current_chat_key))
        except (OSError, json.JSONDecodeError):
            self.current_chat_key = None
            self.encryptor = None
            LOGGER.debug(f'Не удалось получить ключ для {self.current_chat}')

        # Если ключа нет то ошибка, что не удалось начать чат с пользователем
        if not self.current_chat_key:
            self.messages.warning(
                self, 'Ошибка',
                'Для выбранного пользователя нет ключа шифрования.')
            return

        # Ставим надпись и активируем кнопки
        self.label_new_message.setText(
            f'Введите сообщенние для {self.current_chat}:')
        self.btn_clear.setDisabled(False)
        self.btn_send.setDisabled(False)
        self.text_message.setDisabled(False)

        self.history_list_update()
コード例 #3
0
def encrypt(mensaje, clave_pub_r):
    """
        Nombre: encrypt
        Descripcion: Funcion que encripta un mensaje mediante la AES con modo de encadenamiento CBC.
            Para ello crea una clave simetrica y un vector de inicializacion aleatorios. Genera
            el sobre digital de la clave.
        Argumentos:
            -mensaje: mensaje a cifrar.
            -clave_pub_r: clave publica del receptor.
        Retorno: IV + sobre digital + mensaje cifrado
    """
    print("-> Encriptando el mensaje...", end="")
    # Cifrado simétrico: AES con modo de encadenamiento CBC,
    # con IV de 16 bytes, y longitud de clave de 256 bits.
    # Generamos una clave de 256 bits = 32 bytes
    iv = get_random_bytes(16)
    clave_s = get_random_bytes(32)
    cipher = AES.new(clave_s, AES.MODE_CBC, iv)
    # El mensaje tiene que ser multiplo del tamanio del bloque
    # (16 en AES) asi que añadimos padding
    mensaje_cifrado = cipher.encrypt(pad(mensaje, AES.block_size))

    # Obtenemos el sobre con OAEP
    # La clave es clave_pub_r y el mensaje es clave_s
    cipher = PKCS1_OAEP.new(clave_pub_r)
    try:
        sobre_digital = cipher.encrypt(clave_s)
        print("OK")
        return iv + sobre_digital + mensaje_cifrado
    except ValueError:
        print("Error al cifrar.")
        return None
コード例 #4
0
ファイル: auth.py プロジェクト: trenton42/salt
    def _encrypt_private(self, ret, dictkey, target):
        '''
        The server equivalent of ReqChannel.crypted_transfer_decode_dictentry
        '''
        # encrypt with a specific AES key
        pubfn = os.path.join(self.opts['pki_dir'],
                             'minions',
                             target)
        key = salt.crypt.Crypticle.generate_key_string()
        pcrypt = salt.crypt.Crypticle(
            self.opts,
            key)
        try:
            pub = salt.crypt.get_rsa_pub_key(pubfn)
        except (ValueError, IndexError, TypeError):
            return self.crypticle.dumps({})
        except IOError:
            log.error('AES key not found')
            return {'error': 'AES key not found'}

        pret = {}
        if not six.PY2:
            key = salt.utils.stringutils.to_bytes(key)
        if HAS_M2:
            pret['key'] = pub.public_encrypt(key, RSA.pkcs1_oaep_padding)
        else:
            cipher = PKCS1_OAEP.new(pub)
            pret['key'] = cipher.encrypt(key)
        pret[dictkey] = pcrypt.dumps(
            ret if ret is not False else {}
        )
        return pret
コード例 #5
0
ファイル: crypto.py プロジェクト: szatanszmatan/myrdp
    def encrypt(self, message):
        if isinstance(message, unicode):
            message = message.encode('utf8')

        cipher = PKCS1_OAEP.new(self.key)
        encryptedMessage = cipher.encrypt(message)
        return base64.b64encode(encryptedMessage)
コード例 #6
0
def decrypt(mensaje):
    """
        Nombre: decrypt
        Descripcion: Funcion que descifra un mensaje.
        Argumentos:
            -mensaje: mensaje cifrado y firmado
        Retorno: mensaje descifrado
    """
    # Obtenemos el vector de inicializacion y el sobre digital
    print("-> Descifrando fichero...", end="")
    iv = mensaje[0:16]
    sobre_digital = mensaje[16:16 + 256]

    # Obtenemos la clave privada del receptor
    f = open('clave.pem', 'r')
    clave_priv_r = RSA.import_key(f.read())
    f.close()

    # Obtenemos el sobre con OAEP
    cipher = PKCS1_OAEP.new(clave_priv_r)
    try:
        clave_s = cipher.decrypt(sobre_digital)
    except ValueError:
        print("Error: No es posible descifrar")
        return None

    # Desciframos y quitamos el pad
    cipher = AES.new(clave_s, AES.MODE_CBC, iv)
    mensaje_descifrado = unpad(cipher.decrypt(mensaje[16 + 256:]),
                               AES.block_size)

    print("OK")
    return mensaje_descifrado
コード例 #7
0
def get_RSA_cipher(keytype):
    ''' Helper to grab either of the two RSA keys as needed. Returns the cipher object and the size of the key.'''
    with open(f'key.{keytype}') as f:
        key = f.read()
    rsakey = RSA.importKey(key)
    # Returns an RSA cipher object and the size of the RSA key in bytes
    return (PKCS1_OAEP.new(rsakey), rsakey.size_in_bytes())
コード例 #8
0
def encrypt(message):
    publickey = open("public.pem", "rb")
    public_key = RSA.importKey(publickey.read())
    encryptor = PKCS1_OAEP.new(public_key)
    encrypted_data = encryptor.encrypt(message)
    print(encrypted_data)
    return encrypted_data
コード例 #9
0
def encrypt(msg, pubKey):
    encryptor = PKCS1_OAEP.new(pubKey)
    string = bytes(msg, encoding='utf-8')
    encrypted = encryptor.encrypt(string)
    encrypted = binascii.hexlify(encrypted)

    return encrypted
コード例 #10
0
ファイル: zeromq.py プロジェクト: MaximilianMeister/salt-2
 def crypted_transfer_decode_dictentry(self,
                                       load,
                                       dictkey=None,
                                       tries=3,
                                       timeout=60):
     if not self.auth.authenticated:
         # Return controle back to the caller, continue when authentication succeeds
         yield self.auth.authenticate()
     # Return control to the caller. When send() completes, resume by populating ret with the Future.result
     ret = yield self.message_client.send(
         self._package_load(self.auth.crypticle.dumps(load)),
         timeout=timeout,
         tries=tries,
     )
     key = self.auth.get_keys()
     cipher = PKCS1_OAEP.new(key)
     if 'key' not in ret:
         # Reauth in the case our key is deleted on the master side.
         yield self.auth.authenticate()
         ret = yield self.message_client.send(
             self._package_load(self.auth.crypticle.dumps(load)),
             timeout=timeout,
             tries=tries,
         )
     aes = cipher.decrypt(ret['key'])
     pcrypt = salt.crypt.Crypticle(self.opts, aes)
     data = pcrypt.loads(ret[dictkey])
     if six.PY3:
         data = salt.transport.frame.decode_embedded_strs(data)
     raise tornado.gen.Return(data)
コード例 #11
0
 def testEncryptDecrypt3(self):
     # Verify that OAEP supports labels
     pt = self.rng(35)
     xlabel = self.rng(22)
     cipher = PKCS.new(self.key1024, label=xlabel)
     ct = cipher.encrypt(pt)
     self.assertEqual(cipher.decrypt(ct), pt)
コード例 #12
0
ファイル: encryptor.py プロジェクト: retro-desert/Encryptor
    def crypt1(file):

        f = open(file, "rb")
        data = f.read()
        f.close()

        file_out = open(str(file) + ".bin", "wb")

        recipient_key = RSA.import_key(open(pubKey).read())
        session_key = get_random_bytes(16)

        cipher_rsa = PKCS1_OAEP.new(recipient_key)
        enc_session_key = cipher_rsa.encrypt(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 (enc_session_key, cipher_aes.nonce, tag, ciphertext)
        ]
        file_out.close()
        print("[+]" + file[len(directory) + 1:] + " ENCRYPT!")
        folder_size = os.path.getsize(file)
        os.remove(file)

        dir2 = cleanfile
        erase(+folder_size, dir2)
コード例 #13
0
def _encrypt_data(data, mode):
    recipient_key_path = os.path.join(os.pardir, "keys", "public",
                                      "receiver.pem")
    encrypted_file = tempfile.mktemp()

    recipient_key = RSA.import_key(open(recipient_key_path).read())
    session_key = get_random_bytes(16)

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

    # Encrypt the data with the AES session key
    cipher_aes = AES.new(session_key, mode)
    ciphertext = cipher_aes.encrypt(pad(data, AES.block_size))

    iv = cipher_aes.iv if mode != AES.MODE_ECB else get_random_bytes(16)
    with open(encrypted_file, "wb") as file_out:
        [
            file_out.write(x)
            for x in (enc_session_key, str(mode).encode(), iv, ciphertext)
        ]
        file_out.close()

    return encrypted_file
コード例 #14
0
def encrypt_key(key, public_key, write_to_file=True):
    encryptor = PKCS1_OAEP.new(public_key)
    encrypted_key = encryptor.encrypt(key)
    if write_to_file:
        with open('./keys/encrypted_key.aes', 'wb') as f:
            f.write(encrypted_key)
    return encrypted_key
コード例 #15
0
 def testEncryptDecrypt3(self):
         # Verify that OAEP supports labels
         pt = self.rng(35)
         xlabel = self.rng(22)
         cipher = PKCS.new(self.key1024, label=xlabel)
         ct = cipher.encrypt(pt)
         self.assertEqual(cipher.decrypt(ct), pt)
コード例 #16
0
    def set_active_user(self):
        '''Метод активации чата с собеседником.'''
        # Запрашиваем публичный ключ пользователя и создаём объект шифрования
        try:
            self.current_chat_key = self.transport.key_request(
                self.current_chat)
            logger.debug(f'Загружен открытый ключ для {self.current_chat}')
            if self.current_chat_key:
                self.encryptor = PKCS1_OAEP.new(
                    RSA.import_key(self.current_chat_key))
        except (OSError, json.JSONDecodeError):
            self.current_chat_key = None
            self.encryptor = None
            logger.debug(f'Не удалось получить ключ для {self.current_chat}')

        # Если ключа нет то ошибка, что не удалось начать чат с пользователем
        if not self.current_chat_key:
            self.messages.warning(
                self, 'Ошибка', 'Для выбранного пользователя нет ключа шифрования.')
            return

        # Ставим надпись и активируем кнопки
        self.ui.label_new_message.setText(
            f'Введите сообщенние для {self.current_chat}:')
        self.ui.btn_clear.setDisabled(False)
        self.ui.btn_send.setDisabled(False)
        self.ui.text_message.setDisabled(False)

        # Заполняем окно историю сообщений по требуемому пользователю.
        self.history_list_update()
コード例 #17
0
ファイル: jwe.py プロジェクト: techguy613/pyjwkest
    def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
        if padding == "pkcs1_padding":
            cipher = PKCS1_v1_5.new(key)
            if self.with_digest:
                dsize = SHA.digest_size
            else:
                dsize = 0
            sentinel = Random.new().read(32 + dsize)
            text = cipher.decrypt(ciphertext, sentinel)
            if dsize:
                _digest = text[-dsize:]
                _msg = text[:-dsize]
                digest = SHA.new(_msg).digest()
                if digest == _digest:
                    text = _msg
                else:
                    raise DecryptionFailed()
            else:
                if text == sentinel:
                    raise DecryptionFailed()
        elif padding == "pkcs1_oaep_padding":
            cipher = PKCS1_OAEP.new(key)
            text = cipher.decrypt(ciphertext)
        else:
            raise Exception("Unsupported padding")

        return text
コード例 #18
0
ファイル: auth.py プロジェクト: scutojr/salt
    def _encrypt_private(self, ret, dictkey, target):
        '''
        The server equivalent of ReqChannel.crypted_transfer_decode_dictentry
        '''
        # encrypt with a specific AES key
        pubfn = os.path.join(self.opts['pki_dir'], 'minions', target)
        key = salt.crypt.Crypticle.generate_key_string()
        pcrypt = salt.crypt.Crypticle(self.opts, key)
        try:
            with salt.utils.files.fopen(pubfn) as f:
                pub = RSA.importKey(f.read())
        except (ValueError, IndexError, TypeError):
            return self.crypticle.dumps({})
        except IOError:
            log.error('AES key not found')
            return {'error': 'AES key not found'}

        pret = {}
        cipher = PKCS1_OAEP.new(pub)
        if six.PY2:
            pret['key'] = cipher.encrypt(key)
        else:
            pret['key'] = cipher.encrypt(salt.utils.to_bytes(key))
        pret[dictkey] = pcrypt.dumps(ret if ret is not False else {})
        return pret
コード例 #19
0
def decrypt_file(private_key, src_file, dest_file):
    try:
        with open(src_file, "rb") as f:
            rsa_key = RSA.import_key(open(private_key).read())
            encrypted_session_key = f.read(rsa_key.size_in_bytes())
            nonce = f.read(16)
            tag = f.read(16)
            ciphertext = f.read(-1)

            # Decrypt session key
            cipher_rsa = PKCS1_OAEP.new(rsa_key)
            session_key = cipher_rsa.decrypt(encrypted_session_key)
            # Decrypt data
            cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
            data = cipher_aes.decrypt_and_verify(ciphertext, tag)
            data = data.decode("utf-8")
    except Exception as e:
        print("Unable to decrypt file: {}".format(src_file))
        raise e

    try:
        with open(dest_file, "w") as f:
            f.write(data)
    except Exception as e:
        print("Unable to write output file: {}".format(dest_file))
        raise e
コード例 #20
0
def decrypt_data(encrypted_file, access_key):
    private_dir = os.path.join(os.pardir, "keys", "private", "private.pem")
    private_key = RSA.import_key(open(private_dir).read(),
                                 passphrase=hash_access_key(access_key))

    with open(encrypted_file, "rb") as file_in:
        enc_session_key, mode, iv, ciphertext = \
            [file_in.read(x) for x in (private_key.size_in_bytes(), 1, 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)
    mode = int(mode.decode())
    # Decrypt the data with the AES session key
    if mode == AES.MODE_ECB:
        cipher_aes = AES.new(session_key, mode)
    else:
        cipher_aes = AES.new(session_key, mode, iv)
    data = unpad(cipher_aes.decrypt(ciphertext), AES.block_size)

    if os.path.basename(encrypted_file) == MESSAGE:
        messagebox.showinfo(title="Received a message",
                            message=f"New message:\n{data.decode()}")

    with open(encrypted_file, "wb") as decrypted_file:
        decrypted_file.write(data)
コード例 #21
0
ファイル: make_test_data.py プロジェクト: ngalongc/1password
def gen_sym_key(ekid, new_kid=None, iv=None, k=None):
    out = {'kid': ekid, 'cty': 'b5+jwk+json'}

    if new_kid != None:
        kid = new_kid
    else:
        kid = gen_uuid()

    if k != None:
        new_key = k
    else:
        new_key = get_random_bytes(32)

    key_dat = {
        'alg': 'A256GCM',
        'ext': True,
        'key_ops': ['decrypt', 'encrypt'],
        'kty': 'oct',
        'kid': kid
    }

    key_dat['k'] = optestlib.opb64e(new_key)

    key_dat_str = json.dumps(key_dat)
    optestlib.p_str("New symmetric key", json.dumps(key_dat, indent=4))

    sym_keys[kid] = new_key
    if ekid == 'mp':
        #        sym_keys['mk'] = new_key

        optestlib.p_debug('\n*** Encrypting sym key with AES kid %s' % ekid)
        iv, ct = optestlib.enc_aes_gcm(key_dat_str, sym_keys[ekid], iv=iv)

        optestlib.p_data('IV', iv, dump=False)
        optestlib.p_data('KEY', sym_keys[ekid], dump=False)
        optestlib.p_data('Ciphertext', ct, dump=False)

        out['iv'] = optestlib.opb64e(iv)
        out['data'] = optestlib.opb64e(ct)
        out['enc'] = 'A256GCM'

    else:  # only the primary sym_key is itself AES encrypted, rest by RSA
        optestlib.p_debug('\n*** Encrypting sym key with RSA kid %s\n' % ekid)

        jwkj = '{"keys": [%s]}' % json.dumps(pub_keys[ekid])
        jwk = load_jwks(jwkj)[0]
        optestlib.p_str('Public key e:', jwk.e)
        optestlib.p_str('Public key n:', jwk.n)
        RSA_Key = RSA.construct((jwk.n, jwk.e))

        C = PKCS1_OAEP.new(RSA_Key)
        ct = C.encrypt(key_dat_str)

        out['enc'] = 'RSA-OAEP'
        out['data'] = optestlib.opb64e(ct)
        optestlib.p_debug('')
        optestlib.p_data('RSA-OAEP ciphertext', ct, dump=False)

    return kid, out
コード例 #22
0
def encrypt(*args, **kwargs):
    """
    Encrypt a text file using a public key.
    The encryption is provided by `PyCryptodome`_.

    Args:
        *args: Input file[s].
        **kwargs: Optional Arbitrary keyword arguments.
            They might represent a RSA public key or the output file[s].

    Examples:
        The first argument is a list while the next argument can be both a
        string or a list, depending on the keyword.

        >>> encrypt(['egg.txt'], rsa_public_key='rsa.pub', output=['egg.bin'])

    .. _PyCryptodome:
        https://www.pycryptodome.org

    """
    rsa_public_key = kwargs.get('rsa_public_key')
    for file_input_plain in enumerate(args):
        filename, file_extension = os.path.splitext(file_input_plain[1])
        defout = filename + ".bin"  # Default output :)
        try:
            file_output = open(
                kwargs.get(
                    'output')[file_input_plain[0]] or defout, "wb")
        except IndexError as e:
            print("Did you provided more input files than output files?", e)
            output = input(
                'Enter the next output file[' + defout + ']: ') or defout
            file_output = open(output, "wb")
        except TypeError as e:
            print("Probably you didn't provided an output:", e)
            # The output file will be in the same directory of the input file.
            print("The output file will be " + defout)
            file_output = open(defout, "wb")

        # Get the public key
        recipient_key = RSA.import_key(open(rsa_public_key).read())

        # Generate the random password file
        session_key = get_random_bytes(16)

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

        # Get the data from a text file as byte strings
        file_in = open(file_input_plain[1], 'rb')
        data = b''.join([line for line in file_in])
        file_in.close()

        # 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_output.write(x) for x in (cipher_aes.nonce, tag, ciphertext)]
        file_output.close()
コード例 #23
0
ファイル: chat_client-cli.py プロジェクト: wolfyxk/PySecChat
def showmsg():
    full_msg = b''
    new_msg = True

    while 1:
        try:
            data = server.conn.recv(BUFFERSIZE)
        except:
            print(f'Connection Lost')
            server.conn = None
            break
        # If data is not empty
        if data:
            if new_msg:
                msgtype = data[:3].decode('utf-8')  # Type of message (MSG/PK)
                msglen = int(
                    data[4:HEADERLEN].decode('utf-8'))  # Length of message
                new_msg = False

            full_msg += data

            if len(full_msg) - HEADERLEN == msglen:

                # Uncomment the following line to see raw messages
                # print(str(full_msg))

                # If message is a public key
                if msgtype.strip(' ') == 'PK':
                    print(f'PubKey Recieved from server')
                    # Import public key string into RSA key object
                    srvpubkey = RSA.importKey(full_msg[HEADERLEN:])
                    encryptor = PKCS1_OAEP.new(srvpubkey)
                    server.pubkey = encryptor
                    print('Sending ENCTEST message to server')
                    server.conn.sendall(
                        setupMsg(
                            server.pubkey.encrypt('ENCTEST'.encode('utf-8'))))
                    time.sleep(0.5)
                    server.conn.sendall(setupPubKey(pubkeybytes))

                # If message is of MSG type
                elif msgtype.strip(' ') == 'MSG':
                    decrypted = clidecryptor.decrypt(
                        full_msg[HEADERLEN:]).decode('utf-8')

                    if server.rsaestablished is False:
                        if decrypted == 'ENCTEST':
                            server.rsaestablished = True
                            print(f'ENCTEST recieved from server')
                        else:
                            print(
                                f'Server encryption test failed, Disconnecting'
                            )
                            server.disconnect()
                    else:
                        print(f'{decrypted}')

                new_msg = True
                full_msg = b''
コード例 #24
0
def encryptDiffie(serverDHPublicKey, clientPublicRSA):
    # Instantiating RSA cipher
    RSACipher = PKCS1_OAEP.new(clientPublicRSA)
    # Encrypting client Diffle-Hellman public key with client RSA public key
    encryptedclientDHPublicKey = RSACipher.encrypt(
        str(serverDHPublicKey).encode())
    # Returning encrypted client Diffle-Hellman public key
    return encryptedclientDHPublicKey
コード例 #25
0
ファイル: blinder_send.py プロジェクト: xXNicolaXx/Incogn1to
def rsa_encryption(public_key_list):

    # Encrypt the AES key with the public RSA key
    dest_public_key = RSA.import_key(public_key_list)
    chypher_rsa = PKCS1_OAEP.new(dest_public_key)
    enc_session_key = chypher_rsa.encrypt(aes_key)

    return enc_session_key
コード例 #26
0
def generate_rsa(key, nonce_or_iv):
    rsa_key = RSA.import_key(key)
    cipher_rsa = PKCS1_OAEP.new(rsa_key)

    def do_computation(msg: bytes):
        cipher_rsa.encrypt(msg)

    return do_computation
コード例 #27
0
ファイル: crypto.py プロジェクト: whande1992/myrdp
 def decrypt(self, encryptedMessage):
     cipher = PKCS1_OAEP.new(self.key)
     if encryptedMessage is None:
         return None
     decryptedMessage = cipher.decrypt(base64.b64decode(encryptedMessage))
     if isinstance(decryptedMessage, (bytes, bytearray)):
         decryptedMessage = decryptedMessage.decode('utf8')
     return decryptedMessage
コード例 #28
0
def encriptar():
    mensaje = b"Nuevo mensaje secreto"
    key = RSA.importKey(open("llavepublica.pem", "rb").read())
    cifrado = PKCS1_OAEP.new(key)
    cifrarmensaje = cifrado.encrypt(mensaje)
    f = open("textoCifrado.txt", "wb")
    f.write(cifrarmensaje)
    f.close()
コード例 #29
0
 def testEncryptDecrypt1(self):
     # Encrypt/Decrypt messages of length [0..128-2*20-2]
     for pt_len in xrange(0, 128 - 2 * 20 - 2):
         pt = self.rng(pt_len)
         cipher = PKCS.new(self.key1024)
         ct = cipher.encrypt(pt)
         pt2 = cipher.decrypt(ct)
         self.assertEqual(pt, pt2)
コード例 #30
0
 def _init_keys(self, key_response_data):
     cipher = PKCS1_OAEP.new(self.rsa_key)
     encrypted_encryption_key = base64.standard_b64decode(
         key_response_data['keydata']['encryptionkey'])
     encrypted_sign_key = base64.standard_b64decode(
         key_response_data['keydata']['hmackey'])
     self.encryption_key = _decrypt_key(encrypted_encryption_key, cipher)
     self.sign_key = _decrypt_key(encrypted_sign_key, cipher)
コード例 #31
0
 def testEncryptDecrypt1(self):
         # Encrypt/Decrypt messages of length [0..128-2*20-2]
         for pt_len in xrange(0,128-2*20-2):
             pt = self.rng(pt_len)
             cipher = PKCS.new(self.key1024)
             ct = cipher.encrypt(pt)
             pt2 = cipher.decrypt(ct)
             self.assertEqual(pt,pt2)
コード例 #32
0
ファイル: xl_rsa.py プロジェクト: lei025/pyyyy
 def encrypt(self, data):
     """
     encrypted data by rsa
     :param data: Plaintext
     :return: Binary ciphertext
     """
     cipher_rsa = PKCS1_OAEP.new(self.key)
     return cipher_rsa.encrypt(data)
コード例 #33
0
ファイル: session_key.py プロジェクト: zemdom/aes-encryption
    def __init__(self, rsa_key):
        # keys are stored as byte string
        self.key_size = None
        self.session_key = None  # byte string
        self.encrypted_session_key = None  # byte string

        self.rsa_key = rsa_key  # byte string
        self.cipher = PKCS1_OAEP.new(RSA.import_key(self.rsa_key))
コード例 #34
0
	def encrypt(self,msg):

		# Encrypt the session key with the public RSA key
		cipher_rsa = PKCS1_OAEP.new(self.key_pair[1],hashAlgo=SHA256)
		encrypt_data = cipher_rsa.encrypt(msg)
		# msg = b64encode(msg)
		# encrypt_data = cipher_rsa.encrypt(msg)
		return encrypt_data
コード例 #35
0
def doRSA(message, keySize):

    # Encrypt
    encryptStart = time.time()
    RSA_key = RSA.generate(keySize)
    RSA_cipher = PKCS1_OAEP.new(RSA_key)
    RSA_ciphertext = RSA_cipher.encrypt(message.encode())
    encryptTime = time.time() - encryptStart

    # Decrypt
    decryptStart = time.time()
    RSA_cipher2 = PKCS1_OAEP.new(RSA_key)
    out = RSA_cipher2.decrypt(RSA_ciphertext).decode()
    #	print(out)
    decryptTime = time.time() - decryptStart

    return (encryptTime, decryptTime)
コード例 #36
0
 def testDecrypt1(self):
         # Verify decryption using all test vectors
         for test in self._testData:
                 # Build the key
                 comps = [ long(rws(test[0][x]),16) for x in ('n','e','d') ]
                 key = RSA.construct(comps)
                 # The real test
                 cipher = PKCS.new(key, test[4])
                 pt = cipher.decrypt(t2b(test[2]))
                 self.assertEqual(pt, t2b(test[1]))
コード例 #37
0
ファイル: jwe.py プロジェクト: techguy613/pyjwkest
 def encrypt(self, msg, key, padding="pkcs1_padding"):
     if padding == "pkcs1_padding":
         cipher = PKCS1_v1_5.new(key)
         if self.with_digest:  # add a SHA digest to the message
             h = SHA.new(msg)
             msg += h.digest()
     elif padding == "pkcs1_oaep_padding":
         cipher = PKCS1_OAEP.new(key)
     else:
         raise Exception("Unsupported padding")
     return cipher.encrypt(msg)
コード例 #38
0
ファイル: google.py プロジェクト: Geka000/gpsoauth
def signature(email, password, key):
    signature = bytearray(b'\x00')

    struct = key_to_struct(key)
    signature.extend(hashlib.sha1(struct).digest()[:4])

    cipher = PKCS1_OAEP.new(key)
    encrypted_login = cipher.encrypt((email + u'\x00' + password).encode('utf-8'))

    signature.extend(encrypted_login)

    return base64.urlsafe_b64encode(signature)
コード例 #39
0
 def testEncryptDecrypt4(self):
         # Verify that encrypt() uses the custom MGF
         global mgfcalls
         # Helper function to monitor what's requested from MGF
         def newMGF(seed,maskLen):
             global mgfcalls
             mgfcalls += 1
             return bchr(0x00)*maskLen
         mgfcalls = 0
         pt = self.rng(32)
         cipher = PKCS.new(self.key1024, mgfunc=newMGF)
         ct = cipher.encrypt(pt)
         self.assertEqual(mgfcalls, 2)
         self.assertEqual(cipher.decrypt(ct), pt)
コード例 #40
0
 def add_issuer_key(self, private_key):
     """
     Adds a private key to the list of keys available for decryption
     and signatures
     :return: Boolean - Whether the key is already in the list
     """
     new_key = RSAKey(key=import_rsa_key(private_key),
                      kid=self.__generate_key_id(private_key))
     for key in self.issuer_private_keys:
         if new_key.kid == key.kid:
             return False
     self.issuer_private_keys.append(new_key)
     self.loaded_issuer_private_keys[new_key.kid] = PKCS1_OAEP.new(
         RSA.importKey(private_key))
     return True
コード例 #41
0
    def parse_key_response(self, headerdata):
        # Init Decryption
        enc_key = headerdata['keyresponsedata']['keydata']['encryptionkey']
        hmac_key = headerdata['keyresponsedata']['keydata']['hmackey']
        encrypted_encryption_key = base64.standard_b64decode(enc_key)
        encrypted_sign_key = base64.standard_b64decode(hmac_key)
        cipher_rsa = PKCS1_OAEP.new(self.rsa_key)

        # Decrypt encryption key
        cipher_raw = cipher_rsa.decrypt(encrypted_encryption_key)
        encryption_key_data = json.JSONDecoder().decode(cipher_raw)
        self.encryption_key = self.__base64key_decode(encryption_key_data['k'])

        # Decrypt sign key
        sign_key_raw = cipher_rsa.decrypt(encrypted_sign_key)
        sign_key_data = json.JSONDecoder().decode(sign_key_raw)
        self.sign_key = self.__base64key_decode(sign_key_data['k'])
コード例 #42
0
 def testEncryptDecrypt2(self):
         # Helper function to monitor what's requested from RNG
         global asked
         def localRng(N):
             global asked
             asked += N
             return self.rng(N)
         # Verify that OAEP is friendly to all hashes
         for hashmod in (MD2,MD5,SHA1,SHA256,RIPEMD160):
             # Verify that encrypt() asks for as many random bytes
             # as the hash output size
             asked = 0
             pt = self.rng(40)
             cipher = PKCS.new(self.key1024, hashmod, randfunc=localRng)
             ct = cipher.encrypt(pt)
             self.assertEqual(cipher.decrypt(ct), pt)
             self.assertEqual(asked, hashmod.digest_size)
コード例 #43
0
ファイル: LnRSA_Class.py プロジェクト: Loreton/LnPythonLib
    def PKCS1_OAEP_AES_decrypt(self, data, inpFile):


        file_in = open(inpFile, "rb")

        private_key = self._privateKey

        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)


        return data
コード例 #44
0
 def testEncrypt1(self):
         # Verify encryption using all test vectors
         for test in self._testData:
                 # Build the key
                 comps = [ long(rws(test[0][x]),16) for x in ('n','e') ]
                 key = RSA.construct(comps)
                 # RNG that takes its random numbers from a pool given
                 # at initialization
                 class randGen:
                     def __init__(self, data):
                         self.data = data
                         self.idx = 0
                     def __call__(self, N):
                         r = self.data[self.idx:N]
                         self.idx += N
                         return r
                 # The real test
                 cipher = PKCS.new(key, test[4], randfunc=randGen(t2b(test[3])))
                 ct = cipher.encrypt(t2b(test[1]))
                 self.assertEqual(ct, t2b(test[2]))
コード例 #45
0
ファイル: LnRSA_Class.py プロジェクト: Loreton/LnPythonLib
    def PKCS1_OAEP_AES_encrypt(self, data, outFile):


            # recipient_key = Crypto.PublicKey.RSA.import_key(open("receiver.pem").read())
        recipient_key = self._privateKey
        session_key = Random.get_random_bytes(32)

            # Encrypt the session key with the public RSA key
        cipher_rsa = PKCS1_OAEP.new(recipient_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)

            # creazione del file con i dati crypted
        print ('file {FILE} has been created with encrypted data.'.format(FILE=outFile))
        file_out = open(outFile, "wb")
        file_out.write(cipher_rsa.encrypt(session_key))
        [ file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext) ]

        return ciphertext
コード例 #46
0
ファイル: crypto.py プロジェクト: szatanszmatan/myrdp
 def decrypt(self, encryptedMessage):
     cipher = PKCS1_OAEP.new(self.key)
     if encryptedMessage is None:
         return None
     decryptedMessage = cipher.decrypt(base64.b64decode(encryptedMessage))
     return decryptedMessage.decode('utf8')
コード例 #47
0
 def testMemoryview(self):
     pt = b("XER")
     cipher = PKCS.new(self.key1024)
     ct = cipher.encrypt(memoryview(bytearray(pt)))
     pt2 = cipher.decrypt(memoryview(bytearray(ct)))
     self.assertEqual(pt, pt2)
コード例 #48
0
 def testEncrypt2(self):
         # Verify that encryption fails if plaintext is too long
         pt = '\x00'*(128-2*20-2+1)
         cipher = PKCS.new(self.key1024)
         self.assertRaises(ValueError, cipher.encrypt, pt)
コード例 #49
0
 def testDecrypt2(self):
         # Simplest possible negative tests
         for ct_size in (127,128,129):
             cipher = PKCS.new(self.key1024)
             self.assertRaises(ValueError, cipher.decrypt, bchr(0x00)*ct_size)
コード例 #50
0
ファイル: LnRSA_Class.py プロジェクト: Loreton/LnPythonLib
    def encrypt_PKCS1_OAEP(self, message):
        key = self._publicKey
        cipher = PKCS1_OAEP.new(key)
        ciphertext = cipher.encrypt(message)

        return ciphertext
コード例 #51
0
    def test_lookup(self):

        engine = PlumberyEngine()
        self.assertEqual(engine.lookup('plumbery.version'), __version__)

        engine.secrets = {}
        random = engine.lookup('secret.random')
        self.assertEqual(len(random), 9)
        self.assertEqual(engine.lookup('secret.random'), random)

        md5 = engine.lookup('secret.random.md5')
        self.assertEqual(len(md5), 32)
        self.assertNotEqual(md5, random)

        sha = engine.lookup('secret.random.sha1')
        self.assertEqual(len(sha), 40)
        self.assertNotEqual(sha, random)

        sha = engine.lookup('secret.random.sha256')
        self.assertEqual(len(sha), 64)
        self.assertNotEqual(sha, random)

        id1 = engine.lookup('id1.uuid')
        self.assertEqual(len(id1), 36)
        self.assertEqual(engine.lookup('id1.uuid'), id1)
        id2 = engine.lookup('id2.uuid')
        self.assertEqual(len(id2), 36)
        self.assertNotEqual(id1, id2)

        engine.lookup('application.secret')
        engine.lookup('database.secret')
        engine.lookup('master.secret')
        engine.lookup('slave.secret')

        original = b'hello world'
        if HAS_CRYPTO:
            text = engine.lookup('pair1.rsa_public')
            self.assertTrue(ensure_string(text).startswith('ssh-rsa '))
            key = RSA.importKey(text)
            cipher = PKCS1_OAEP.new(key)
            encrypted = cipher.encrypt(original)

            privateKey = engine.lookup('pair1.rsa_private')
            self.assertTrue(ensure_string(privateKey).startswith(
                '-----BEGIN RSA PRIVATE KEY-----'))
            key = RSA.importKey(engine.lookup('pair1.rsa_private'))
            cipher = PKCS1_OAEP.new(key)
            decrypted = cipher.decrypt(encrypted)
            self.assertEqual(decrypted, original)

            token = engine.lookup('https://discovery.etcd.io/new')
            self.assertEqual(token.startswith(
                'https://discovery.etcd.io/'), True)
            self.assertEqual(len(token), 58)

            self.assertEqual(len(engine.secrets), 13)

            with self.assertRaises(LookupError):
                localKey = engine.lookup('local.rsa_private')

            localKey = engine.lookup('rsa_public.local')
            try:
                path = '~/.ssh/id_rsa.pub'
                with open(os.path.expanduser(path)) as stream:
                    text = stream.read()
                    stream.close()
                    self.assertEqual(localKey.strip(), text.strip())
                    plogging.info("Successful lookup of local public key")

            except IOError:
                pass
コード例 #52
0
ファイル: LnRSA_Class.py プロジェクト: Loreton/LnPythonLib
    def decrypt_PKCS1_OAEP(self, ciphertext):
        key = self._privateKey
        cipher = PKCS1_OAEP.new(key)
        message = cipher.decrypt(ciphertext)

        return message