本文整理汇总了Python中cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey方法的典型用法代码示例。如果您正苦于以下问题:Python rsa.RSAPublicKey方法的具体用法?Python rsa.RSAPublicKey怎么用?Python rsa.RSAPublicKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.hazmat.primitives.asymmetric.rsa
的用法示例。
在下文中一共展示了rsa.RSAPublicKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: from_cryptography_key
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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
示例2: type
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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,))
示例3: _key_identifier_from_public_key
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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()
示例4: __init__
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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]
示例5: test_basic
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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)
示例6: _scan_a_cert
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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)
示例7: __init__
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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)
示例8: _key_identifier_from_public_key
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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()
示例9: _get_rsa_parameters
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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
示例10: _get_basic_certificate_text
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
def _get_basic_certificate_text(cls, certificate: Certificate) -> List[str]:
text_output = [
cls._format_field(
"SHA1 Fingerprint:", binascii.hexlify(certificate.fingerprint(hashes.SHA1())).decode("ascii")
),
cls._format_field("Common Name:", _get_name_as_short_text(certificate.subject)),
cls._format_field("Issuer:", _get_name_as_short_text(certificate.issuer)),
cls._format_field("Serial Number:", str(certificate.serial_number)),
cls._format_field("Not Before:", certificate.not_valid_before.date().isoformat()),
cls._format_field("Not After:", certificate.not_valid_after.date().isoformat()),
cls._format_field("Public Key Algorithm:", certificate.public_key().__class__.__name__),
]
if certificate.signature_hash_algorithm:
# The signature_hash_algorithm can be None if signature did not use separate hash (ED25519, ED448)
# https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Certificate.signature_hash_algorithm
text_output.append(cls._format_field("Signature Algorithm:", certificate.signature_hash_algorithm.name))
public_key = certificate.public_key()
if isinstance(public_key, EllipticCurvePublicKey):
text_output.append(cls._format_field("Key Size:", str(public_key.curve.key_size)))
text_output.append(cls._format_field("Curve:", str(public_key.curve.name)))
elif isinstance(public_key, RSAPublicKey):
text_output.append(cls._format_field("Key Size:", str(public_key.key_size)))
text_output.append(cls._format_field("Exponent:", str(public_key.public_numbers().e))) # type: ignore
else:
# DSA Key? https://github.com/nabla-c0d3/sslyze/issues/314
pass
try:
# Print the SAN extension if there's one
text_output.append(
cls._format_field(
"DNS Subject Alternative Names:", str(extract_dns_subject_alternative_names(certificate))
)
)
except KeyError:
pass
return text_output
示例11: _serialize_public_ssh_key
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
def _serialize_public_ssh_key(key):
if isinstance(key, rsa.RSAPublicKey):
public_numbers = key.public_numbers()
return b"ssh-rsa " + base64.b64encode(
_ssh_write_string(b"ssh-rsa")
+ _ssh_write_mpint(public_numbers.e)
+ _ssh_write_mpint(public_numbers.n)
)
else:
# Since we only write RSA keys, drop the other serializations
return
示例12: import_from_pyca
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
def import_from_pyca(self, key):
if isinstance(key, rsa.RSAPrivateKey):
self._import_pyca_pri_rsa(key)
elif isinstance(key, rsa.RSAPublicKey):
self._import_pyca_pub_rsa(key)
elif isinstance(key, ec.EllipticCurvePrivateKey):
self._import_pyca_pri_ec(key)
elif isinstance(key, ec.EllipticCurvePublicKey):
self._import_pyca_pub_ec(key)
elif isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)):
self._import_pyca_pri_okp(key)
elif isinstance(key, (Ed25519PublicKey, Ed448PublicKey)):
self._import_pyca_pub_okp(key)
else:
raise InvalidJWKValue('Unknown key object %r' % key)
示例13: public_key
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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
)
示例14: isPublic
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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))
示例15: _openssh_public_key_bytes
# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import rsa [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey [as 别名]
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())
)