当前位置: 首页>>代码示例>>Python>>正文


Python hashes.SHA256属性代码示例

本文整理汇总了Python中cryptography.hazmat.primitives.hashes.SHA256属性的典型用法代码示例。如果您正苦于以下问题:Python hashes.SHA256属性的具体用法?Python hashes.SHA256怎么用?Python hashes.SHA256使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在cryptography.hazmat.primitives.hashes的用法示例。


在下文中一共展示了hashes.SHA256属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def validate(self, authenticator_data, rp_id_hash, client_data_hash):
        # See https://www.w3.org/TR/webauthn/#fido-u2f-attestation, "Verification procedure"
        credential = authenticator_data.credential
        public_key_u2f = b'\x04' + credential.public_key.x + credential.public_key.y
        verification_data = b'\x00' + rp_id_hash + client_data_hash + credential.id + public_key_u2f
        assert len(credential.public_key.x) == 32
        assert len(credential.public_key.y) == 32
        self.cert_public_key.verify(self.signature, verification_data, ec.ECDSA(hashes.SHA256()))
        key_id = x509.SubjectKeyIdentifier.from_public_key(self.cert_public_key).digest.hex()
        att_root_cert_chain = self.metadata_for_key_id(key_id)["attestationRootCertificates"]

        # TODO: implement full cert chain validation
        # See https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Certificate.tbs_certificate_bytes
        # See https://github.com/pyca/cryptography/issues/2381
        # See https://github.com/wbond/certvalidator
        assert len(att_root_cert_chain) == 1
        att_root_cert = x509.load_der_x509_certificate(att_root_cert_chain[0].encode(),
                                                       cryptography.hazmat.backends.default_backend())
        att_root_cert.public_key().verify(self.att_cert.signature,
                                          self.att_cert.tbs_certificate_bytes,
                                          padding.PKCS1v15(),
                                          self.att_cert.signature_hash_algorithm)
        return self.validated_attestation(type="Basic", trust_path="x5c", credential=credential) 
开发者ID:pyauth,项目名称:pywarp,代码行数:25,代码来源:attestation.py

示例2: encryption_step_5

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def encryption_step_5(self, module, message, additional_data, cm):
		client_ephemeral_public = message[len(self.cmh_struct_encryption[4][0]):]

		c = module.lookup_client_pub(additional_data)

		try:
			public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, "\x04"+client_ephemeral_public)
		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_ephemeral_public_key = public_numbers.public_key(default_backend())

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

		module.post_encryption_server(message[len(self.cmh_struct_encryption[4][0]):], additional_data)

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

		return module.cmh_struct[cm][3]

	# checking for the key file values in the config 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:26,代码来源:enc_advanced.py

示例3: _get_key

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def _get_key():
    if this.key:
        return this.key

    secret = getpass.getpass()
    try:
        salt = config().get('Security', 'salt')
    except NoOptionError:
        salt = base64.urlsafe_b64encode(os.urandom(16))
        config().set('Security', 'salt', salt)

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
        backend=default_backend()
    )
    this.key = base64.urlsafe_b64encode(kdf.derive(secret))
    return this.key 
开发者ID:rtshome,项目名称:pgrepup,代码行数:22,代码来源:crypt.py

示例4: encrypt

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def encrypt(message, receiver_public_key):
    sender_private_key = ec.generate_private_key(ec.SECP256K1(), backend)
    shared_key = sender_private_key.exchange(ec.ECDH(), receiver_public_key)
    sender_public_key = sender_private_key.public_key()
    point = sender_public_key.public_numbers().encode_point()
    iv = '000000000000'
    xkdf = x963kdf.X963KDF(
        algorithm = hashes.SHA256(),
        length = 32,
        sharedinfo = '',
        backend = backend
        )
    key = xkdf.derive(shared_key)
    encryptor = Cipher(
        algorithms.AES(key),
        modes.GCM(iv),
        backend = backend
        ).encryptor()
    ciphertext = encryptor.update(message) + encryptor.finalize()
    return point + encryptor.tag + ciphertext 
开发者ID:ethereans,项目名称:github-token,代码行数:22,代码来源:encrypted_queries_tools.py

示例5: decrypt

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def decrypt(message, receiver_private_key):
    point = message[0:65]
    tag = message[65:81]
    ciphertext = message[81:]
    sender_public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), point)
    sender_public_key = sender_public_numbers.public_key(backend)
    shared_key = receiver_private_key.exchange(ec.ECDH(), sender_public_key)
    iv = '000000000000'
    xkdf = x963kdf.X963KDF(
        algorithm = hashes.SHA256(),
        length = 32,
        sharedinfo = '',
        backend = backend
        )
    key = xkdf.derive(shared_key)
    decryptor = Cipher(
        algorithms.AES(key),
        modes.GCM(iv,tag),
        backend = backend
        ).decryptor()
    message = decryptor.update(ciphertext) +  decryptor.finalize()
    return message 
开发者ID:ethereans,项目名称:github-token,代码行数:24,代码来源:encrypted_queries_tools.py

示例6: create

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def create(cls, client, password, cert_data):
        """Create a new certificate."""
        cert = x509.load_pem_x509_certificate(cert_data, default_backend())
        base64_cert = cert.public_bytes(Encoding.PEM).decode('utf-8')
        # STRIP OUT CERT META "-----BEGIN CERTIFICATE-----"
        base64_cert = '\n'.join(base64_cert.split('\n')[1:-2])
        data = {
            'type': 'client',
            'certificate': base64_cert,
            'password': password,
        }
        client.api.certificates.post(json=data)

        # XXX: rockstar (08 Jun 2016) - Please see the open lxd bug here:
        # https://github.com/lxc/lxd/issues/2092
        fingerprint = binascii.hexlify(
            cert.fingerprint(hashes.SHA256())).decode('utf-8')
        return cls.get(client, fingerprint) 
开发者ID:lxc,项目名称:pylxd,代码行数:20,代码来源:certificate.py

示例7: _derive_keys

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def _derive_keys(self, password=None):
        label = encode(self.encryption_oid) + encode(self.mac_oid)
        context = self.nonce.asOctets()
        backend = default_backend()

        kdf = KBKDFHMAC(
            algorithm=hashes.SHA256(),
            mode=Mode.CounterMode,
            length=48,
            rlen=4,
            llen=4,
            location=CounterLocation.BeforeFixed,
            label=label,
            context=context,
            fixed=None,
            backend=backend
        )

        key = kdf.derive(password)
        if self.DEBUG:
            sys.stderr.write("Derived key: {0}\n".format(key))

        self.encryption_key = key[0:16]
        self.mac_key = key[16:] 
开发者ID:fireeye,项目名称:ADFSpoof,代码行数:26,代码来源:EncryptedPfx.py

示例8: _get_key

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def _get_key(self, alg, key, p2s, p2c):
        if isinstance(key, bytes):
            plain = key
        else:
            plain = key.encode('utf8')
        salt = bytes(self.name.encode('utf8')) + b'\x00' + p2s

        if self.hashsize == 256:
            hashalg = hashes.SHA256()
        elif self.hashsize == 384:
            hashalg = hashes.SHA384()
        elif self.hashsize == 512:
            hashalg = hashes.SHA512()
        else:
            raise ValueError('Unknown Hash Size')

        kdf = PBKDF2HMAC(algorithm=hashalg, length=_inbytes(self.keysize),
                         salt=salt, iterations=p2c, backend=self.backend)
        rk = kdf.derive(plain)
        if _bitsize(rk) != self.keysize:
            raise InvalidJWEKeyLength(self.keysize, len(rk))
        return JWK(kty="oct", use="enc", k=base64url_encode(rk)) 
开发者ID:latchset,项目名称:jwcrypto,代码行数:24,代码来源:jwa.py

示例9: generate_csr

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def generate_csr(common_name, dnsnames, ips, keysize):
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=keysize,
        backend=default_backend()
    )

    key_pem = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )

    csr = x509.CertificateSigningRequestBuilder()
    csr = csr.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]))
    csr = csr.add_extension(
        x509.SubjectAlternativeName(dnsnames + ips),
        critical=False,
    )
    csr = csr.sign(key, hashes.SHA256(), default_backend())

    csr_pem = csr.public_bytes(serialization.Encoding.PEM)

    return key_pem, csr_pem 
开发者ID:python,项目名称:pypi-infra,代码行数:26,代码来源:requestor.py

示例10: kdf

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def kdf(key_material: bytes) -> bytes:
    """NIST SP 800-56a Concatenation Key Derivation Function (see section 5.8.1).

    Pretty much copied from geth's implementation:
    https://github.com/ethereum/go-ethereum/blob/673007d7aed1d2678ea3277eceb7b55dc29cf092/crypto/ecies/ecies.go#L167
    """
    key = b""
    hash_blocksize = hashes.SHA256().block_size
    reps = ((KEY_LEN + 7) * 8) / (hash_blocksize * 8)
    counter = 0
    while counter <= reps:
        counter += 1
        ctx = sha256()
        ctx.update(struct.pack(">I", counter))
        ctx.update(key_material)
        key += ctx.digest()
    return key[:KEY_LEN] 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:19,代码来源:ecies.py

示例11: generate_signature

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def generate_signature(self, pri_key: str, msg: bytes) -> str:
        if self.__scheme == SignatureScheme.SHA224withECDSA:
            private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP224R1(), default_backend())
            signature = private_key.sign(
                msg,
                ec.ECDSA(hashes.SHA224())
            )
        elif self.__scheme == SignatureScheme.SHA256withECDSA:
            private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP256R1(), default_backend())
            signature = private_key.sign(
                msg,
                ec.ECDSA(hashes.SHA256())
            )
        elif self.__scheme == SignatureScheme.SHA384withECDSA:
            private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP384R1(), default_backend())
            signature = private_key.sign(
                msg,
                ec.ECDSA(hashes.SHA384())
            )
        else:
            raise SDKException(ErrorCode.other_error('Invalid signature scheme.'))
        sign = SignatureHandler.dsa_der_to_plain(signature)
        return sign 
开发者ID:ontio,项目名称:ontology-python-sdk,代码行数:25,代码来源:signature_handler.py

示例12: sign

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def sign(self, s):
        """
        Create a signature of the string s

        :param s: String to sign
        :type s: str
        :return: The hexlified and versioned signature of the string
        :rtype: str
        """
        if not self.private:
            log.info('Could not sign message {0!s}, no private key!'.format(s))
            # TODO: should we throw an exception in this case?
            return ''

        signature = self.private.sign(
            to_bytes(s),
            asym_padding.PSS(
                mgf=asym_padding.MGF1(hashes.SHA256()),
                salt_length=asym_padding.PSS.MAX_LENGTH),
            hashes.SHA256())
        res = ':'.join([self.sig_ver, hexlify_and_unicode(signature)])
        return res 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:24,代码来源:crypto.py

示例13: _encrypt_from_parts

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def _encrypt_from_parts(self, data, current_time, iv):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
        )

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:21,代码来源:fernet.py

示例14: __init__

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def __init__(self, key, length, algorithm, backend):
        if not isinstance(backend, HMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement HMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE
            )

        if len(key) < 16:
            raise ValueError("Key length has to be at least 128 bits.")

        if not isinstance(length, six.integer_types):
            raise TypeError("Length parameter must be an integer type.")

        if length < 6 or length > 8:
            raise ValueError("Length of HOTP has to be between 6 to 8.")

        if not isinstance(algorithm, (SHA1, SHA256, SHA512)):
            raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.")

        self._key = key
        self._length = length
        self._algorithm = algorithm
        self._backend = backend 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:25,代码来源:hotp.py

示例15: encrypt

# 需要导入模块: from cryptography.hazmat.primitives import hashes [as 别名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA256 [as 别名]
def encrypt(input_str, key, iterations=100000):
    """Basic encryption with a predefined key. Its purpose is to protect not very important data, just to avoid
    saving them as plaintext."""

    salt = b'D9\x82\xbfSibW(\xb1q\xeb\xd1\x84\x118'
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=iterations,
        backend=default_backend()
    )
    key = base64.urlsafe_b64encode(kdf.derive(key.encode('utf-8')))
    fer = Fernet(key)
    h = fer.encrypt(input_str.encode('utf-8'))
    h = h.hex()
    return h 
开发者ID:Bertrand256,项目名称:dash-masternode-tool,代码行数:19,代码来源:app_utils.py


注:本文中的cryptography.hazmat.primitives.hashes.SHA256属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。