def test_rsa_provider_init_invalid_passphrase(self):
        private_key = RSA.generate(2048)
        public_key = private_key.publickey()
        passphrase = random_string(6)
        invalid_passphrase = random_string(8)

        with open('./rsa-test.private_key.pem', 'wb') as f:
            f.write(private_key.exportKey(passphrase=passphrase))

        with open('./rsa-test.public_key.pem', 'wb') as f:
            f.write(public_key.exportKey(passphrase=passphrase))

        self.assertRaises(ClientError,
                          LocalRsaProvider,
                          dir='./',
                          key='rsa-test',
                          passphrase=invalid_passphrase)
        silently_remove('./rsa-test.public_key.pem')
        silently_remove('./rsa-test.private_key.pem')

        private_key_str = RsaKey.exportKey(private_key, passphrase=passphrase)
        public_key_str = RsaKey.exportKey(public_key, passphrase=passphrase)

        self.assertRaises(ClientError,
                          RsaProvider,
                          key_pair={
                              'private_key': private_key_str,
                              'public_key': public_key_str
                          },
                          passphrase=invalid_passphrase)
Beispiel #2
0
    def pack(self,
             command: Union[str, bytes, bytearray],
             data: Union[str, bytes, bytearray],
             encrypt: bool,
             type_: int = 0,
             *,
             key: RSA.RsaKey = None) -> Packet:
        if not (isinstance(type_, int) and -1 < type_ < 256):
            raise ValueError('Unsupported type')

        if isinstance(command, (str, bytes, bytearray)):
            if isinstance(command, str):
                command = command.encode('utf8')
            elif isinstance(command, bytearray):
                command = bytes(command)
        else:
            raise ValueError('Unsupported command type')

        if isinstance(data, (str, bytes, bytearray)):
            if isinstance(data, str):
                data = data.encode('utf8')
            if isinstance(data, bytes):
                data = bytearray(data)

            if len(data) > 4294967295:
                raise ValueError('data max length is 4294967295 bytes')
        else:
            raise TypeError('Unsupported data type')

        if not key:
            pass
        elif key and not isinstance(key, RSA.RsaKey):
            raise TypeError('key must be RSA key')
        else:
            if not key.can_encrypt():
                raise KeyError('key can not encrypt data')

        if encrypt:
            cipher: PKCS1_OAEP.PKCS1OAEP_Cipher = PKCS1_OAEP.new(
                key if key else self.key, SHA3_256, randfunc=Random.new().read)
            chunk: int = 65535 if ((key.size_in_bytes() if key else self.key.size_in_bytes()) - 66) > 65535 else \
                (key.size_in_bytes() if key else self.key.size_in_bytes()) - 66
            encrypted = bytearray()

            for i in (data[i:i + chunk]
                      for i in range(0, data.__len__(), chunk)):
                encrypted.extend(cipher.encrypt(i))

        return Packet(
            Header(
                Flags(
                    type_, encrypt,
                    key.size_in_bytes()
                    if key else self.key.size_in_bytes() if encrypt else 0,
                    len(encrypted) if encrypt else len(data)), command,
                b'\x00' * 32), encrypted if encrypt else data)
Beispiel #3
0
def store_keys(privkey: RsaKey, pubkey: RsaKey):
    try:
        priv_file: BinaryIO = open(".config/rsa_private.key", "wb")
        pub_file: BinaryIO = open(".config/rsa_public.key", "wb")
        priv_file.write(privkey.export_key())
        pub_file.write(pubkey.export_key())
        priv_file.close()
        pub_file.close()
    except Exception as e:
        print(e)
        print("Cannot store keys in .config dir. Exiting...")
        raise SystemExit
Beispiel #4
0
def generate_dispatcher_input(
    my_bls_public_key: str,
    my_bls_public_key_shares: List[str],
    my_bls_private_key_shares: List[int],
    my_rsa_key: RsaKey,
    all_rsa_public_keys: List[str],
) -> Tuple[List[Dict[str, Any]], int]:
    """
    Generate dispatcher input data.
    """
    input_data = []
    my_rsa_public_key_ssh = my_rsa_key.publickey().export_key(
        "OpenSSH").decode("ascii")
    my_index = -1
    for i in range(len(all_rsa_public_keys)):
        recipient_rsa_public_key = RSA.import_key(all_rsa_public_keys[i])
        recipient_bls_private_key_share = my_bls_private_key_shares[i]

        if recipient_rsa_public_key == my_rsa_key.publickey():
            my_index = i
            continue

        encrypted_data = {
            "public_key": my_bls_public_key,
            "public_key_shares": my_bls_public_key_shares,
            "private_key_share": str(recipient_bls_private_key_share),
        }
        enc_session_key, nonce, tag, ciphertext = rsa_encrypt(
            recipient_public_key=recipient_rsa_public_key,
            data=json.dumps(encrypted_data),
        )
        signature = rsa_sign(my_rsa_key, ciphertext)

        input_data.append({
            "sender_rsa_public_key":
            my_rsa_public_key_ssh,
            "recipient_rsa_public_key":
            recipient_rsa_public_key.export_key("OpenSSH").decode("ascii"),
            "enc_session_key":
            enc_session_key.hex(),
            "ciphertext":
            ciphertext.hex(),
            "nonce":
            nonce.hex(),
            "tag":
            tag.hex(),
            "signature":
            signature.hex(),
        })

    return input_data, my_index
Beispiel #5
0
def decrypt_message(message: bytes, receiver_private_key: RsaKey) -> bytes:
    """
    Decrypts message, using the specified key to decrypt symmetric key firs
    :param message: message with the following structure: IV + encrypted symmetric key + encrypted message
    :param receiver_private_key: RsaKey to decrypt symmetric key
    :return: decrypted message
    """
    iv = message[:IV_LEN]
    enc_aes_key = message[IV_LEN:IV_LEN + receiver_private_key.size_in_bytes()]  # Assume encryption has been done with same key size
    enc_message = message[IV_LEN + receiver_private_key.size_in_bytes():]

    cipher_rsa = PKCS1_OAEP.new(receiver_private_key)
    aes_key = cipher_rsa.decrypt(enc_aes_key)

    cipher_aes = AES.new(aes_key, AES.MODE_CBC, iv)
    return unpad(cipher_aes.decrypt(enc_message), AES.block_size)  # Padding have to be removed
Beispiel #6
0
def proto_to_pubkey(key: RsaPubKey) -> RsaKey:
    """
    Reads an RsaPubKey proto message back into an RsaKey
    """
    n = int.from_bytes(key.modulus, 'big')
    e = int.from_bytes(key.pub_exponent, 'big')
    return RsaKey(n=n, e=e)
Beispiel #7
0
 def __init__(self, key: RSA.RsaKey = None):
     if not key:
         self.key = RSA.generate(4096, Random.new().read)
     elif key and isinstance(key, RSA.RsaKey) and key.has_private():
         self.key: RSA.RsaKey = key
     else:
         raise TypeError('key must be private RSA key')
Beispiel #8
0
def save_private_key(key: RSA.RsaKey, password):
    filename = os.getcwd() + "/keys/private_key/private_key.txt"
    key, vector = encrypt_key(key.exportKey(), password)
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "wb") as f:
        f.write(key)
        f.write(vector)
        f.close()
Beispiel #9
0
def verify_signature(message: bytes, sender_public_key: RsaKey) -> bytes:
    """
    Verifies if the message has a valid signature, raising SignatureNotAuthentic if not
    :param message: message to be verified
    :param sender_public_key: public key of the pretended sender
    :return: original message without signature if it is valid
    :raise: SignatureNotAuthentic if signature is not valid
    """
    signature = message[:sender_public_key.size_in_bytes()]  # Assume encryption has been done with same key size
    original_message = message[sender_public_key.size_in_bytes():]
    h = SHA256.new(original_message)
    verifier = pkcs1_15.new(sender_public_key)
    try:
        verifier.verify(h, signature)
        return original_message
    except ValueError:
        raise SignatureNotAuthentic
Beispiel #10
0
    def save_ssid_pk(self, ssid: str, ap_pk: RsaKey):
        """ Saves an SSID/public key pair to the station's memory

        Args:
            ssid (str):     The SSID to save
            ap_pk (RsaKey): The public key associated with the ssid
        """
        self.saved.add((ssid, ap_pk.exportKey()))
Beispiel #11
0
	def store_key(key: RsaKey, friendly_name: str = None):
		if not isinstance(key, RsaKey):
			raise ValueError('First argument must be an RsaKey!')

		name = friendly_name if friendly_name else str(uuid.uuid4())
		file_name = f'{paths.PATH_WALLETS}/{name}.der'
		os.makedirs(os.path.dirname(file_name), exist_ok=True)
		with open(file_name, 'wb+') as file:
			file.write(key.exportKey(format='DER'))
Beispiel #12
0
    def rsa_export_key(self, key_file: str, key: RSA.RsaKey) -> None:
        """Export RSA key to file

        Args:
            key_file (str): Path to RSA key file
            key (RSA.RsaKey): RSA key to export
        """
        key_file_obj = Path(key_file).resolve()
        key_file_obj.parent.mkdir(parents=True, exist_ok=True)
        with key_file_obj.open('wb') as f:
            f.write(key.export_key())
Beispiel #13
0
def get_http_authentication(private_key: RsaKey,
                            private_key_id: str) -> HTTPSignatureHeaderAuth:
    """
    Get HTTP signature authentication for a request.
    """
    key = private_key.exportKey()
    return HTTPSignatureHeaderAuth(
        headers=["(request-target)", "user-agent", "host", "date"],
        algorithm="rsa-sha256",
        key=key,
        key_id=private_key_id,
    )
Beispiel #14
0
    def write_pubkey(self, pubkey: RSA.RsaKey) -> None:
        """Write a pubkey to the endpoint."""

        print(f"Sending a pubkey to {self.endpoint_addr}")
        self._sock.sendall(
            Message.of(pubkey.export_key(), ContentType.BINARY).to_bytes())

        self._sent_pubkey = True

        if self._endpoint_pubkey is not None:
            self._connected = True

            print(f"Established connection to {self.endpoint_addr}")
def _decrypt_via_rsa_oaep(cipherdict: dict, key: RSA.RsaKey) -> bytes:
    """Decrypt a bytestring with PKCS#1 RSA OAEP (asymmetric algo).

    :param cipherdict: list of ciphertext chunks
    :param key: private RSA key

    :return: the decrypted bytestring"""
    _check_asymmetric_key_length_bits(key.size_in_bits())

    decipher = PKCS1_OAEP.new(key, hashAlgo=RSA_OAEP_HASHER)

    encrypted_chunks = cipherdict["digest_list"]

    decrypted_chunks = []
    for encrypted_chunk in encrypted_chunks:
        decrypted_chunk = decipher.decrypt(encrypted_chunk)
        decrypted_chunks.append(decrypted_chunk)
    return b"".join(decrypted_chunks)
Beispiel #16
0
def _encrypt_via_rsa_oaep(plaintext: bytes, key: RSA.RsaKey) -> dict:
    """Encrypt a bytestring with PKCS#1 RSA OAEP (asymmetric algo).

    :param plaintext: the bytes to cipher
    :param key: public RSA key

    :return: a dict with field `digest_list`, containing bytestring chunks of variable width."""
    _check_asymmetric_key_length_bits(key.size_in_bits())

    cipher = PKCS1_OAEP.new(key=key, hashAlgo=RSA_OAEP_HASHER)
    chunks = split_as_chunks(plaintext,
                             chunk_size=RSA_OAEP_CHUNKS_SIZE,
                             must_pad=False,
                             accept_incomplete_chunk=True)

    encrypted_chunks = []
    for chunk in chunks:
        encrypted_chunk = cipher.encrypt(chunk)
        encrypted_chunks.append(encrypted_chunk)
    return dict(digest_list=encrypted_chunks)
Beispiel #17
0
    def user_register(self, username: str, email: str, public_key: RsaKey):
        """
        Registers a new user
        :param username:
        :param email:
        :param public_key:
        :return: a dictionary with keys userID and ts
        """
        url = API.base_url + "/users/register"
        body = {
            "nombre": username,
            "email": email,
            "publicKey": public_key.export_key("PEM").decode()
        }

        response = requests.post(url, headers=self.header, json=body)
        parsed_response = json.loads(response.text)

        if response.status_code != 200:
            raise api_exceptions[parsed_response["error_code"]]

        return parsed_response
Beispiel #18
0
def decrypt(data: bytes, mode: EncryptionMode,
            rec_privkey: RSA.RsaKey) -> bytes:
    """Decrypt given bytes using a specified encryption mode and."""

    key_len = rec_privkey.size_in_bytes()
    enc_session_key = data[:key_len]
    cipher_rsa = PKCS1_OAEP.new(rec_privkey)

    if mode == EncryptionMode.ECB:
        iv = None
        ciphertext = data[key_len:]
    else:
        iv_end = key_len + AES.block_size
        iv = data[key_len:iv_end]
        ciphertext = data[iv_end:]

    try:
        session_key = cipher_rsa.decrypt(enc_session_key)
    except ValueError:
        session_key = os.urandom(16)

    cipher_aes = {
        EncryptionMode.ECB: AES.new(session_key, AES.MODE_ECB),
        EncryptionMode.CBC: AES.new(session_key, AES.MODE_CBC, cast(bytes,
                                                                    iv)),
        EncryptionMode.CFB: AES.new(session_key, AES.MODE_CFB, cast(bytes,
                                                                    iv)),
        EncryptionMode.OFB: AES.new(session_key, AES.MODE_OFB, cast(bytes,
                                                                    iv)),
    }[mode]

    try:
        data = unpad(cipher_aes.decrypt(ciphertext), AES.block_size)
    except ValueError:
        data = ("".join(
            random.SystemRandom().choice(string.printable)
            for _ in range(random.randint(5, 100)))).encode("utf-8")

    return data
Beispiel #19
0
    def unpack(self,
               raw: Union[bytes, bytearray],
               key: RSA.RsaKey = None) -> Packet:
        if isinstance(raw, (bytes, bytearray)):
            if isinstance(raw, bytes):
                raw = bytearray(raw)

            header: Header = self.unpack_header(raw[:HEADER_SIZE])

            if header.checksum != hashlib.blake2s(raw[HEADER_SIZE:]).digest():
                raise PacketError('Data is corrupted (Bad checksum)')

            if header.flags.encrypted:
                cipher: PKCS1_OAEP.PKCS1OAEP_Cipher = PKCS1_OAEP.new(
                    key if key and key.has_private() else self.key, SHA3_256)
                chunk: int = header.flags.cluster
                decrypted = bytearray()

                try:
                    for i in (raw[HEADER_SIZE:][i:i + chunk]
                              for i in range(0,
                                             raw.__len__() -
                                             HEADER_SIZE, chunk)):
                        decrypted.extend(cipher.decrypt(i))
                except ValueError:
                    raise DamageError(f'Encrypted data is damaged')

            header.flags.size = len(
                decrypted) if header.flags.encrypted else len(
                    raw[HEADER_SIZE:])

            return Packet(
                header,
                decrypted if header.flags.encrypted else raw[HEADER_SIZE:],
                bytes(raw[44:76]) if header.flags.encrypted else None)
        else:
            raise TypeError('Raw must be bytes or bytearray')
Beispiel #20
0
 def __add_host_key(self, new_key: RSA.RsaKey, hostname: str) -> None:
     self.acceptable_hosts.append(new_key)
     with open(f'{self.path}/{hostname}', 'w') as key_file:
         key_file.writelines(new_key.export_key(format='OpenSSH').decode('utf-8'))
Beispiel #21
0
    def __init__(self, private_key: RSA.RsaKey):
        super().__init__(private_key.public_key())

        # Override public key with private one
        self._rsa = private_key
Beispiel #22
0
 def _save_keypair(self, key: RSA.RsaKey) -> None:
     self._priv = key.exportKey("PEM")
     self._pub = key.publickey().exportKey("DER")
Beispiel #23
0
 def get_private_key(self, keys: RsaKey, passphrase: str) -> str:
     private_key = keys.exportKey(passphrase=passphrase,
                                  pkcs=self._pub_key_crypto_standard,
                                  protection=self._protection)
     return private_key.decode()
Beispiel #24
0
 def from_rsa_obj(cls, rsa: RSA.RsaKey):
     if not rsa.has_private():
         return XeCrypt_RSA(n=rsa._n, e=rsa._e)
     else:
         return XeCrypt_RSA(n=rsa._n, e=rsa._e, d=rsa._d, p=rsa._p, q=rsa._q, u=rsa._u)
Beispiel #25
0
 def get_public_key(keys: RsaKey) -> str:
     public_key = keys.publickey().exportKey()
     return public_key.decode()
Beispiel #26
0
def save_public_key(key: RSA.RsaKey):
    filename = os.getcwd() + "/keys/public_key/public_key.txt"
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "wb") as f:
        f.write(key.exportKey())
        f.close()
 def decrypt(self, key: RSA.RsaKey, cipher: bytes):
     c = bytes_to_long(cipher)
     m = str(key._decrypt(c) & 1)
     self.wfile.write(m.encode())
Beispiel #28
0
OSS_STS_KEY = os.getenv("OSS_TEST_STS_KEY")
OSS_STS_ARN = os.getenv("OSS_TEST_STS_ARN")

OSS_PAYER_UID = os.getenv("OSS_TEST_PAYER_UID")
OSS_PAYER_ID = os.getenv("OSS_TEST_PAYER_ACCESS_KEY_ID")
OSS_PAYER_SECRET = os.getenv("OSS_TEST_PAYER_ACCESS_KEY_SECRET")

OSS_INVENTORY_BUCKET_DESTINATION_ARN = os.getenv("OSS_TEST_RAM_ROLE_ARN")
OSS_INVENTORY_BUCKET_DESTINATION_ACCOUNT = os.getenv("OSS_TEST_RAM_UID")

OSS_AUTH_VERSION = None
OSS_TEST_AUTH_SERVER_HOST = os.getenv("OSS_TEST_AUTH_SERVER_HOST")

private_key = RSA.generate(1024)
public_key = private_key.publickey()
private_key_str = RsaKey.exportKey(private_key)
public_key_str = RsaKey.exportKey(public_key)
key_pair = {'private_key': private_key_str, 'public_key': public_key_str}

private_key_compact = '''-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCokfiAVXXf5ImFzKDw+XO/UByW6mse2QsIgz3ZwBtMNu59fR5z
ttSx+8fB7vR4CN3bTztrP9A6bjoN0FFnhlQ3vNJC5MFO1PByrE/MNd5AAfSVba93
I6sx8NSk5MzUCA4NJzAUqYOEWGtGBcom6kEF6MmR1EKib1Id8hpooY5xaQIDAQAB
AoGAOPUZgkNeEMinrw31U3b2JS5sepG6oDG2CKpPu8OtdZMaAkzEfVTJiVoJpP2Y
nPZiADhFW3e0ZAnak9BPsSsySRaSNmR465cG9tbqpXFKh9Rp/sCPo4Jq2n65yood
JBrnGr6/xhYvNa14sQ6xjjfSgRNBSXD1XXNF4kALwgZyCAECQQDV7t4bTx9FbEs5
36nAxPsPM6aACXaOkv6d9LXI7A0J8Zf42FeBV6RK0q7QG5iNNd1WJHSXIITUizVF
6aX5NnvFAkEAybeXNOwUvYtkgxF4s28s6gn11c5HZw4/a8vZm2tXXK/QfTQrJVXp
VwxmSr0FAajWAlcYN/fGkX1pWA041CKFVQJAG08ozzekeEpAuByTIOaEXgZr5MBQ
gBbHpgZNBl8Lsw9CJSQI15wGfv6yDiLXsH8FyC9TKs+d5Tv4Cvquk0efOQJAd9OC
lCKFs48hdyaiz9yEDsc57PdrvRFepVdj/gpGzD14mVerJbOiOF6aSV19ot27u4on
Beispiel #29
0
def parse_key(key: RSA.RsaKey) -> str:
    """Returns the string version of a RSA key"""

    return binascii.hexlify(key.exportKey(
        format='DER')).decode('ascii')
Beispiel #30
0
 def set_key(self, key: RsaKey):
     self.config["SecureBox"]["key"] = key.export_key("PEM").decode()