Example #1
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)
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))
def setup_keys(shared_key):
    output_key = ChaCha20Poly1305(
        HKDF(hashes.SHA512(), 32,
             b"MediaRemote-Salt", b"MediaRemote-Write-Encryption-Key",
             default_backend()).derive(shared_key))
    input_key = ChaCha20Poly1305(
        HKDF(hashes.SHA512(), 32,
             b"MediaRemote-Salt", b"MediaRemote-Read-Encryption-Key",
             default_backend()).derive(shared_key))
    return output_key, input_key
Example #4
0
def KDF_RK(rk, dh_out):
    kd = HKDF(algorithm=hashes.SHA256(),
              length=64,
              salt=rk,
              info=b'kdf_rk_info',
              backend=default_backend())
    kd_out = kd.derive(dh_out)
    root_key = kd_out[:32]
    chain_key = kd_out[32:]
    return root_key, chain_key
Example #5
0
    def derive_kek(cls, curve: 'CoseCurve', private_key: 'EC2',
                   public_key: 'EC2', context: 'CoseKDFContext') -> bytes:
        shared_secret = cls._ecdh(curve, private_key, public_key)

        kdf = HKDF(algorithm=cls.get_hash_func(),
                   length=context.supp_pub_info.key_data_length,
                   salt=None,
                   info=context.encode(),
                   backend=default_backend())
        return kdf.derive(shared_secret)
Example #6
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{"
Example #7
0
def hkdf_extract_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)

    prk = hkdf._extract(binascii.unhexlify(params["ikm"]))

    assert prk == binascii.unhexlify(params["prk"])
Example #8
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"])
Example #9
0
def hkdf(inp: bytes, length: int) -> bytes:
    # use HKDF on an input to derive a key
    hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=length,
        salt=b"",
        info=b"",
        backend=default_backend(),
    )
    return hkdf.derive(inp)
Example #10
0
File: kdf.py Project: nymble/hpke
 def expand(self, prk, info, L, salt=None):
     """ Expand a pseudorandom key 'prk'' using
         optional string "info" into "L" bytes of output keying material.
     """
     hkdf = HKDF_hazmat(algorithm=self.Hash(),
                        length=L,
                        salt=salt,
                        info=info,
                        backend=backend)
     return hkdf.derive(prk)
Example #11
0
def derive_fernet_key(key):
    backend = default_backend()
    salt = b'fleio-hkdf-salt'  # NOTE(tomo): We need a predictable salt, do not change
    info = b'fleio-fernet-hkdf'
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=32,
                salt=salt,
                info=info,
                backend=backend)
    return base64.urlsafe_b64encode(hkdf.derive(force_bytes(key)))
def computeAemKey(tek):
    salt = None
    info = 'EN-AEMK'.encode('UTF-8')
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=16,
                salt=salt,
                info=info,
                backend=backend)
    aemKey = hkdf.derive(tek)
    return (aemKey)
Example #13
0
 def deriveShared(self, salt=None):
     saltN = salt if salt != None else os.urandom(16)
     info = b"is-just-info"
     hkdf = HKDF(algorithm=hashes.SHA256(),
                 length=32,
                 salt=saltN,
                 info=info,
                 backend=default_backend())
     key = hkdf.derive(self.sharedKey)
     return key, saltN
Example #14
0
    def test_verify(self, backend):
        hkdf = HKDF(
            hashes.SHA256(),
            16,
            salt=None,
            info=None,
            backend=backend
        )

        hkdf.verify(b"\x01" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")
Example #15
0
def hap_hkdf(key, salt, info):
    """Just a shorthand."""
    hkdf = HKDF(
        algorithm=HAP_CRYPTO.HKDF_HASH,
        length=HAP_CRYPTO.HKDF_KEYLEN,
        salt=salt,
        info=info,
        backend=backend,
    )
    return hkdf.derive(key)
Example #16
0
def hkdf_expand(salt, info, shared_secret):
    """Derive encryption keys from shared secret."""
    hkdf = HKDF(
        algorithm=hashes.SHA512(),
        length=32,
        salt=salt.encode(),
        info=info.encode(),
        backend=default_backend(),
    )
    return hkdf.derive(shared_secret)
Example #17
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{"
def hkdf_function(session_key):
    salt = b'alienware'
    info = b'hello world'
    backend = default_backend()
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=32,
                salt=salt,
                info=info,
                backend=backend)
    obtained_key = hkdf.derive(session_key)
    return obtained_key
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
Example #20
0
    def test_verify_invalid(self, backend):
        hkdf = HKDF(
            hashes.SHA256(),
            16,
            salt=None,
            info=None,
            backend=backend
        )

        with pytest.raises(InvalidKey):
            hkdf.verify(b"\x02" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u")
Example #21
0
def daily_trace(dayNumber, traceKey):
  """A Daily Tracing Key is generated for every 24-hour window where the protocol is advertising."""
  
  hkdf = HKDF(algorithm=hashes.SHA256(), #Setup HKDF
              length=16, 
              salt=None, 
              info=str.encode("CT-DTK" + str(dayNumber)),
              backend=default_backend()) 
  
  dtk_i = hkdf.derive(traceKey)
  return dtk_i
Example #22
0
def derive_fernet_key(input_key):
    """Derive a 32-bit b64-encoded Fernet key from arbitrary input key.
    """
    hkdf = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        info=info,
        backend=backend,
    )
    return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key)))
Example #23
0
File: kdf.py Project: nymble/hpke
 def extract(self, salt, ikm):
     """ Extract a pseudorandom key of fixed length from input
         keying material "ikm" and an optional octet string "salt"
     """
     hash_len = self.Hash.digest_size
     hkdf = HKDF_hazmat(algorithm=self.Hash(),
                        length=hash_len,
                        salt=salt,
                        info=None,
                        backend=backend)
     return hkdf.derive(ikm)
Example #24
0
    def set_server_public_key(self, server_public_key: Sequence):
        common_secret = pow(int_from_bytes(server_public_key, 'big'),
                            self.pkey, self.DH_PRIME_1024)
        common_secret = int_to_bytes(common_secret)

        hkdf = HKDF(algorithm=hashes.SHA256(),
                    length=16,
                    salt=None,
                    info=None,
                    backend=default_backend())
        self.aes_key = hkdf.derive(common_secret)
def derivation_keys(shared_key):
    if not type(shared_key) == bytes:
        shared_key = shared_key.encode(utf_type)
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=32,
                salt=shared_key[16:32],
                info=shared_key[:16],
                backend=default_backend())

    keyDerived = hkdf.derive(shared_key[16:])
    return keyDerived
def derive_key(session_key, salt):

    backend = default_backend()

    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=32,
                salt=salt,
                info=None,
                backend=backend)

    return hkdf.derive(session_key)
Example #27
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"])
Example #28
0
 def KeyBuild(self, key):
     key = key.encode()
     hdkf = HKDF(
         algorithm = hashes.SHA512(),
         length = 32,
         salt = self.salt,
         info = None,
         backend = self.backend
     )
     key = hdkf.derive(key)
     return(key)
def generate_final_master_secret(master_secret, rand_client_server):
	backend = default_backend()
	info = "hkdf-example"
	hkdf = HKDF(
		algorithm=hashes.SHA256(),
		length=32,
		salt=rand_client_server,
		info=info,
		backend=backend) 
	key = hkdf.derive(master_secret)	
	return key
    def _hkdf(self, initial_material, key_length, info):
        # type: (bytes, int, Text) -> bytes
        """Use HKDF to derive a key.

        :param bytes initial_material: Initial material to use with HKDF
        :param int key_length: Length of key to derive
        :param str info: Info value to use in HKDF calculate
        :returns: Derived key material
        :rtype: bytes
        """
        hkdf = HKDF(algorithm=hashes.SHA256(), length=key_length, salt=None, info=info, backend=default_backend())
        return hkdf.derive(initial_material)
Example #31
0
def derivate(key, salt, spec):
    length = 0
    if spec == 'ECDHE-AES128-SHA':
        length = 16
    elif spec == 'ECDHE-AES256-SHA':
        length = 32
    hkdf = HKDF(algorithm=hashes.SHA256(),
                length=length,
                salt=salt,
                info=b"hkdf-example",
                backend=default_backend())
    return hkdf.derive(key)
Example #32
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=default_backend())
    return kdf.derive(secret)
Example #33
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"])
Example #34
0
def hkdf_extract_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
    )

    prk = hkdf._extract(binascii.unhexlify(params["ikm"]))

    assert prk == binascii.unhexlify(params["prk"])
Example #35
0
    def derive_key(self, bpassword, bsalt, attr_types):
        """
        Generate the key used for encryption
        """
        passToken = bpassword + self.btoken
        hkdf = Crypto_HKDF(algorithm=hashes.SHA256(),
                           length=32,
                           salt=bsalt,
                           info=self.btoken,
                           backend=default_backend())

        return hkdf.derive(bpassword)
Example #36
0
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
Example #37
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"])
Example #38
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)
Example #39
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"))
Example #40
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))
Example #41
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
Example #42
0
 def extract(self, salt, ikm):
     h = self.hash
     hkdf = HKDF(h, h.digest_size, salt, None, default_backend())
     if ikm is None:
         ikm = b"\x00" * h.digest_size
     return hkdf._extract(ikm)
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
Example #44
0
File: security.py Project: gnott/h
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)
Example #45
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)
Example #46
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)
Example #47
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)