예제 #1
0
    def test_invalid_digest_size(self, backend):
        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=65)

        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=0)

        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=-1)
예제 #2
0
    def mac_gen(self, my_text):

        if (self.digest == "SHA256"):
            h = hmac.HMAC(self.symmetric_key,
                          hashes.SHA256(),
                          backend=default_backend())
        elif (self.digest == "SHA384"):
            h = hmac.HMAC(self.symmetric_key,
                          hashes.SHA384(),
                          backend=default_backend())
        elif (self.digest == "MD5"):
            h = hmac.HMAC(self.symmetric_key,
                          hashes.MD5(),
                          backend=default_backend())
        elif (self.digest == "SHA512"):
            h = hmac.HMAC(self.symmetric_key,
                          hashes.SHA512(),
                          backend=default_backend())
        elif (self.digest == "BLAKE2"):
            h = hmac.HMAC(self.symmetric_key,
                          hashes.BLAKE2b(64),
                          backend=default_backend())

        h.update(my_text)

        self.mac = binascii.hexlify(h.finalize())
예제 #3
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]
예제 #4
0
def split_rekey(priv_a: Union[UmbralPrivateKey, CurveBN],
                pubkey_b_point: Union[UmbralPublicKey, Point],
                threshold: int, N: int,
                params: UmbralParameters=None) -> List[KFrag]:
    """
    Creates a re-encryption key from Alice to Bob and splits it in KFrags,
    using Shamir's Secret Sharing. Requires a threshold number of KFrags 
    out of N to guarantee correctness of re-encryption.

    Returns a list of KFrags.
    """
    params = params if params is not None else default_params()

    if isinstance(priv_a, UmbralPrivateKey):
        priv_a = priv_a.bn_key

    if isinstance(pubkey_b_point, UmbralPublicKey):
        pubkey_b_point = pubkey_b_point.point_key

    g = params.g
    pubkey_a_point = priv_a * g

    x = CurveBN.gen_rand(params.curve)
    xcomp = x * g
    d = CurveBN.hash(xcomp, pubkey_b_point, pubkey_b_point * x, params=params)

    coeffs = [priv_a * (~d)]
    coeffs += [CurveBN.gen_rand(params.curve) for _ in range(threshold - 1)]

    u = params.u

    g_ab = priv_a * pubkey_b_point

    blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
    blake2b.update(pubkey_a_point.to_bytes())
    blake2b.update(pubkey_b_point.to_bytes())
    blake2b.update(g_ab.to_bytes())
    hashed_dh_tuple = blake2b.finalize()

    kfrags = []
    for _ in range(N):
        id_kfrag = CurveBN.gen_rand(params.curve)

        share_x = CurveBN.hash(id_kfrag, hashed_dh_tuple, params=params)

        rk = poly_eval(coeffs, share_x)

        u1 = rk * u
        y = CurveBN.gen_rand(params.curve)

        signature_input = [y * g, id_kfrag, pubkey_a_point, pubkey_b_point, u1, xcomp]
        z1 = CurveBN.hash(*signature_input, params=params)
        z2 = y - priv_a * z1

        kfrag = KFrag(bn_id=id_kfrag, bn_key=rk, 
                      point_noninteractive=xcomp, point_commitment=u1, 
                      bn_sig1=z1, bn_sig2=z2)
        kfrags.append(kfrag)

    return kfrags
    def __init__(self, app, pipeline, id=None, config=None):
        super().__init__(app, pipeline, id, config)

        self.Backend = default_backend()

        algorithm = self.Config['algorithm'].upper()

        if algorithm == "SHA224":
            self.Algorithm = hashes.SHA224()
        elif algorithm == "SHA256":
            self.Algorithm = hashes.SHA256()
        elif algorithm == "SHA384":
            self.Algorithm = hashes.SHA384()
        elif algorithm == "SHA512":
            self.Algorithm = hashes.SHA512()
        elif algorithm == "SHA1":
            self.Algorithm = hashes.SHA1()
        elif algorithm == "MD5":
            self.Algorithm = hashes.MD5()
        elif algorithm == "BLAKE2B":
            digest_size = int(self.Config['digest_size'])
            self.Algorithm = hashes.BLAKE2b(digest_size)
        elif algorithm == "BLAKE2S":
            digest_size = int(self.Config['digest_size'])
            self.Algorithm = hashes.BLAKE2s(digest_size)
        else:
            L.error("Unknown hashing algorithm '{}'".format(
                self.Config['algorithm']))
            raise RuntimeError("Unknown hashing algorithm '{}'".format(
                self.Config['algorithm']))
class TestBLAKE2b(object):
    test_b2b = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "blake2"),
        ["blake2b.txt"],
        hashes.BLAKE2b(digest_size=64),
    )
예제 #7
0
파일: bignum.py 프로젝트: kbhokray/pyUmbral
    def hash_to_bn(cls, *crypto_items, params=None):
        params = params if params is not None else default_params()

        # TODO: Clean this in an upcoming cleanup of pyUmbral
        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        for item in crypto_items:
            try:
                item_bytes = item.to_bytes()
            except AttributeError:
                if not isinstance(item, bytes):
                    raise TypeError(
                        "{} is not acceptable type, received {}".format(
                            item, type(item)))
                item_bytes = item
            blake2b.update(item_bytes)

        i = 0
        h = 0
        while h < params.CURVE_MINVAL_HASH_512:
            blake2b_i = blake2b.copy()
            blake2b_i.update(i.to_bytes(params.CURVE_KEY_SIZE_BYTES, 'big'))
            hash_digest = blake2b_i.finalize()
            h = int.from_bytes(hash_digest, byteorder='big', signed=False)
            i += 1

        hash_bn = h % int(params.order)
        res = cls.from_int(hash_bn, params.curve)
        return res
예제 #8
0
    def hash(cls, *crypto_items, params: UmbralParameters) -> 'CurveBN':
        # TODO: Clean this in an upcoming cleanup of pyUmbral
        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        for item in crypto_items:
            try:
                item_bytes = item.to_bytes()
            except AttributeError:
                if isinstance(item, bytes):
                    item_bytes = item
                else:
                    raise TypeError(
                        "{} is not acceptable type, received {}".format(
                            item, type(item)))
            blake2b.update(item_bytes)

        hash_digest = openssl._bytes_to_bn(blake2b.finalize())

        _1 = backend._lib.BN_value_one()

        order_minus_1 = openssl._get_new_BN()
        res = backend._lib.BN_sub(order_minus_1, params.curve.order, _1)
        backend.openssl_assert(res == 1)

        bignum = openssl._get_new_BN()
        with backend._tmp_bn_ctx() as bn_ctx:
            res = backend._lib.BN_mod(bignum, hash_digest, order_minus_1,
                                      bn_ctx)
            backend.openssl_assert(res == 1)

        res = backend._lib.BN_add(bignum, bignum, _1)
        backend.openssl_assert(res == 1)

        return cls(bignum, params.curve)
def generate_shared_key(private_key, public_key_pem, algorithm):
    """
	It generates the shared key of Diffie Hellman.
	:param private_key:
	:param public_key_pem:
	:param algorithm: The digestion algorithm
	"""
    public_key = serialization.load_pem_public_key(
        public_key_pem, backend=default_backend()
    )

    shared_key = private_key.exchange(public_key)

    if algorithm == "SHA256":
        hash_algorithm = hashes.SHA256()
    elif algorithm == "SHA512":
        hash_algorithm = hashes.SHA512()
    elif algorithm == "BLAKE2":
        hash_algorithm = hashes.BLAKE2b(64)
    else:
        raise Exception("Hash Algorithm name not found")

    derived_key = HKDF(
        algorithm=hash_algorithm,
        length=32,
        salt=None,
        info=b"handshake data",
        backend=default_backend(),
    ).derive(shared_key)

    logger.info(f"My Shared Key: {derived_key}")
    return derived_key
예제 #10
0
def hash_content(file_name, hash_function, avalanche=""):

    # possible cryptographic hash function
    options = {'MD5': hashes.MD5(), 'SHA-256': hashes.SHA256(), 'SHA-384': hashes.SHA384() \
        ,'SHA-512': hashes.SHA512(), 'BLAKE-2': hashes.BLAKE2b(64)}

    if hash_function not in options:
        print(f"Incorrect cryptographic hash function: {hash_function}")
        print(f"Available cryptographic hash functions: {hashes}")

    digest = hashes.Hash(options[hash_function], backend=default_backend())

    data = []
    with open(file_name, "r") as fr:
        blob = fr.read(1024)
        encoded = blob.encode()
        byte_arr = bytearray(encoded)
        byte_arr[0] = byte_arr[0] ^ 1
        digest.update(byte_arr)
        while blob:
            blob = fr.read(1024)
            digest.update(blob.encode())

    with open(hash_function.lower() + avalanche + ".txt", "w") as fw:
        fw.write(f"{hash_function}: {binascii.hexlify(digest.finalize())}")
 def test_blake2b(self, backend):
     h = hmac.HMAC(b"0" * 64, hashes.BLAKE2b(digest_size=64), backend)
     h.update(b"test")
     digest = h.finalize()
     assert digest == binascii.unhexlify(
         b"b5319122f8a24ba134a0c9851922448104e25be5d1b91265c0c68b22722f0f29"
         b"87dba4aeaa69e6bed7edc44f48d6b1be493a3ce583f9c737c53d6bacc09e2f32"
     )
예제 #12
0
파일: utils.py 프로젝트: soros1321/pyUmbral
def kdf(ecpoint, key_length):
    data = ecpoint.to_bytes(is_compressed=True)

    return HKDF(algorithm=hashes.BLAKE2b(64),
                length=key_length,
                salt=None,
                info=None,
                backend=default_backend()).derive(data)
예제 #13
0
def split_rekey(priv_a: Union[UmbralPrivateKey, BigNum],
                pub_b: Union[UmbralPublicKey, Point],
                threshold: int,
                N: int,
                params: UmbralParameters = None) -> List[KFrag]:
    """
    Creates a re-encryption key from Alice to Bob and splits it in KFrags,
    using Shamir's Secret Sharing. Requires a threshold number of KFrags 
    out of N to guarantee correctness of re-encryption.

    Returns a list of KFrags.
    """
    params = params if params is not None else default_params()

    if isinstance(priv_a, UmbralPrivateKey):
        priv_a = priv_a.bn_key

    if isinstance(pub_b, UmbralPublicKey):
        pub_b = pub_b.point_key

    g = params.g
    pub_a = priv_a * g

    x = BigNum.gen_rand(params.curve)
    xcomp = x * g
    d = hash_to_bn([xcomp, pub_b, pub_b * x], params)

    coeffs = [priv_a * (~d)]
    coeffs += [BigNum.gen_rand(params.curve) for _ in range(threshold - 1)]

    u = params.u

    g_ab = priv_a * pub_b

    blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
    blake2b.update(pub_a.to_bytes())
    blake2b.update(pub_b.to_bytes())
    blake2b.update(g_ab.to_bytes())
    hashed_dh_tuple = blake2b.finalize()

    kfrags = []
    for _ in range(N):
        id_kfrag = BigNum.gen_rand(params.curve)

        share_x = hash_to_bn([id_kfrag, hashed_dh_tuple], params)

        rk = poly_eval(coeffs, share_x)

        u1 = rk * u
        y = BigNum.gen_rand(params.curve)

        z1 = hash_to_bn([y * g, id_kfrag, pub_a, pub_b, u1, xcomp], params)
        z2 = y - priv_a * z1

        kfrag = KFrag(id_=id_kfrag, key=rk, x=xcomp, u1=u1, z1=z1, z2=z2)
        kfrags.append(kfrag)

    return kfrags
예제 #14
0
    def get_digest(self, hash_algorithm):
        self.supported_digest_algorithms(hash_algorithm)

        if hash_algorithm == SHA256:
            return hashes.SHA256()
        elif hash_algorithm == SHA512:
            return hashes.SHA512()
        elif hash_algorithm == BLAKE2:
            return hashes.BLAKE2b(64)
예제 #15
0
    def _reconstruct_shamirs_secret(
            self, priv_b: Union[UmbralPrivateKey, CurveBN]) -> None:
        g = self._umbral_params.g

        if isinstance(priv_b, UmbralPrivateKey):
            pub_b = priv_b.get_pubkey()
            priv_b = priv_b.bn_key
        else:
            pub_b = priv_b * g

        cfrag_0 = self._attached_cfrags[0]
        id_0 = cfrag_0._kfrag_id
        ni = cfrag_0._point_noninteractive
        xcoord = cfrag_0._point_xcoord

        dh_xcoord = priv_b * xcoord

        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        blake2b.update(xcoord.to_bytes())
        blake2b.update(pub_b.to_bytes())
        blake2b.update(dh_xcoord.to_bytes())
        hashed_dh_tuple = blake2b.finalize()

        if len(self._attached_cfrags) > 1:
            xs = [
                CurveBN.hash(cfrag._kfrag_id,
                             hashed_dh_tuple,
                             params=self._umbral_params)
                for cfrag in self._attached_cfrags
            ]
            x_0 = CurveBN.hash(id_0,
                               hashed_dh_tuple,
                               params=self._umbral_params)
            lambda_0 = lambda_coeff(x_0, xs)
            e = lambda_0 * cfrag_0._point_e1
            v = lambda_0 * cfrag_0._point_v1

            for cfrag in self._attached_cfrags[1:]:
                if (ni, xcoord) != (cfrag._point_noninteractive,
                                    cfrag._point_xcoord):
                    raise ValueError(
                        "Attached CFrags are not pairwise consistent")

                x_i = CurveBN.hash(cfrag._kfrag_id,
                                   hashed_dh_tuple,
                                   params=self._umbral_params)
                lambda_i = lambda_coeff(x_i, xs)
                e = e + (lambda_i * cfrag._point_e1)
                v = v + (lambda_i * cfrag._point_v1)
        else:
            e = cfrag_0._point_e1
            v = cfrag_0._point_v1

        self._point_e_prime = e
        self._point_v_prime = v
        self._point_noninteractive = ni
예제 #16
0
    def checksum_file(self, p_algo2checksum, p_file_path, p_file_name):

        # Prepare
        _inputs = f"{self.inputs}|{p_algo2checksum}|{p_file_path}|{p_file_name}"
        _module_name = __name__
        _func_name = inspect.currentframe().f_code.co_name
        _response_tuple = None
        _msg = None
        _file = f"{p_file_path}{p_file_name}"
        _algo_checksum_file = None
        _checksum = None
        _checksum_b64encode = None
        _output_value_string = None

        # Choose Algorithm
        if p_algo2checksum.lower() == 'sha256':
            _algo_checksum_file = hashes.SHA256()
        elif p_algo2checksum.lower() == 'blake2':
            _algo_checksum_file = hashes.BLAKE2b(64)
        else:
            _msg = 'Unknown algorithm'
            _response_tuple = (
                'NOK',
                f"{ utility.my_log('Error',_module_name,_func_name,inspect.currentframe().f_lineno,_inputs, _msg)}"
            )
            return (_response_tuple)

        if os.path.exists(_file):

            with open(_file, "rb") as f:
                try:
                    _file_hash = hashes.Hash(_algo_checksum_file,
                                             backend=self.backend)
                    while chunk := f.read(
                            8192):  # Read the binary file to the end (8192)
                        _file_hash.update(chunk)
                except Exception:
                    _response_tuple = (
                        'NOK',
                        f"{ utility.my_log('Exception',_module_name,_func_name,inspect.currentframe().f_lineno,_inputs,_msg)}"
                    )

            _checksum = _file_hash.finalize()
            _checksum_b64encode = base64.urlsafe_b64encode(_checksum)
            _output_value_string = self.byte_representation(
                'from_bin', _checksum_b64encode)
            _response_tuple = ('OK', _output_value_string)

        else:
            _msg = 'File does not exist'
            _response_tuple = (
                'NOK',
                f"{ utility.my_log('Error',_module_name,_func_name,inspect.currentframe().f_lineno,_inputs, _msg)}"
            )

        return (_response_tuple)
예제 #17
0
def _derive_wrapping_key_from_key_material(salt: bytes,
                                           key_material: bytes) -> bytes:
    """
    Uses HKDF to derive a 32 byte wrapping key to encrypt key material with.
    """
    wrapping_key = HKDF(algorithm=hashes.BLAKE2b(64),
                        length=64,
                        salt=salt,
                        info=b'NuCypher-KeyWrap',
                        backend=default_backend()).derive(key_material)

    return wrapping_key[:32]
예제 #18
0
def _kdf(eph_pk: bytes, shared_key: bytes) -> Tuple[bytes, bytes]:
    """
    Key derivation function
    """
    # Hashing
    key_material = hashes.Hash(hashes.BLAKE2b(64), backend=default_backend())
    key_material.update(_KDF_TAG)
    key_material.update(eph_pk)
    key_material.update(shared_key)
    key_material = key_material.finalize()
    assert len(key_material) == _KEY_MATERIAL_LENGTH_BYTES
    return \
        key_material[:_SYM_KEY_LENGTH_BYTES], \
        key_material[_SYM_KEY_LENGTH_BYTES:]
예제 #19
0
    def create_digest(message, digst_algorithm):
        hash_algorithm = None

        if digst_algorithm == "SHA512":
            hash_algorithm = hashes.SHA512_256()
        elif digst_algorithm == "BLAKE2":
            hash_algorithm = hashes.BLAKE2b(64)
        else:
            raise Exception("Digest Algorithm name not found!")

        digest = hashes.Hash(hash_algorithm)
        digest.update(message)

        return digest.finalize()
예제 #20
0
def kdf(
    ecpoint: Point,
    key_length: int,
    salt: Optional[bytes] = None,
    info: Optional[bytes] = None,
) -> bytes:

    data = ecpoint.to_bytes(is_compressed=True)
    hkdf = HKDF(algorithm=hashes.BLAKE2b(64),
                length=key_length,
                salt=salt,
                info=info,
                backend=default_backend())
    return hkdf.derive(data)
예제 #21
0
class TestBLAKE2b(object):
    test_blake2b = generate_base_hash_test(
        hashes.BLAKE2b(digest_size=64), digest_size=64,
    )

    def test_invalid_digest_size(self, backend):
        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=65)

        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=0)

        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=-1)
예제 #22
0
def dechachacry(data, salt, nonce):
    keyraw = salt + bytes(getpass(), "UTF-8")
    key = hashes.Hash(hashes.BLAKE2b(64), backend=default_backend())
    key.update(keyraw)
    key = key.finalize()
    k3y = bytes()
    for bits in range(0, 32, 1):
        stream = [key[bits] ^ key[(bits + 32)]]
        k3y = k3y + bytes(stream)
        if bits == 31:
            key = k3y
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    decrypt = cipher.decryptor()
    return decrypt.update(data)
예제 #23
0
 def __init__(self):
     nonce = bytes(token_hex(8), "utf-8")
     key = bytes(token_hex(32), "utf-8")
     hasher = hashes.Hash(hashes.BLAKE2b(64), backend=default_backend())
     hasher.update(key)
     key = hasher.finalize()
     prekey = bytes()
     for bits in range(0,32,1):
         stream = [key[bits] ^ key[(bits+32)]]
         prekey = prekey + bytes(stream)
         if bits == 31:
             key = prekey
     algorithm = algorithms.ChaCha20(key, nonce)
     cipher = Cipher(algorithm, mode=None, backend=default_backend())
     self.encryptor = cipher.encryptor()
예제 #24
0
파일: point.py 프로젝트: sriharikapu/ews
def unsafe_hash_to_point(data: bytes = b'',
                         params: UmbralParameters = None,
                         label: bytes = b'') -> 'Point':
    """
    Hashes arbitrary data into a valid EC point of the specified curve,
    using the try-and-increment method.
    It admits an optional label as an additional input to the hash function.
    It uses BLAKE2b (with a digest size of 64 bytes) as the internal hash function.

    WARNING: Do not use when the input data is secret, as this implementation is not
    in constant time, and hence, it is not safe with respect to timing attacks.
    """

    params = params if params is not None else default_params()

    len_data = len(data).to_bytes(4, byteorder='big')
    len_label = len(label).to_bytes(4, byteorder='big')

    label_data = len_label + label + len_data + data

    # We use an internal 32-bit counter as additional input
    i = 0
    while i < 2**32:
        ibytes = i.to_bytes(4, byteorder='big')
        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        blake2b.update(label_data + ibytes)
        hash_digest = blake2b.finalize()[:1 + params.CURVE_KEY_SIZE_BYTES]

        sign = b'\x02' if hash_digest[0] & 1 == 0 else b'\x03'
        compressed_point = sign + hash_digest[1:]

        try:
            return Point.from_bytes(compressed_point, params.curve)
        except InternalError as e:
            # We want to catch specific InternalExceptions:
            # - Point not in the curve (code 107)
            # - Invalid compressed point (code 110)
            # https://github.com/openssl/openssl/blob/master/include/openssl/ecerr.h#L228
            if e.err_code[0].reason in (107, 110):
                pass
            else:
                # Any other exception, we raise it
                raise e

        i += 1

    # Only happens with probability 2^(-32)
    raise ValueError('Could not hash input into the curve')
예제 #25
0
    def _reconstruct_shamirs_secret(self,
                                    pub_a: Union[UmbralPublicKey, Point],
                                    priv_b: Union[UmbralPrivateKey, BigNum],
                                    params: UmbralParameters = None) -> None:

        params = params if params is not None else default_params()

        if isinstance(priv_b, UmbralPrivateKey):
            priv_b = priv_b.bn_key

        if isinstance(pub_a, UmbralPublicKey):
            pub_a = pub_a.point_key

        g = params.g
        pub_b = priv_b * g
        g_ab = priv_b * pub_a

        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        blake2b.update(pub_a.to_bytes())
        blake2b.update(pub_b.to_bytes())
        blake2b.update(g_ab.to_bytes())
        hashed_dh_tuple = blake2b.finalize()

        id_cfrag_pairs = list(self._attached_cfrags.items())
        id_0, cfrag_0 = id_cfrag_pairs[0]
        x_0 = BigNum.hash_to_bn(id_0, hashed_dh_tuple, params=params)
        if len(id_cfrag_pairs) > 1:
            xs = [
                BigNum.hash_to_bn(_id, hashed_dh_tuple, params=params)
                for _id in self._attached_cfrags.keys()
            ]
            lambda_0 = lambda_coeff(x_0, xs)
            e = lambda_0 * cfrag_0.point_eph_e1
            v = lambda_0 * cfrag_0.point_eph_v1

            for id_i, cfrag in id_cfrag_pairs[1:]:
                x_i = BigNum.hash_to_bn(id_i, hashed_dh_tuple, params=params)
                lambda_i = lambda_coeff(x_i, xs)
                e = e + (lambda_i * cfrag.point_eph_e1)
                v = v + (lambda_i * cfrag.point_eph_v1)
        else:
            e = cfrag_0.point_eph_e1
            v = cfrag_0.point_eph_v1

        self._point_eph_e_prime = e
        self._point_eph_v_prime = v
        self._point_noninteractive = cfrag_0.point_eph_ni
예제 #26
0
파일: point.py 프로젝트: eramitg/pyUmbral
def unsafe_hash_to_point(data,
                         params: UmbralParameters,
                         label=None) -> 'Point':
    """
    Hashes arbitrary data into a valid EC point of the specified curve,
    using the try-and-increment method.
    It admits an optional label as an additional input to the hash function.
    It uses BLAKE2b (with a digest size of 64 bytes) as the internal hash function.

    WARNING: Do not use when the input data is secret, as this implementation is not
    in constant time, and hence, it is not safe with respect to timing attacks.

    TODO: Check how to uniformly generate ycoords. Currently, it only outputs points
    where ycoord is even (i.e., starting with 0x02 in compressed notation)
    """
    if label is None:
        label = []

    # We use a 32-bit counter as additional input
    i = 1
    while i < 2**32:
        ibytes = i.to_bytes(4, byteorder='big')
        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        blake2b.update(label + ibytes + data)
        hash_digest = blake2b.finalize()[:params.CURVE_KEY_SIZE_BYTES]

        compressed02 = b"\x02" + hash_digest

        try:
            return Point.from_bytes(compressed02, params.curve)
        except InternalError as e:
            # We want to catch specific InternalExceptions:
            # - Point not in the curve (code 107)
            # - Invalid compressed point (code 110)
            # https://github.com/openssl/openssl/blob/master/include/openssl/ecerr.h#L228
            if e.err_code[0].reason in (107, 110):
                pass
            else:
                # Any other exception, we raise it
                raise e

        i += 1

    # Only happens with probability 2^(-32)
    raise ValueError('Could not hash input into the curve')
예제 #27
0
    def _reconstruct_shamirs_secret(self, 
                                    pub_a: Union[UmbralPublicKey, Point], 
                                    priv_b: Union[UmbralPrivateKey, CurveBN],
                                    params: UmbralParameters=None) -> None:

        params = params if params is not None else default_params()

        if isinstance(priv_b, UmbralPrivateKey):
            priv_b = priv_b.bn_key

        if isinstance(pub_a, UmbralPublicKey):
            pub_a = pub_a.point_key

        g = params.g
        pub_b = priv_b * g
        g_ab = priv_b * pub_a

        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        blake2b.update(pub_a.to_bytes())
        blake2b.update(pub_b.to_bytes())
        blake2b.update(g_ab.to_bytes())
        hashed_dh_tuple = blake2b.finalize()

        cfrag_0 = self._attached_cfrags[0]
        id_0 = cfrag_0._bn_kfrag_id
        x_0 = CurveBN.hash(id_0, hashed_dh_tuple, params=params)
        if len(self._attached_cfrags) > 1:
            xs = [CurveBN.hash(cfrag._bn_kfrag_id, hashed_dh_tuple, params=params)
                    for cfrag in self._attached_cfrags]
            lambda_0 = lambda_coeff(x_0, xs)
            e = lambda_0 * cfrag_0._point_e1
            v = lambda_0 * cfrag_0._point_v1

            for cfrag in self._attached_cfrags[1:]:
                x_i = CurveBN.hash(cfrag._bn_kfrag_id, hashed_dh_tuple, params=params)
                lambda_i = lambda_coeff(x_i, xs)
                e = e + (lambda_i * cfrag._point_e1)
                v = v + (lambda_i * cfrag._point_v1)
        else:
            e = cfrag_0._point_e1
            v = cfrag_0._point_v1

        self._point_e_prime = e
        self._point_v_prime = v
        self._point_noninteractive = cfrag_0._point_noninteractive
예제 #28
0
    def derive_privkey_by_label(self, label: bytes, salt: bytes=None, 
                                params: UmbralParameters=None):
        """
        Derives an UmbralPrivateKey using a KDF from this instance of 
        UmbralKeyingMaterial, a label, and an optional salt.
        """
        params = params if params is not None else default_params()

        key_material = HKDF(
            algorithm=hashes.BLAKE2b(64),
            length=64,
            salt=salt,
            info=b"NuCypherKMS/KeyDerivation/"+label,
            backend=default_backend()
        ).derive(self.keying_material)

        bn_key = CurveBN.hash(key_material, params=params)
        return UmbralPrivateKey(bn_key, params)
예제 #29
0
파일: curvebn.py 프로젝트: cygnusv/pyUmbral
    def hash(cls, *crypto_items, params=None):
        params = params if params is not None else default_params()

        curve_nid = backend._elliptic_curve_to_nid(params.curve)
        order = openssl._get_ec_order_by_curve_nid(curve_nid)
        group = openssl._get_ec_group_by_curve_nid(curve_nid)

        # TODO: Clean this in an upcoming cleanup of pyUmbral
        blake2b = hashes.Hash(hashes.BLAKE2b(64), backend=backend)
        for item in crypto_items:
            try:
                item_bytes = item.to_bytes()
            except AttributeError:
                if isinstance(item, bytes):
                    item_bytes = item
                else:
                    raise TypeError(
                        "{} is not acceptable type, received {}".format(
                            item, type(item)))
            blake2b.update(item_bytes)

        hash_digest = blake2b.finalize()
        hash_digest = int.from_bytes(hash_digest,
                                     byteorder='big',
                                     signed=False)
        hash_digest = openssl._int_to_bn(hash_digest)

        _1 = backend._lib.BN_value_one()

        order_minus_1 = openssl._get_new_BN()
        res = backend._lib.BN_sub(order_minus_1, order, _1)
        backend.openssl_assert(res == 1)

        bignum = openssl._get_new_BN()
        with backend._tmp_bn_ctx() as bn_ctx:
            res = backend._lib.BN_mod(bignum, hash_digest, order_minus_1,
                                      bn_ctx)
            backend.openssl_assert(res == 1)

        res = backend._lib.BN_add(bignum, bignum, _1)
        backend.openssl_assert(res == 1)

        return cls(bignum, curve_nid, group, order)
예제 #30
0
def enchachacry(data):
    nonce = bytes(token_hex(8), "UTF-8")
    salt = bytes(token_hex(8), "UTF-8")
    keyraw = salt + bytes(getpass(), "UTF-8")
    key = hashes.Hash(hashes.BLAKE2b(64), backend=default_backend())
    key.update(keyraw)
    key = key.finalize()
    k3y = bytes()
    for bits in range(0, 32, 1):
        stream = [key[bits] ^ key[(bits + 32)]]
        k3y = k3y + bytes(stream)
        if bits == 31:
            key = k3y
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    marker = bytes(
        b"\x8c\x14\xf6t\xea\xd5\xe3\x88Z\xa8~\xceE\x02w\\\xf4/w\xfa\xc6\xc5g}")
    encrypt = cipher.encryptor()
    return (marker + salt + nonce + encrypt.update(data))