本文整理匯總了Python中cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey方法的典型用法代碼示例。如果您正苦於以下問題:Python rsa.RSAPrivateKey方法的具體用法?Python rsa.RSAPrivateKey怎麽用?Python rsa.RSAPrivateKey使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cryptography.hazmat.primitives.asymmetric.rsa
的用法示例。
在下文中一共展示了rsa.RSAPrivateKey方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: create_key
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def create_key(key_path: str) -> rsa.RSAPrivateKey:
key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
with open(key_path, "wb") as filehandle:
filehandle.write(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
return key
示例2: from_cryptography_key
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [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
示例3: type
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [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,))
示例4: getFileSignature
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def getFileSignature(cls, filename: str, private_key: RSAPrivateKey) -> Optional[str]:
"""Creates the signature for the (hash of the) provided file, given a private key.
:param filename: The file to be signed.
:param private_key: The private key used for signing.
:return: The signature if successful, 'None' otherwise.
"""
file_hash = cls.getFileHash(filename)
if file_hash is None:
return None
try:
file_hash_bytes = base64.b64decode(file_hash)
signature_bytes = private_key.sign(
file_hash_bytes,
padding.PSS(mgf = padding.MGF1(cls.__hash_algorithm), salt_length = padding.PSS.MAX_LENGTH),
Prehashed(cls.__hash_algorithm)
)
return base64.b64encode(signature_bytes).decode("utf-8")
except: # Yes, we do really want this on _every_ exception that might occur.
Logger.logException("e", "Couldn't sign '{0}', no signature generated.".format(filename))
return None
示例5: loadPrivateKey
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def loadPrivateKey(private_filename: str, optional_password: Optional[str]) -> Optional[RSAPrivateKey]:
"""Load a private key from a file.
:param private_filename: The filename of the file containing the private key.
:param optional_password: The key can be signed with a password as well (or not).
:return: The private key contained in the file.
"""
try:
password_bytes = None if optional_password is None else optional_password.encode()
with open(private_filename, "rb") as file:
private_key = load_pem_private_key(file.read(), backend=default_backend(), password=password_bytes)
return private_key
except: # Yes, we do really want this on _every_ exception that might occur.
Logger.logException("e", "Couldn't load private-key.")
return None
示例6: decrypt
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def decrypt(smime: bytes, key: rsa.RSAPrivateKey, serial: Optional[int] = None):
"""Decrypt an S/MIME message using the RSA Private Key given.
The recipient can be hinted using the serial parameter, otherwise we assume single recipient = the given key.
"""
string_content = smime.decode('utf8')
msg: Message = email.message_from_string(string_content)
assert msg.get_content_type() == 'application/pkcs7-mime'
assert msg.get_filename() == 'smime.p7m'
assert msg.get('Content-Description') == 'S/MIME Encrypted Message'
b64payload = msg.get_payload()
payload = b64decode(b64payload)
decrypted_data = decrypt_smime_content(payload, key)
decrypted_msg: Message = email.message_from_bytes(decrypted_data)
return decrypted_msg.get_payload()
示例7: certificate
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
b = x509.CertificateBuilder()
name = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Commandment"),
x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
])
cer = b.subject_name(name).issuer_name(name).public_key(
private_key.public_key()
).serial_number(1).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=10)
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), True
).sign(private_key, hashes.SHA256(), default_backend())
return cer
示例8: ca_certificate
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def ca_certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
b = x509.CertificateBuilder()
name = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Commandment"),
x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
])
cert = b.serial_number(1).issuer_name(
name
).subject_name(
name
).public_key(
private_key.public_key()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=10)
).add_extension(
x509.BasicConstraints(ca=True, path_length=None), True
).sign(private_key, hashes.SHA256(), default_backend())
return cert
示例9: assertKey
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def assertKey(self, ca, key_type=RSAPrivateKey, password=None):
priv_path = 'ocsp/%s.key' % ca.serial
cert_path = 'ocsp/%s.pem' % ca.serial
self.assertTrue(ca_storage.exists(priv_path))
self.assertTrue(ca_storage.exists(cert_path))
with ca_storage.open(priv_path, 'rb') as stream:
priv = stream.read()
priv = load_pem_private_key(priv, password, default_backend())
self.assertIsInstance(priv, key_type)
with ca_storage.open(cert_path, 'rb') as stream:
cert = stream.read()
cert = x509.load_pem_x509_certificate(cert, default_backend())
self.assertIsInstance(cert, x509.Certificate)
db_cert = Certificate.objects.exclude(pk__in=self.existing_certs).first()
self.assertEqual(db_cert.authority_information_access.ocsp, [])
return priv, cert
示例10: test_basic
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def test_basic(self):
with self.assertSignal(pre_create_ca) as pre, self.assertSignal(post_create_ca) as post:
out, err = self.init_ca()
self.assertTrue(pre.called)
self.assertEqual(out, '')
self.assertEqual(err, '')
ca = CertificateAuthority.objects.first()
self.assertPostCreateCa(post, ca)
self.assertPrivateKey(ca)
self.assertSerial(ca.serial)
self.assertSignature([ca], ca)
ca.full_clean() # assert e.g. max_length in serials
self.assertBasic(ca.x509, algo='sha512')
# test the private key
key = ca.key(None)
self.assertIsInstance(key, RSAPrivateKey)
self.assertEqual(key.key_size, 1024)
self.assertSubject(ca.x509, [('C', 'AT'), ('ST', 'Vienna'), ('L', 'Vienna'),
('O', 'Org'), ('OU', 'OrgUnit'), ('CN', 'Test CA')])
self.assertIssuer(ca, ca)
self.assertAuthorityKeyIdentifier(ca, ca)
self.assertEqual(ca.serial, int_to_hex(ca.x509.serial_number))
示例11: verify_ssh_sig
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def verify_ssh_sig(self, data, msg):
if msg.get_text() != 'ssh-rsa':
return False
key = self.key
if isinstance(key, rsa.RSAPrivateKey):
key = key.public_key()
verifier = key.verifier(
signature=msg.get_binary(),
padding=padding.PKCS1v15(),
algorithm=hashes.SHA1(),
)
verifier.update(data)
try:
verifier.verify()
except InvalidSignature:
return False
else:
return True
示例12: generate_rsa_private_key
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def generate_rsa_private_key(key_size=2048, public_exponent=65537):
"""
Generate RSA private key.
Args:
key_size (int): RSA key size
public_exponent (int): Key public exponent
Return:
rsa.RSAPrivateKey
"""
return rsa.generate_private_key(
public_exponent=public_exponent,
key_size=key_size,
backend=cryptography_default_backend
)
示例13: generate_valid_root_ca_cert_pem
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def generate_valid_root_ca_cert_pem(private_key):
"""
Helper to create and serialize root CA cert.
Args:
private_key (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey): Key that
should be used for signing the certificate.
Return:
PEM text representing serialized certificate.
"""
return serialize_cert_to_pem(
sign_cert_builder(
ca_cert_builder(
private_key.public_key(),
),
private_key
)
)
示例14: __init__
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def __init__(self, priv_key, algorithm):
"""Constructor for RsaSign.
Args:
priv_key: rsa.RSAPrivateKey, the RSA private key.
algorithm: string, RSA algorithm as defined at
https://tools.ietf.org/html/rfc7518#section-3.1.
Raises:
TypeError: if the private key is not an instance of rsa.RSAPrivateKey.
UnsupportedAlgorithm: if the algorithm is not supported.
"""
if not isinstance(priv_key, rsa.RSAPrivateKey):
raise TypeError(
"The private key must be an instance of rsa.RSAPrivateKey")
self.priv_key = priv_key
self.algorithm = algorithm
(self.hash, self.padding) = jwsutil.parse_rsa_algorithm(algorithm)
示例15: decode_pem_key
# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import rsa [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey [as 別名]
def decode_pem_key(key_pem):
"""Convert plaintext PEM key into the format usable for JWT generation
Args:
key_pam (str): key data in PEM format, presented as plain string
Returns:
Parsed PEM data
"""
private_key = serialization.load_pem_private_key(
data=key_pem.encode('ascii'),
password=None,
backend=default_backend())
msg = 'Unexpected private key type'
assert isinstance(private_key, rsa.RSAPrivateKey), msg
assert private_key.key_size >= 2048, 'RSA key size too small'
return private_key