Python cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey() Examples
The following are 30
code examples of cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cryptography.hazmat.primitives.asymmetric.rsa
, or try the search function
.
Example #1
Source File: certificates.py From core with GNU General Public License v3.0 | 7 votes |
def _scan_a_cert(id, cert_path, key_path, assigns, is_acme=False): with open(cert_path, "rb") as f: crt = x509.load_pem_x509_certificate(f.read(), default_backend()) with open(key_path, "rb") as f: key = serialization.load_pem_private_key( f.read(), password=None, backend=default_backend() ) sha1 = binascii.hexlify(crt.fingerprint(hashes.SHA1())).decode() md5 = binascii.hexlify(crt.fingerprint(hashes.MD5())).decode() sha1 = ":".join([sha1[i:i+2].upper() for i in range(0, len(sha1), 2)]) md5 = ":".join([md5[i:i+2].upper() for i in range(0, len(md5), 2)]) kt = "RSA" if isinstance(key.public_key(), rsa.RSAPublicKey) else "DSA" common_name = crt.subject.get_attributes_for_oid(NameOID.COMMON_NAME) return Certificate( id=id, cert_path=cert_path, key_path=key_path, keytype=kt, keylength=key.key_size, domain=common_name[0].value, assigns=assigns.get(id, []), expiry=crt.not_valid_after, sha1=sha1, md5=md5, is_acme=is_acme)
Example #2
Source File: Trust.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, public_key_filename: str, pre_err_handler: Callable[[str], None] = None) -> None: """Initializes a Trust object. A Trust object represents a public key and related utility methods on that key. If the application only has a single public key, it's best to use 'getInstance' or 'getInstanceOrNone'. :param public_key_filename: Path to the file that holds the public key. :param pre_err_handler: An extra error handler which will be called before TrustBasics.defaultViolationHandler Receives a human readable error string as argument. :raise Exception: if public key file provided by the argument can't be found or parsed. """ self._public_key = None # type: Optional[RSAPublicKey] try: with open(public_key_filename, "rb") as file: self._public_key = load_pem_public_key(file.read(), backend = default_backend()) except: # Yes, we do really want this on _every_ exception that might occur. self._public_key = None raise Exception("e", "Couldn't load public-key '{0}'.".format(public_key_filename)) # NOTE: Handle _potential_ security violation outside of this initializer, in case it's just for validation. def violation_handler(message: str): if pre_err_handler is not None: pre_err_handler(message) TrustBasics.defaultViolationHandler(message=message) self._violation_handler = violation_handler # type: Callable[[str], None]
Example #3
Source File: extensions.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint ) else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo ) data = bytes(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
Example #4
Source File: crypto.py From learn_python3_spider with MIT License | 6 votes |
def from_cryptography_key(cls, crypto_key): """ Construct based on a ``cryptography`` *crypto_key*. :param crypto_key: A ``cryptography`` key. :type crypto_key: One of ``cryptography``'s `key interfaces`_. :rtype: PKey .. versionadded:: 16.1.0 """ pkey = cls() if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey, dsa.DSAPublicKey, dsa.DSAPrivateKey)): raise TypeError("Unsupported key type") pkey._pkey = crypto_key._evp_pkey if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)): pkey._only_public = True pkey._initialized = True return pkey
Example #5
Source File: keys.py From learn_python3_spider with MIT License | 6 votes |
def type(self): """ Return the type of the object we wrap. Currently this can only be 'RSA', 'DSA', or 'EC'. @rtype: L{str} @raises RuntimeError: If the object type is unknown. """ if isinstance( self._keyObject, (rsa.RSAPublicKey, rsa.RSAPrivateKey)): return 'RSA' elif isinstance( self._keyObject, (dsa.DSAPublicKey, dsa.DSAPrivateKey)): return 'DSA' elif isinstance( self._keyObject, (ec.EllipticCurvePublicKey, ec.EllipticCurvePrivateKey)): return 'EC' else: raise RuntimeError( 'unknown type of object: %r' % (self._keyObject,))
Example #6
Source File: extensions.py From quickstart-redhat-openshift with Apache License 2.0 | 6 votes |
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint ) else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo ) data = bytes(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
Example #7
Source File: tests_querysets.py From django-ca with GNU General Public License v3.0 | 6 votes |
def test_basic(self): key_size = ca_settings.CA_MIN_KEY_SIZE ca = CertificateAuthority.objects.init( name='Root CA', key_size=key_size, key_type='RSA', algorithm=hashes.SHA256(), expires=self.expires(720), parent=None, pathlen=0, subject=Subject([('CN', 'ca.example.com')])) self.assertEqual(ca.name, 'Root CA') # verify private key properties self.assertEqual(ca.key(None).key_size, 1024) self.assertIsInstance(ca.key(None).public_key(), RSAPublicKey) # verity public key propertiesa self.assertBasic(ca.x509) self.assertEqual(ca.subject, Subject({'CN': 'ca.example.com'})) # verify X509 properties self.assertEqual(ca.basic_constraints, BasicConstraints({'critical': True, 'value': {'ca': True, 'pathlen': 0}})) self.assertEqual(ca.key_usage, KeyUsage({'critical': True, 'value': ['cRLSign', 'keyCertSign']})) self.assertIsNone(ca.subject_alternative_name, None) self.assertIsNone(ca.extended_key_usage) self.assertIsNone(ca.tls_feature) self.assertIsNone(ca.issuer_alternative_name)
Example #8
Source File: crypto.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def from_cryptography_key(cls, crypto_key): """ Construct based on a ``cryptography`` *crypto_key*. :param crypto_key: A ``cryptography`` key. :type crypto_key: One of ``cryptography``'s `key interfaces`_. :rtype: PKey .. versionadded:: 16.1.0 """ pkey = cls() if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey, dsa.DSAPublicKey, dsa.DSAPrivateKey)): raise TypeError("Unsupported key type") pkey._pkey = crypto_key._evp_pkey if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)): pkey._only_public = True pkey._initialized = True return pkey
Example #9
Source File: rsa_verify.py From jws with Apache License 2.0 | 6 votes |
def __init__(self, pub_key, algorithm): """Constructor for RsaVerify. Args: pub_key: rsa.RSAPublicKey algorithm: string, RSA algorithm as defined at https://tools.ietf.org/html/rfc7518#section-3.1. Raises: TypeError: if public key is not an instance of rsa.RSAPublicKey. UnsupportedAlgorithm: if the algorithm is not supported. """ if not isinstance(pub_key, rsa.RSAPublicKey): raise TypeError("The public key must be an instance of RSAPublicKey") self.pub_key = pub_key self.algorithm = algorithm (self.hash, self.padding) = jwsutil.parse_rsa_algorithm(algorithm)
Example #10
Source File: keys.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def type(self): """ Return the type of the object we wrap. Currently this can only be 'RSA', 'DSA', or 'EC'. @rtype: L{str} @raises RuntimeError: If the object type is unknown. """ if isinstance( self._keyObject, (rsa.RSAPublicKey, rsa.RSAPrivateKey)): return 'RSA' elif isinstance( self._keyObject, (dsa.DSAPublicKey, dsa.DSAPrivateKey)): return 'DSA' elif isinstance( self._keyObject, (ec.EllipticCurvePublicKey, ec.EllipticCurvePrivateKey)): return 'EC' else: raise RuntimeError( 'unknown type of object: %r' % (self._keyObject,))
Example #11
Source File: extensions.py From quickstart-git2s3 with Apache License 2.0 | 6 votes |
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_numbers().encode_point() else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo ) data = six.binary_type(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
Example #12
Source File: crypto.py From pyopenssl with Apache License 2.0 | 6 votes |
def from_cryptography_key(cls, crypto_key): """ Construct based on a ``cryptography`` *crypto_key*. :param crypto_key: A ``cryptography`` key. :type crypto_key: One of ``cryptography``'s `key interfaces`_. :rtype: PKey .. versionadded:: 16.1.0 """ pkey = cls() if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey, dsa.DSAPublicKey, dsa.DSAPrivateKey)): raise TypeError("Unsupported key type") pkey._pkey = crypto_key._evp_pkey if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)): pkey._only_public = True pkey._initialized = True return pkey
Example #13
Source File: extensions.py From teleport with Apache License 2.0 | 6 votes |
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_numbers().encode_point() else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo ) data = six.binary_type(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
Example #14
Source File: _robot_tester.py From sslyze with GNU Affero General Public License v3.0 | 5 votes |
def _get_rsa_parameters(server_info: ServerConnectivityInfo, openssl_cipher_string: str) -> Optional[RSAPublicNumbers]: ssl_connection = server_info.get_preconfigured_tls_connection() ssl_connection.ssl_client.set_cipher_list(openssl_cipher_string) parsed_cert = None try: # Perform the SSL handshake ssl_connection.connect() cert_as_pem = ssl_connection.ssl_client.get_received_chain()[0] parsed_cert = load_pem_x509_certificate(cert_as_pem.encode("ascii"), backend=default_backend()) except ServerRejectedTlsHandshake: # Server does not support RSA cipher suites? pass except ClientCertificateRequested: # AD: The server asked for a client cert. We could still retrieve the server certificate, but it is unclear # to me if the ROBOT check is supposed to work even if we do not provide a client cert. My guess is that # it should not work since it requires completing a full handshake, which we can't without a client cert. # Hence, propagate the error to make the check fail. raise finally: ssl_connection.close() if parsed_cert: public_key = parsed_cert.public_key() if isinstance(public_key, RSAPublicKey): return public_key.public_numbers() else: return None else: return None
Example #15
Source File: utils.py From lemur with Apache License 2.0 | 5 votes |
def check_cert_signature(cert, issuer_public_key): """ Check a certificate's signature against an issuer public key. Before EC validation, make sure we support the algorithm, otherwise raise UnsupportedAlgorithm On success, returns None; on failure, raises UnsupportedAlgorithm or InvalidSignature. """ if isinstance(issuer_public_key, rsa.RSAPublicKey): # RSA requires padding, just to make life difficult for us poor developers :( if cert.signature_algorithm_oid == x509.SignatureAlgorithmOID.RSASSA_PSS: # In 2005, IETF devised a more secure padding scheme to replace PKCS #1 v1.5. To make sure that # nobody can easily support or use it, they mandated lots of complicated parameters, unlike any # other X.509 signature scheme. # https://tools.ietf.org/html/rfc4056 raise UnsupportedAlgorithm("RSASSA-PSS not supported") else: padder = padding.PKCS1v15() issuer_public_key.verify( cert.signature, cert.tbs_certificate_bytes, padder, cert.signature_hash_algorithm, ) elif isinstance(issuer_public_key, ec.EllipticCurvePublicKey) and isinstance( ec.ECDSA(cert.signature_hash_algorithm), ec.ECDSA ): issuer_public_key.verify( cert.signature, cert.tbs_certificate_bytes, ec.ECDSA(cert.signature_hash_algorithm), ) else: raise UnsupportedAlgorithm( "Unsupported Algorithm '{var}'.".format( var=cert.signature_algorithm_oid._name ) )
Example #16
Source File: x509.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_signature_valid(self, public_key): if not isinstance(public_key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') res = self._backend._lib.X509_CRL_verify( self._x509_crl, public_key._evp_pkey ) if res != 1: self._backend._consume_errors() return False return True
Example #17
Source File: base.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def public_key(self, key): """ Sets the requestor's public key (as found in the signing request). """ if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') if self._public_key is not None: raise ValueError('The public key may only be set once.') return CertificateBuilder( self._issuer_name, self._subject_name, key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
Example #18
Source File: padding.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def calculate_max_pss_salt_length(key, hash_algorithm): if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): raise TypeError("key must be an RSA public or private key") # bit length - 1 per RFC 3447 emlen = int(math.ceil((key.key_size - 1) / 8.0)) salt_length = emlen - hash_algorithm.digest_size - 2 assert salt_length >= 0 return salt_length
Example #19
Source File: x509.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def is_signature_valid(self, public_key): if not isinstance(public_key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') res = self._backend._lib.X509_CRL_verify( self._x509_crl, public_key._evp_pkey ) if res != 1: self._backend._consume_errors() return False return True
Example #20
Source File: backend.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def _openssh_public_key_bytes(self, key): if isinstance(key, rsa.RSAPublicKey): public_numbers = key.public_numbers() return b"ssh-rsa " + base64.b64encode( serialization._ssh_write_string(b"ssh-rsa") + serialization._ssh_write_mpint(public_numbers.e) + serialization._ssh_write_mpint(public_numbers.n) ) elif isinstance(key, dsa.DSAPublicKey): public_numbers = key.public_numbers() parameter_numbers = public_numbers.parameter_numbers return b"ssh-dss " + base64.b64encode( serialization._ssh_write_string(b"ssh-dss") + serialization._ssh_write_mpint(parameter_numbers.p) + serialization._ssh_write_mpint(parameter_numbers.q) + serialization._ssh_write_mpint(parameter_numbers.g) + serialization._ssh_write_mpint(public_numbers.y) ) else: assert isinstance(key, ec.EllipticCurvePublicKey) public_numbers = key.public_numbers() try: curve_name = { ec.SECP256R1: b"nistp256", ec.SECP384R1: b"nistp384", ec.SECP521R1: b"nistp521", }[type(public_numbers.curve)] except KeyError: raise ValueError( "Only SECP256R1, SECP384R1, and SECP521R1 curves are " "supported by the SSH public key format" ) return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode( serialization._ssh_write_string(b"ecdsa-sha2-" + curve_name) + serialization._ssh_write_string(curve_name) + serialization._ssh_write_string(public_numbers.encode_point()) )
Example #21
Source File: base.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def public_key(self, key): """ Sets the requestor's public key (as found in the signing request). """ if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') if self._public_key is not None: raise ValueError('The public key may only be set once.') return CertificateBuilder( self._issuer_name, self._subject_name, key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
Example #22
Source File: padding.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def calculate_max_pss_salt_length(key, hash_algorithm): if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): raise TypeError("key must be an RSA public or private key") # bit length - 1 per RFC 3447 emlen = int(math.ceil((key.key_size - 1) / 8.0)) salt_length = emlen - hash_algorithm.digest_size - 2 assert salt_length >= 0 return salt_length
Example #23
Source File: base.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def public_key(self, key): """ Sets the requestor's public key (as found in the signing request). """ if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') if self._public_key is not None: raise ValueError('The public key may only be set once.') return CertificateBuilder( self._issuer_name, self._subject_name, key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
Example #24
Source File: base.py From django-ca with GNU General Public License v3.0 | 5 votes |
def assertBasic(self, cert, algo='SHA256'): """Assert some basic key properties.""" self.assertEqual(cert.version, x509.Version.v3) self.assertIsInstance(cert.public_key(), rsa.RSAPublicKey) self.assertIsInstance(cert.signature_hash_algorithm, getattr(hashes, algo.upper()))
Example #25
Source File: x509.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def is_signature_valid(self, public_key): if not isinstance(public_key, (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey)): raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' ' or EllipticCurvePublicKey.') res = self._backend._lib.X509_CRL_verify( self._x509_crl, public_key._evp_pkey ) if res != 1: self._backend._consume_errors() return False return True
Example #26
Source File: models.py From lemur with Apache License 2.0 | 5 votes |
def key_type(self): if isinstance(self.parsed_cert.public_key(), rsa.RSAPublicKey): return "RSA{key_size}".format( key_size=self.parsed_cert.public_key().key_size )
Example #27
Source File: padding.py From learn_python3_spider with MIT License | 5 votes |
def calculate_max_pss_salt_length(key, hash_algorithm): if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): raise TypeError("key must be an RSA public or private key") # bit length - 1 per RFC 3447 emlen = int(math.ceil((key.key_size - 1) / 8.0)) salt_length = emlen - hash_algorithm.digest_size - 2 assert salt_length >= 0 return salt_length
Example #28
Source File: extensions.py From learn_python3_spider with MIT License | 5 votes |
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint ) else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo ) reader = DERReader(serialized) with reader.read_single_element(SEQUENCE) as public_key_info: algorithm = public_key_info.read_element(SEQUENCE) public_key = public_key_info.read_element(BIT_STRING) # Double-check the algorithm structure. with algorithm: algorithm.read_element(OBJECT_IDENTIFIER) if not algorithm.is_empty(): # Skip the optional parameters field. algorithm.read_any_element() # BIT STRING contents begin with the number of padding bytes added. It # must be zero for SubjectPublicKeyInfo structures. if public_key.read_byte() != 0: raise ValueError('Invalid public key encoding') data = public_key.data return hashlib.sha1(data).digest()
Example #29
Source File: keys.py From learn_python3_spider with MIT License | 5 votes |
def isPublic(self): """ Check if this instance is a public key. @return: C{True} if this is a public key. """ return isinstance( self._keyObject, (rsa.RSAPublicKey, dsa.DSAPublicKey, ec.EllipticCurvePublicKey))
Example #30
Source File: Trust.py From Uranium with GNU Lesser General Public License v3.0 | 5 votes |
def generateNewKeyPair() -> Tuple[RSAPrivateKeyWithSerialization, RSAPublicKey]: """Create a new private-public key-pair. :return: A tulple of private-key/public key. """ private_key = rsa.generate_private_key(public_exponent = 65537, key_size = 4096, backend = default_backend()) return private_key, private_key.public_key()