當前位置: 首頁>>代碼示例>>Python>>正文


Python utils.Prehashed方法代碼示例

本文整理匯總了Python中cryptography.hazmat.primitives.asymmetric.utils.Prehashed方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.Prehashed方法的具體用法?Python utils.Prehashed怎麽用?Python utils.Prehashed使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cryptography.hazmat.primitives.asymmetric.utils的用法示例。


在下文中一共展示了utils.Prehashed方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: sign_digest

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256):
    """
    Given a digest and a private key, sign it.
    Return the base64-encoded signature
    """
    if not isinstance(hash_hex, (str, unicode)):
        raise ValueError("hash hex is not a string")

    hash_hex = str(hash_hex)

    pk_i = decode_privkey_hex(privkey_hex)
    privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend())

    sig = privk.sign(hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))

    sig_r, sig_s = decode_dss_signature(sig)
    sigb64 = encode_signature(sig_r, sig_s)
    return sigb64 
開發者ID:blockstack,項目名稱:virtualchain,代碼行數:20,代碼來源:ecdsalib.py

示例2: verify_digest

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256):
    """
    Given a digest, public key (as hex), and a base64 signature,
    verify that the public key signed the digest.
    Return True if so
    Return False if not
    """
    if not isinstance(hash_hex, (str, unicode)):
        raise ValueError("hash hex is not a string")

    hash_hex = str(hash_hex)
    pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex)
    sig_r, sig_s = decode_signature(sigb64)

    pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubk_uncompressed_hex.decode('hex')).public_key(default_backend())
    signature = encode_dss_signature(sig_r, sig_s)

    try:
        pubk.verify(signature, hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
        return True
    except InvalidSignature:
        return False 
開發者ID:blockstack,項目名稱:virtualchain,代碼行數:24,代碼來源:ecdsalib.py

示例3: sign

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def sign(self, byts):
        '''
        Compute the ECC signature for the given bytestream.

        Args:
            byts (bytes): The bytes to sign.

        Returns:
            bytes: The RSA Signature bytes.
        '''
        chosen_hash = c_hashes.SHA256()
        hasher = c_hashes.Hash(chosen_hash, default_backend())
        hasher.update(byts)
        digest = hasher.finalize()
        return self.priv.sign(digest,
                              c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
                              ) 
開發者ID:vertexproject,項目名稱:synapse,代碼行數:19,代碼來源:ecc.py

示例4: verify

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def verify(self, byts, sign):
        '''
        Verify the signature for the given bytes using the ECC
        public key.

        Args:
            byts (bytes): The data bytes.
            sign (bytes): The signature bytes.

        Returns:
            bool: True if the data was verified, False otherwise.
        '''
        try:
            chosen_hash = c_hashes.SHA256()
            hasher = c_hashes.Hash(chosen_hash, default_backend())
            hasher.update(byts)
            digest = hasher.finalize()
            self.publ.verify(sign,
                             digest,
                             c_ec.ECDSA(c_utils.Prehashed(chosen_hash))
                             )
            return True
        except InvalidSignature:
            logger.exception('Error in publ.verify')
            return False 
開發者ID:vertexproject,項目名稱:synapse,代碼行數:27,代碼來源:ecc.py

示例5: _ecc_static_length_signature

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def _ecc_static_length_signature(key, algorithm, digest):
    """Calculates an elliptic curve signature with a static length using pre-calculated hash.

    :param key: Elliptic curve private key
    :type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
    :param algorithm: Master algorithm to use
    :type algorithm: aws_encryption_sdk.identifiers.Algorithm
    :param bytes digest: Pre-calculated hash digest
    :returns: Signature with required length
    :rtype: bytes
    """
    pre_hashed_algorithm = ec.ECDSA(Prehashed(algorithm.signing_hash_type()))
    signature = b""
    while len(signature) != algorithm.signature_len:
        _LOGGER.debug(
            "Signature length %d is not desired length %d.  Recalculating.", len(signature), algorithm.signature_len
        )
        signature = key.sign(digest, pre_hashed_algorithm)
        if len(signature) != algorithm.signature_len:
            # Most of the time, a signature of the wrong length can be fixed
            # by negating s in the signature relative to the group order.
            _LOGGER.debug(
                "Signature length %d is not desired length %d.  Negating s.", len(signature), algorithm.signature_len
            )
            r, s = decode_dss_signature(signature)
            s = _ECC_CURVE_PARAMETERS[algorithm.signing_algorithm_info.name].order - s
            signature = encode_dss_signature(r, s)
    return signature 
開發者ID:aws,項目名稱:aws-encryption-sdk-python,代碼行數:30,代碼來源:elliptic_curve.py

示例6: verify

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def verify(self, signature):
        """Verifies the signature against the current cryptographic verifier state.

        :param bytes signature: The signature to verify
        """
        prehashed_digest = self._hasher.finalize()
        self.key.verify(
            signature=signature,
            data=prehashed_digest,
            signature_algorithm=ec.ECDSA(Prehashed(self.algorithm.signing_hash_type())),
        ) 
開發者ID:aws,項目名稱:aws-encryption-sdk-python,代碼行數:13,代碼來源:authentication.py

示例7: _calculate_digest_and_algorithm

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def _calculate_digest_and_algorithm(backend, data, algorithm):
    if not isinstance(algorithm, Prehashed):
        hash_ctx = hashes.Hash(algorithm, backend)
        hash_ctx.update(data)
        data = hash_ctx.finalize()
    else:
        algorithm = algorithm._algorithm

    if len(data) != algorithm.digest_size:
        raise ValueError(
            "The provided data must be the same length as the hash "
            "algorithm's digest size."
        )

    return (data, algorithm) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:17,代碼來源:utils.py

示例8: _check_not_prehashed

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def _check_not_prehashed(signature_algorithm):
    if isinstance(signature_algorithm, Prehashed):
        raise TypeError(
            "Prehashed is only supported in the sign and verify methods. "
            "It cannot be used with signer or verifier."
        ) 
開發者ID:tp4a,項目名稱:teleport,代碼行數:8,代碼來源:utils.py

示例9: verify_signature_v2

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def verify_signature_v2(args):
    """ Verify a previously signed binary image, using the RSA public key """
    SECTOR_SIZE = 4096
    SIG_BLOCK_MAX_COUNT = 3

    vk = _get_sbv2_rsa_pub_key(args.keyfile)
    image_content = args.datafile.read()
    if len(image_content) < SECTOR_SIZE or len(image_content) % SECTOR_SIZE != 0:
        raise esptool.FatalError("Invalid datafile. Data size should be non-zero & a multiple of 4096.")

    digest = digest = hashlib.sha256()
    digest.update(image_content[:-SECTOR_SIZE])
    digest = digest.digest()

    for sig_blk_num in range(SIG_BLOCK_MAX_COUNT):
        sig_blk = validate_signature_block(image_content, sig_blk_num)
        if sig_blk is None:
            raise esptool.FatalError("Signature block %d invalid. Signature could not be verified with the provided key." % sig_blk_num)
        sig_data = struct.unpack("<BBxx32s384sI384sI384sI16x", sig_blk)

        if sig_data[2] != digest:
            raise esptool.FatalError("Signature block image digest does not match the actual image digest %s. Expected %s." % (digest, sig_data[2]))

        try:
            vk.verify(
                sig_data[-2][::-1],
                digest,
                padding.PSS(
                    mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=32
                ),
                utils.Prehashed(hashes.SHA256())
            )
            print("Signature block %d verification successful with %s." % (sig_blk_num, args.keyfile.name))
            return
        except exceptions.InvalidSignature:
            print("Signature block %d is not signed by %s. Checking the next block" % (sig_blk_num, args.keyfile.name))
            continue
    raise esptool.FatalError("Checked all blocks. Signature could not be verified with the provided key.") 
開發者ID:espressif,項目名稱:esptool,代碼行數:41,代碼來源:espsecure.py

示例10: is_signature_valid

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def is_signature_valid(encoded_signature, signature_digest, public_key_bytes):
        try:
            public_key = load_der_public_key(public_key_bytes, default_backend())
            public_key.verify(encoded_signature, signature_digest, ec.ECDSA(Prehashed(hashes.SHA256())))
            return True
        except (ValueError, InvalidSignature):
            pass
        return False 
開發者ID:lbryio,項目名稱:lbry-sdk,代碼行數:10,代碼來源:transaction.py

示例11: generate_signature

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def generate_signature(self, file_obj):
        file_obj.seek(0)
        chunked_file = IterableChunkedFile(file_obj)
        for chunk in chunked_file:
            self.hasher.update(chunk)
        file_obj.seek(0)
        digest = self.hasher.finalize()
        signature = self.private_key.sign(
            digest, self.padding, utils.Prehashed(self.hash)
        )
        return signature 
開發者ID:openstack,項目名稱:openstacksdk,代碼行數:13,代碼來源:image_signer.py

示例12: Sign

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def Sign(self, data):
        """Signs given data using a private key.

        Parameters
        ----------
        data : TODO
            TODO

        Returns
        -------
        TODO
            The signed ``data``

        """
        return self.rsa_key.sign(data, padding.PKCS1v15(), utils.Prehashed(hashes.SHA1())) 
開發者ID:JeffLIrion,項目名稱:adb_shell,代碼行數:17,代碼來源:sign_cryptography.py

示例13: Sign

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def Sign(self, data):
        return self.rsa_key.sign(
            data, padding.PKCS1v15(), utils.Prehashed(hashes.SHA1())) 
開發者ID:google,項目名稱:python-adb,代碼行數:5,代碼來源:sign_cryptography.py

示例14: verify

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def verify(self, message: bytes,
               verifying_key: UmbralPublicKey,
               is_prehashed: bool = False) -> bool:
        """
        Verifies that a message's signature was valid.

        :param message: The message to verify
        :param verifying_key: UmbralPublicKey of the signer
        :param is_prehashed: True if the message has been prehashed previously
        :return: True if valid, False if invalid
        """
        cryptography_pub_key = verifying_key.to_cryptography_pubkey()
        if is_prehashed:
            signature_algorithm = ECDSA(utils.Prehashed(self.hash_algorithm()))
        else:
            signature_algorithm = ECDSA(self.hash_algorithm())

        # TODO: Raise error instead of returning boolean
        try:
            cryptography_pub_key.verify(
                signature=self._der_encoded_bytes(),
                data=message,
                signature_algorithm=signature_algorithm
            )
        except InvalidSignature:
            return False
        return True 
開發者ID:nucypher,項目名稱:pyUmbral,代碼行數:29,代碼來源:signing.py

示例15: __call__

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import utils [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.utils import Prehashed [as 別名]
def __call__(self, message: bytes, is_prehashed: bool = False) -> Signature:
        """
         Signs the message with this instance's private key.

         :param message: Message to hash and sign
         :param is_prehashed: True if the message has been prehashed previously
         :return: signature
         """
        if is_prehashed:
            signature_algorithm = ECDSA(utils.Prehashed(self.hash_algorithm()))
        else:
            signature_algorithm = ECDSA(self.hash_algorithm())

        signature_der_bytes = self.__cryptography_private_key.sign(message, signature_algorithm)
        return Signature.from_bytes(signature_der_bytes, der_encoded=True, curve=self.curve) 
開發者ID:nucypher,項目名稱:pyUmbral,代碼行數:17,代碼來源:signing.py


注:本文中的cryptography.hazmat.primitives.asymmetric.utils.Prehashed方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。