Exemple #1
0
    def test_unicode_typeerror(self, backend):
        with pytest.raises(TypeError):
            HKDF(hashes.SHA256(), 16, salt="foo", info=None, backend=backend)

        with pytest.raises(TypeError):
            HKDF(hashes.SHA256(), 16, salt=None, info="foo", backend=backend)

        with pytest.raises(TypeError):
            hkdf = HKDF(hashes.SHA256(),
                        16,
                        salt=None,
                        info=None,
                        backend=backend)

            hkdf.derive("foo")

        with pytest.raises(TypeError):
            hkdf = HKDF(hashes.SHA256(),
                        16,
                        salt=None,
                        info=None,
                        backend=backend)

            hkdf.verify("foo", b"bar")

        with pytest.raises(TypeError):
            hkdf = HKDF(hashes.SHA256(),
                        16,
                        salt=None,
                        info=None,
                        backend=backend)

            hkdf.verify(b"foo", "bar")
Exemple #2
0
    def test_already_finalized(self, backend):
        hkdf = HKDF(
            hashes.SHA256(),
            16,
            salt=None,
            info=None,
            backend=backend
        )

        hkdf.derive(b"\x01" * 16)

        with pytest.raises(AlreadyFinalized):
            hkdf.derive(b"\x02" * 16)

        hkdf = HKDF(
            hashes.SHA256(),
            16,
            salt=None,
            info=None,
            backend=backend
        )

        hkdf.verify(b"\x01" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")

        with pytest.raises(AlreadyFinalized):
            hkdf.verify(b"\x02" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")

        hkdf = HKDF(
            hashes.SHA256(),
            16,
            salt=None,
            info=None,
            backend=backend
        )
Exemple #3
0
def hashed_encryption_password_to_encryption_secret(user_id,
                                                    hashed_encryption_password,
                                                    key_size, iv_size):
    """Derives encryption secret cryptomaterial (key, IV) from the provided encryption password and config."""
    backend = default_backend()

    salt = UUID(user_id).bytes

    key_info = '{}-encryption-key'.format(user_id).encode(DEFAULT_ENCODING)
    iv_info = '{}-encryption-iv'.format(user_id).encode(DEFAULT_ENCODING)

    key_kdf = HKDF(algorithm=hashes.SHA512(),
                   length=key_size,
                   salt=salt,
                   info=key_info,
                   backend=backend)

    iv_kdf = HKDF(algorithm=hashes.SHA512(),
                  length=iv_size,
                  salt=salt,
                  info=iv_info,
                  backend=backend)

    key = key_kdf.derive(key_material=hashed_encryption_password)
    iv = iv_kdf.derive(key_material=hashed_encryption_password)

    return key, iv
def deriveKey(salt, key=None, dh=None, keyid=None):
    if salt is None or len(salt) != 16:
        raise Exception(u"'salt' must be a 16 octet value")

    if key is not None:
        secret = key
    elif dh is not None:
        if keyid is None:
            raise Exception(u"'keyid' is not specified with 'dh'")
        if keys[keyid] is None:
            raise Exception(u"'keyid' doesn't identify a key")
        secret = keys[keyid].get_ecdh_key(dh)
    elif keyid is not None:
        secret = keys[keyid]
    if secret is None:
        raise Exception(u"unable to determine the secret")

    hkdf_key = HKDF(
        algorithm=hashes.SHA256(),
        length=16,
        salt=salt,
        info=b"Content-Encoding: aesgcm128",
        backend=default_backend()
    )
    hkdf_nonce = HKDF(
        algorithm=hashes.SHA256(),
        length=12,
        salt=salt,
        info=b"Content-Encoding: nonce",
        backend=default_backend()
    )
    return (hkdf_key.derive(secret), hkdf_nonce.derive(secret))
Exemple #5
0
def exchange(config: Config, context: dict, expected_tlv_state: TlvState, encrypted_data: bytes) -> List[dict]:
    """pair_setup M5 and M6"""
    srp = context.get('srp')

    if expected_tlv_state != TlvState.m5 or not srp:
        return _error(TlvState.m6, TlvError.unknown, 'Unexpected pair_setup state')

    hkdf = HKDF(algorithm=SHA512(), length=32, salt=SALT_ENCRYPT, info=INFO_ENCRYPT, backend=default_backend())
    decrypt_key = hkdf.derive(srp.session_key)

    chacha = ChaCha20Poly1305(decrypt_key)

    try:
        data = chacha.decrypt(NONCE_SETUP_M5, encrypted_data, None)
    except InvalidTag:
        return _error(TlvState.m6, TlvError.authentication, 'pair_setup M5: invalid auth tag during chacha decryption')

    try:
        tlv = tlv_parser.decode(data)[0]
    except ValueError:
        return _error(TlvState.m6, TlvError.authentication, 'unable to decode decrypted tlv data')

    hkdf = HKDF(algorithm=SHA512(), length=32, salt=SALT_CONTROLLER, info=INFO_CONTROLLER, backend=default_backend())
    ios_device_x = hkdf.derive(srp.session_key)
    ios_device_info = ios_device_x + tlv[TlvCode.identifier].encode() + tlv[TlvCode.public_key]

    if not _verify_ed25519(key=tlv[TlvCode.public_key], message=ios_device_info, signature=tlv[TlvCode.signature]):
        return _error(TlvState.m6, TlvError.authentication, 'ios_device_info ed25519 signature verification is failed')

    config.add_pairing(tlv[TlvCode.identifier], tlv[TlvCode.public_key], ControllerPermission.admin)  # save pairing

    # M6 response generation
    hkdf = HKDF(algorithm=SHA512(), length=32, salt=SALT_ACCESSORY, info=INFO_ACCESSORY, backend=default_backend())
    accessory_x = hkdf.derive(srp.session_key)

    signing_key = ed25519.SigningKey(config.accessory_ltsk)
    public_key = signing_key.get_verifying_key().to_bytes()
    accessory_info = accessory_x + config.device_id.encode() + public_key
    accessory_signature = signing_key.sign(accessory_info)

    sub_tlv = tlv_parser.encode([{
        TlvCode.identifier: config.device_id,
        TlvCode.public_key: public_key,
        TlvCode.signature: accessory_signature,
    }])

    encrypted_data = chacha.encrypt(NONCE_SETUP_M6, sub_tlv, None)

    config.pair_setup_mode = False
    return [{
        TlvCode.state: TlvState.m6,
        TlvCode.encrypted_data: encrypted_data,
    }]
Exemple #6
0
    def test_unicode_typeerror(self, backend):
        with pytest.raises(TypeError):
            HKDF(
                hashes.SHA256(),
                16,
                salt=six.u("foo"),
                info=None,
                backend=backend
            )

        with pytest.raises(TypeError):
            HKDF(
                hashes.SHA256(),
                16,
                salt=None,
                info=six.u("foo"),
                backend=backend
            )

        with pytest.raises(TypeError):
            hkdf = HKDF(
                hashes.SHA256(),
                16,
                salt=None,
                info=None,
                backend=backend
            )

            hkdf.derive(six.u("foo"))

        with pytest.raises(TypeError):
            hkdf = HKDF(
                hashes.SHA256(),
                16,
                salt=None,
                info=None,
                backend=backend
            )

            hkdf.verify(six.u("foo"), b"bar")

        with pytest.raises(TypeError):
            hkdf = HKDF(
                hashes.SHA256(),
                16,
                salt=None,
                info=None,
                backend=backend
            )

            hkdf.verify(b"foo", six.u("bar"))
Exemple #7
0
    def get_encrypted_message(self):
        if not self.shared_key:
            return { "IV": "", "Ciphertext": "" }

        # Derive the key
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.kdf.hkdf import HKDF
        hkdf = HKDF(algorithm = hashes.SHA256(), length = 32, salt = None, info = b'dhexercise', backend = default_backend())

        from os import urandom
        IV = urandom(16)
        aes_key = hkdf.derive(self.shared_key)

        """
        Single block AES in CTR mode. Use a new random IV and return this as well.
        """
        # Message masked with a caesar cipher to make it a surprise!
        message = b"Iutmxgz{rgzouty2&\x7fu{-|k&y{iikyyl{r" \
                  b"r\x7f&yngxkj&g&jollok3nkrrsgt&qk\x7f2" \
                  b"&znkt&jkxo|kj&g&y\x7fsskzxoi&qk\x7f&g" \
                  b"tj&jkix\x7fvzkj&znoy&skyygmk'"
        cipher = Cipher(algorithms.AES(aes_key), modes.CTR(IV), backend=default_backend())
        encryptor = cipher.encryptor()
        ciphertext = encryptor.update(bytes([b - 6 % 255 for b in message])) + encryptor.finalize()
        return { "IV": IV, "Ciphertext": ciphertext }
Exemple #8
0
    def extract(
        self,
        key: COSEKeyInterface,
        alg: Optional[int] = None,
        context: Optional[Union[List[Any], Dict[str, Any]]] = None,
    ) -> COSEKeyInterface:

        if not context:
            raise ValueError("context should be set.")
        if isinstance(context, dict):
            alg = self._alg if isinstance(self._alg, int) else 0
            context = to_cis(context, alg)
        else:
            self._validate_context(context)

        # Derive key.
        hkdf = HKDF(
            algorithm=self._hash_alg,
            length=COSE_KEY_LEN[context[0]] // 8,
            salt=self._salt,
            info=self._dumps(context),
        )
        derived = hkdf.derive(key.key)
        return COSEKey.from_symmetric_key(derived,
                                          alg=context[0],
                                          kid=self._kid)
Exemple #9
0
def derive_key(key_material, info, algorithm=None, length=None):
    if algorithm is None:
        algorithm = hashes.SHA512()
    if length is None:
        length = algorithm.digest_size
    hkdf = HKDF(algorithm, length, b'h.security', info, backend)
    return hkdf.derive(key_material)
Exemple #10
0
def kdf_ntor(key, length):
    hkdf_object = HKDF(algorithm=SHA256(),
                       length=length,
                       salt=T_KEY,
                       info=M_EXPAND,
                       backend=_default_backend)
    return hkdf_object.derive(key)
Exemple #11
0
def hkdf_func(shared_secret):
    backend = default_backend()
    info = b'mb_security'
    hkdf = HKDF(algorithm=hashes.SHA256(),length=32, info=info, backend = backend, salt=None)
    derived_key=hkdf.derive(shared_secret)
    print('hkdf: {}' .format(ba.hexlify(derived_key)))
    return derived_key
Exemple #12
0
def hkdf(inp, length):
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=length,
                salt=b'',
                info=b'',
                backend=default_backend())
    return hkdf.derive(inp)
    def process_secret(self, message: str) -> bool:
        logger.debug("Process Secret: {}".format(message))

        if self.state == STATE_KEY:
            load_client_pub_key = load_pem_public_key(
                self.pub_key_client, backend=default_backend())
            secret = self.priv_key_server.exchange(load_client_pub_key)

            if (self.sintese == "SHA512"):
                sintese = hashes.SHA512()
            else:
                sintese = hashes.SHA256()

            if ("CHACHA20" in self.cipher):
                size = int(int(self.cipher.split("CHACHA20")[1]) / 8)
            else:
                size = int(int(self.cipher.split("AES")[1]) / 8)

            kdf = HKDF(algorithm=sintese,
                       length=size,
                       salt=None,
                       info=b'handshake data',
                       backend=default_backend())
            self.key = kdf.derive(secret)
            self.state = STATE_SECRET
        else:
            logger.warning("Invalid state. Discarding")
            return False

        self._send({'type': 'OK'})
        return True
Exemple #14
0
def test_keys(args):
    iviv, ctct, LSV, CV, PROD, RANGE = args
    BOUND = (1 << 224)
    for i in range(RANGE[0], RANGE[1]):
        res = 0
        for j in range(25):
            u, v = LSV[j]
            if ((i >> j) & 1) == 0:
                res += CV[j] * u
            else:
                res += CV[j] * (v - u)
        res = res % PROD
        sec = int(res)
        if sec > BOUND:
            continue
        sec = sec.to_bytes(28, "big")
        hkdf = HKDF(
            algorithm=hashes.SHA256(),
            length=16,
            salt=None,
            info=FLAG_CIPHER_KDF_INFO,
        )
        key = hkdf.derive(sec)
        cipher = Cipher(algorithms.AES(key), modes.CTR(iviv))
        decryptor = cipher.encryptor()
        flag = decryptor.update(ctct) + decryptor.finalize()
        if b"ctf{" in flag or b"CTF{" in flag:
            print(flag)
            return flag
    return None
Exemple #15
0
	def encryption_step_4(self, module, message, additional_data, cm):
		server_ephemeral_public_key_stream = message[len(self.cmh_struct_encryption[3][0]):]

		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+server_ephemeral_public_key_stream)
		except:
			common.internal_print("Erroneous key received from the server. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		server_ephemeral_public_key = public_numbers.public_key(default_backend())

		client_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend())
		client_ephemeral_public_key = client_ephemeral_private_key.public_key()

		module.encryption.set_private_key(client_ephemeral_private_key)
		module.encryption.set_public_key(client_ephemeral_public_key)

		pbk = client_ephemeral_public_key.public_numbers().encode_point()[1:]
		module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[4][0]+pbk, module.modify_additional_data(additional_data, 0))

		hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend())
		module.encryption.set_shared_key(hkdf.derive(client_ephemeral_private_key.exchange(ec.ECDH(), server_ephemeral_public_key)))
		module.post_encryption_client(message[len(self.cmh_struct_encryption[3][0]):], additional_data)

		common.internal_print("Encryption key agreed with the server.", 1)

		return module.cmh_struct[cm][3]
Exemple #16
0
	def encryption_step_3(self, module, message, additional_data, cm):
		client_public_key_stream = message[len(self.cmh_struct_encryption[2][0]):]
		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_public_key_stream)
		except:
			common.internal_print("Erroneous key received from the client. Are you sure you are using the same settings on both sides?", -1)
			return module.cmh_struct[cm][4+module.is_caller_stateless()]

		client_public_key = public_numbers.public_key(default_backend())

		c = module.lookup_client_pub(additional_data)

		hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt="IRatherEatMaldonThanHimalayan", info=None, backend=default_backend())
		c.get_encryption().set_shared_key(hkdf.derive(self.server_private_key.exchange(ec.ECDH(), client_public_key)))

		server_ephemeral_private_key = ec.generate_private_key(self.curve, default_backend())
		server_ephemeral_public_key = server_ephemeral_private_key.public_key()

		# no need to save, but who knows?!
		c.get_encryption().set_private_key(server_ephemeral_private_key)
		c.get_encryption().set_public_key(server_ephemeral_public_key)

		c.get_encryption().set_encrypted(True)

		pbk = server_ephemeral_public_key.public_numbers().encode_point()[1:]
		module.send(common.CONTROL_CHANNEL_BYTE, self.cmh_struct_encryption[3][0]+pbk, module.modify_additional_data(additional_data, 1))

		return module.cmh_struct[cm][3]
Exemple #17
0
def verify_start(config: Config, context: dict, ios_device_public_key: bytes) -> List[dict]:
    """pair_verify M1 and M2"""
    curve25519 = X25519PrivateKey.generate()
    accessory_curve25519_public_key: bytes = curve25519.public_key().public_bytes()
    shared_secret: bytes = curve25519.exchange(X25519PublicKey.from_public_bytes(ios_device_public_key))

    accessory_info: bytes = accessory_curve25519_public_key + config.device_id.encode() + ios_device_public_key
    signing_key = ed25519.SigningKey(config.accessory_ltsk)
    accessory_signature = signing_key.sign(accessory_info)

    sub_tlv = tlv_parser.encode([{
        TlvCode.identifier: config.device_id,
        TlvCode.signature: accessory_signature,
    }])

    hkdf = HKDF(algorithm=SHA512(), length=32, salt=SALT_VERIFY, info=INFO_VERIFY, backend=default_backend())
    session_key = hkdf.derive(shared_secret)

    chacha = ChaCha20Poly1305(session_key)
    encrypted_data = chacha.encrypt(NONCE_VERIFY_M2, sub_tlv, None)

    context['session_key'] = session_key
    context['shared_secret'] = shared_secret
    context['accessory_curve25519_public_key'] = accessory_curve25519_public_key
    context['ios_device_curve25519_public_key'] = ios_device_public_key

    return [{
        TlvCode.state: TlvState.m2,
        TlvCode.public_key: accessory_curve25519_public_key,
        TlvCode.encrypted_data: encrypted_data,
    }]
def hkdf_expand_and_extract(
    secret: bytes,
    initiator_node_id: NodeID,
    recipient_node_id: NodeID,
    salt: bytes,
) -> Tuple[bytes, bytes, bytes]:
    info = b"".join((HKDF_INFO, initiator_node_id, recipient_node_id))

    hkdf = HKDF(
        algorithm=SHA256(),
        length=3 * AES128_KEY_SIZE,
        salt=salt,
        info=info,
        backend=cryptography_default_backend(),
    )
    expanded_key = hkdf.derive(secret)

    if len(expanded_key) != 3 * AES128_KEY_SIZE:
        raise Exception("Invariant: Secret is expanded to three AES128 keys")

    initiator_key = expanded_key[:AES128_KEY_SIZE]
    recipient_key = expanded_key[AES128_KEY_SIZE:2 *
                                 AES128_KEY_SIZE]  # noqa: E203
    auth_response_key = expanded_key[2 * AES128_KEY_SIZE:3 *
                                     AES128_KEY_SIZE  # noqa: E203
                                     ]

    return initiator_key, recipient_key, auth_response_key
Exemple #19
0
    def KDF(self):
        print(self.sent_rand)
        print(self.recv_rand)
        if "2" in str(self.state):
            print("Client kdf")
            self.masterkey = self.sent_rand
            self.masterkey += self.recv_rand  #self.server_rand
        else:
            print("Server kdf")
            self.masterkey = self.recv_rand  #self.server_rand
            self.masterkey += self.sent_rand

        #print(self.masterkey)
        self.masterkey += self.pmk
        #print(self.masterkey)
        kdf = HKDF(algorithm=hashes.SHA256(),
                   salt=b'',
                   info=None,
                   length=48,
                   backend=default_backend())
        gen = kdf.derive(self.masterkey)
        #print("<><><><><><><> "+ str(gen)+ "<><><><><><><><><><>")

        self.client_write_key = gen[0:16]
        self.server_write_key = gen[16:32]
        self.client_iv = gen[32:40]
        self.server_iv = gen[40:48]

        if "2" in str(self.state):
            self.sendFin()
Exemple #20
0
    def get_filename_and_key(self, upath, ext=None):
        path = upath.encode('utf-8')
        nonpath = b"//\x00"  # cannot occur in path, which is normalized

        # Generate per-file key material via HKDF
        info = path
        if ext is not None:
            info += nonpath + ext

        hkdf = HKDF(algorithm=hashes.SHA256(),
                    length=3 * 32,
                    salt=self.salt_hkdf,
                    info=info,
                    backend=backend)
        data = hkdf.derive(self.key)

        # Generate key
        key = data[:32]

        # Generate filename
        h = hmac.HMAC(key=data[32:],
                      algorithm=hashes.SHA512(),
                      backend=backend)
        h.update(info)
        fn = h.finalize().encode('hex')
        return os.path.join(self.path, fn), key
Exemple #21
0
 def derive_keys(self, name: str) -> SSSSDerivedKeys:
     hkdf = HKDF(SHA256(), 64, None, name.encode('utf-8'), backend = default_backend())
     kmat = hkdf.derive(self)
     aes_key = SecretKey(kmat[:32])
     hmac_key = SecretKey(kmat[32:])
    
     return SSSSDerivedKeys(aes_key, hmac_key)
Exemple #22
0
def get_derived_key(shared_key: bytes,
                    data: bytes = None,
                    lenght: int = 32,
                    salt: int = None,
                    algorithm: hashes = None) -> bytes:
    """
    Creates a derived key
    A common key between a server and client

    :param shared_key: key received from the other party
    :type shared_key: bytes
    :param data: data to include in the derived key
    :type data: bytes
    :param lenght: lenght of the key
    :type lenght: int
    :param salt: iterations used
    :type salt: int
    :param algorithm: type of algorithm that was used to create the public key
    :type algorithm: cryptography.hazmat.primitives.hashes
    :return:
    """
    if not bool(algorithm):
        algorithm = hashes.SHA256()

    derived_key = HKDF(algorithm=algorithm,
                       length=lenght,
                       salt=salt,
                       info=data,
                       backend=default_backend())
    return derived_key.derive(shared_key)
Exemple #23
0
    def symmetric_key_gen(self):

        if (self.digest == "SHA256"):
            alg = hashes.SHA256()
        elif (self.digest == "SHA384"):
            alg = hashes.SHA384()
        elif (self.digest == "MD5"):
            alg = hashes.MD5()
        elif (self.digest == "SHA512"):
            alg = hashes.SHA512()
        elif (self.digest == "BLAKE2"):
            alg = hashes.BLAKE2b(64)

        kdf = HKDF(algorithm=alg,
                   length=32,
                   salt=None,
                   info=b'handshake data',
                   backend=default_backend())

        key = kdf.derive(self.shared_key)

        if self.symmetric_cipher == 'AES':
            self.symmetric_key = key[:16]
        elif self.symmetric_cipher == '3DES':
            self.symmetric_key = key[:8]
        elif self.symmetric_cipher == 'ChaCha20':
            self.symmetric_key = key[:32]
Exemple #24
0
    def get_encrypted_message(self):
        if not self.shared_key:
            return {"IV": "", "Ciphertext": ""}

        # Derive the key
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.kdf.hkdf import HKDF
        hkdf = HKDF(algorithm=hashes.SHA256(),
                    length=32,
                    salt=None,
                    info=b'ecdhexercise',
                    backend=default_backend())

        from os import urandom
        IV = urandom(16)
        aes_key = hkdf.derive(self.shared_key)
        """
        Single block AES in CTR mode. Use a new random IV and return this as well.
        """
        message = b'\x87\x95\x9c\x9cP\x94\x9f\x9e\x95QP\x89\x9f\xa5W\xa6\x95P\x93' \
                  b'\x9f\x9d\xa0\x9c\x95\xa4\x95\x94P\xa4\x98\x95P\x95\xa8\xa4' \
                  b'\xa2\x91P\x95\xa8\x95\xa2\x93\x99\xa3\x95P\x91\x9e\x94P\xa0' \
                  b'\x95\xa2\x96\x9f\xa2\x9d\x95\x94P\x91\x9ePustxP\x95\xa8\x93' \
                  b'\x98\x91\x9e\x97\x95P\xa5\xa3\x99\x9e\x97P\xa4\x98\x95P~y' \
                  b'\x83\x84P\x80]befPs\xa5\xa2\xa6\x95Q'

        cipher = Cipher(algorithms.AES(aes_key),
                        modes.CTR(IV),
                        backend=default_backend())
        encryptor = cipher.encryptor()
        ciphertext = encryptor.update(bytes([b - 48 % 255 for b in message
                                             ])) + encryptor.finalize()
        return {"IV": IV, "Ciphertext": ciphertext}
Exemple #25
0
def verify_finish(config: Config, context: dict, encrypted_data: bytes) -> List[dict]:
    """pair_verify M3 and M4"""
    session_key = context.get('session_key')
    accessory_curve25519_public_key = context.get('accessory_curve25519_public_key')
    ios_device_curve25519_public_key = context.get('ios_device_curve25519_public_key')

    if not session_key or not accessory_curve25519_public_key or not ios_device_curve25519_public_key:
        return _error(TlvState.m4, TlvError.authentication,
                      'verify_finished call before successful verify_start')

    chacha = ChaCha20Poly1305(session_key)

    try:
        data = chacha.decrypt(NONCE_VERIFY_M3, encrypted_data, None)
    except InvalidTag:
        return _error(TlvState.m4, TlvError.authentication, 'invalid auth tag during chacha decryption')

    try:
        tlv = tlv_parser.decode(data)[0]
    except ValueError:
        return _error(TlvState.m4, TlvError.authentication, 'unable to decode decrypted tlv data')

    ios_device_ltpk = config.get_pairing(tlv[TlvCode.identifier])[1]

    if not ios_device_ltpk:
        return _error(TlvState.m4, TlvError.authentication,
                      'unable to find requested ios device in config file')

    ios_device_info = ios_device_curve25519_public_key + tlv[TlvCode.identifier].encode() + \
        accessory_curve25519_public_key

    if not _verify_ed25519(ios_device_ltpk, message=ios_device_info, signature=tlv[TlvCode.signature]):
        return _error(TlvState.m4, TlvError.authentication,
                      'ios_device_info ed25519 signature verification is failed')

    context['paired'] = True
    context['ios_device_pairing_id'] = tlv[TlvCode.identifier]

    hkdf = HKDF(algorithm=SHA512(), length=32, salt=SALT_CONTROL, info=INFO_CONTROL_WRITE, backend=default_backend())
    context['decrypt_key'] = hkdf.derive(context['shared_secret'])

    hkdf = HKDF(algorithm=SHA512(), length=32, salt=SALT_CONTROL, info=INFO_CONTROL_READ, backend=default_backend())
    context['encrypt_key'] = hkdf.derive(context['shared_secret'])

    return [{
        TlvCode.state: TlvState.m4,
    }]
Exemple #26
0
def _kdf_derive(key):
    kdf = HKDF(algorithm=hashes.SHA256(),
               length=32,
               salt=None,
               info=None,
               backend=default_backend())

    return kdf.derive(key.encode('utf-8'))
Exemple #27
0
def hkdf(ikm, salt=b"", info=b""):
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=64,
                salt=salt,
                info=info,
                backend=default_backend())

    return hkdf.derive(ikm)
Exemple #28
0
 def derive_key(self, secret, info):
     hkdf = HKDF(
         algorithm=hashes.SHA256(),
         length=16,
         salt=None,
         info=info,
     )
     return hkdf.derive(secret)
Exemple #29
0
def derive_servicex_master_key(password):
    # Key length, salt, and info fixed as part of protocol
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=32,
                salt=b"servicex",
                info=b"master jwt",
                backend=default_backend())
    return hkdf.derive(password)
Exemple #30
0
def hkdf_derive(input: bytes, salt: str, info: str) -> bytes:
    hkdf = HKDF(
        algorithm=hashes.SHA512(),
        length=32,
        salt=salt.encode(),
        info=info.encode(),
        backend=backend,
    )
    return hkdf.derive(input)
    def handshake(self):
        backend = default_backend()
        infoA = self.username
        infoB = InfoBank
        hkdfA = HKDF(algorithm=hashes.SHA256(),length=32,salt=None,info=infoA,backend=backend)
        hkdfB = HKDF(algorithm=hashes.SHA256(),length=32,salt=None,info=infoB,backend=backend)

        q = SPAKE2_B(self.password)
        msg_out = q.start()
        self.send(msg_out)
        msg_in = self.recv() # this is message A->B
        key = q.finish(msg_in)
        expected_confirm_A = hkdfA.derive(key)
        confirm_B = hkdfB.derive(key)
        self.send(confirm_B)
        confirm_A = self.recv()
        assert confirm_A == expected_confirm_A
        return key
Exemple #32
0
def ecdh(key, peer_key, file, type, key_length):
    hkdf = HKDF(hashes.SHA256(), key_length, None, None, default_backend())
    try:
        key = hkdf.derive(get_ecdh(key, peer_key, type))
        with open(file, 'wb') as fd:
            fd.write(key)
        print('Shared key was wrote in', file)
    except FileNotFoundError as e:
        print(e)
Exemple #33
0
    def test_derive_short_output(self, backend):
        hkdf = HKDF(
            hashes.SHA256(),
            4,
            salt=None,
            info=None,
            backend=backend
        )

        assert hkdf.derive(b"\x01" * 16) == b"gJ\xfb{"
Exemple #34
0
def hkdf_derive_test(backend, algorithm, params):
    hkdf = HKDF(
        algorithm,
        int(params["l"]),
        salt=binascii.unhexlify(params["salt"]) or None,
        info=binascii.unhexlify(params["info"]) or None,
        backend=backend
    )

    okm = hkdf.derive(binascii.unhexlify(params["ikm"]))

    assert okm == binascii.unhexlify(params["okm"])
def keygen():
   backend = default_backend()
   salt = os.urandom(16)
   info = b"hkdf-example"
   hkdf = HKDF(
      algorithm=hashes.SHA256(),
         length=32,
         salt=salt,
         info=info,
         backend=backend
   )
   key = hkdf.derive(b"This is the symetric key!")
   return key
Exemple #36
0
    def test_derive_long_output(self, backend):
        vector = load_vectors_from_file(
            os.path.join("KDF", "hkdf-generated.txt"), load_nist_vectors
        )[0]
        hkdf = HKDF(
            hashes.SHA256(),
            int(vector["l"]),
            salt=vector["salt"],
            info=vector["info"],
            backend=backend
        )
        ikm = binascii.unhexlify(vector["ikm"])

        assert hkdf.derive(ikm) == binascii.unhexlify(vector["okm"])
Exemple #37
0
def derive_key(secret, namespace, size=32):
    """HKDF-derive key material from the given master secret.

    This applies standard HKDF with our application-specific defaults, to
    produce derived key material of the requested length.
    """
    kdf = HKDF(
        algorithm=hashes.SHA256(),
        length=size,
        salt=b"",
        info=hkdf_namespace(namespace),
        backend=backend
    )
    return kdf.derive(secret)
Exemple #38
0
def rotateip(ip, salt=None):
    """
    rotate ip to another address

    if 'salt' is given, the ip will be
      * salted with secret
      * hashed with SHA-256
      * combined to a new IP
    otherwise, the ip will be rotated to 0.0.0.0

    >>> rotateip("127.0.0.1")
    '0.0.0.0'
    >>> x = rotateip("127.0.0.1", salt=b"secret")
    >>> y = rotateip("127.0.0.1", salt=b"secret2")
    >>> x == y
    False
    """

    def tokenize(a, n):
        return map(lambda i: a[i:i+n], range(0, len(a), n))

    def xor(t):
        x, y = t
        return x ^ y

    if salt is None:
        return "0.0.0.0"

    hkdf = HKDF(algorithm=hashes.SHA256(), length=8, salt=salt,
                info=b"ip-hashing", backend=default_backend())

    hashed = hkdf.derive(ip.encode())

    # for some reason, minimum derived key size is 8, so we need to further
    # reduce the key
    hashed = map(xor, zip(*tokenize(hashed, 4)))

    return ".".join(map(str, hashed))
Exemple #39
0
    def get_filename_and_key(self, upath, ext=None):
        path = upath.encode('utf-8')
        nonpath = b"//\x00" # cannot occur in path, which is normalized

        # Generate per-file key material via HKDF
        info = path
        if ext is not None:
            info += nonpath + ext

        hkdf = HKDF(algorithm=hashes.SHA256(),
                    length=3*32,
                    salt=self.salt_hkdf,
                    info=info,
                    backend=backend)
        data = hkdf.derive(self.key)

        # Generate key
        key = data[:32]

        # Generate filename
        h = hmac.HMAC(key=data[32:], algorithm=hashes.SHA512(), backend=backend)
        h.update(info)
        fn = h.finalize().encode('hex')
        return os.path.join(self.path, fn), key
def deriveKey(mode, salt, key=None, dh=None, keyid=None, authSecret=None, padSize=2):
    def buildInfo(base, context):
        return b"Content-Encoding: " + base + b"\0" + context

    def deriveDH(mode, keyid, dh):
        def lengthPrefix(key):
            return struct.pack("!H", len(key)) + key

        if keyid is None:
            raise Exception(u"'keyid' is not specified with 'dh'")
        if not keyid in keys:
            raise Exception(u"'keyid' doesn't identify a key: " + keyid)
        if not keyid in labels:
            raise Exception(u"'keyid' doesn't identify a key label: " + keyid)
        if mode == "encrypt":
            senderPubKey = keys[keyid].get_pubkey()
            receiverPubKey = dh
        elif mode == "decrypt":
            senderPubKey = dh
            receiverPubKey = keys[keyid].get_pubkey()
        else:
            raise Exception(u"unknown 'mode' specified: " + mode);

        if type(labels[keyid]) == type(u""):
            labels[keyid] = labels[keyid].encode("utf-8")

        return (keys[keyid].get_ecdh_key(dh),
                labels[keyid] + b"\0" +
                    lengthPrefix(receiverPubKey) + lengthPrefix(senderPubKey))

    if salt is None or len(salt) != 16:
        raise Exception(u"'salt' must be a 16 octet value")

    context = b""
    if key is not None:
        secret = key
    elif dh is not None:
        (secret, context) = deriveDH(mode=mode, keyid=keyid, dh=dh)
    elif keyid is not None:
        secret = keys[keyid]
    if secret is None:
        raise Exception(u"unable to determine the secret")

    if authSecret is not None:
        hkdf_auth = HKDF(
            algorithm=hashes.SHA256(),
            length=32,
            salt=authSecret,
            info=buildInfo(b"auth", b""),
            backend=default_backend()
        )
        secret = hkdf_auth.derive(secret)

    if padSize == 2:
        keyinfo = buildInfo(b"aesgcm", context)
        nonceinfo = buildInfo(b"nonce", context)
    elif padSize == 1:
        keyinfo = b"Content-Encoding: aesgcm128"
        nonceinfo = b"Content-Encoding: nonce"
    else:
        raise Exception(u"unable to set context for padSize=" + str(padSize))

    hkdf_key = HKDF(
        algorithm=hashes.SHA256(),
        length=16,
        salt=salt,
        info=keyinfo,
        backend=default_backend()
    )
    hkdf_nonce = HKDF(
        algorithm=hashes.SHA256(),
        length=12,
        salt=salt,
        info=nonceinfo,
        backend=default_backend()
    )
    result = (hkdf_key.derive(secret), hkdf_nonce.derive(secret))
    return result
Exemple #41
0
def hkdf(secret, extra_secret, info, output_len):
    hkdf = HKDF(algorithm=SHA512(), length=output_len, salt=extra_secret, info=info, backend=backend)
    derived = hkdf.derive(secret)
    assert len(derived) == output_len
    return io.BytesIO(derived)
Exemple #42
0
def _hkdf_expand(key, info):
    backend = default_backend()
    salt = '0' * len(key)
    hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=info,
                backend=backend)
    return hkdf.derive(key)
Exemple #43
0
def derive_key(key_material, salt, info):
    algorithm = hashes.SHA512()
    length = algorithm.digest_size
    hkdf = HKDF(algorithm, length, salt, info, backend)
    return hkdf.derive(key_material)