Python cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey() Examples
The following are 30
code examples of cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey().
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: conftest.py From commandment with MIT License | 6 votes |
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
Example #2
Source File: test_jwt_auth.py From box-python-sdk with Apache License 2.0 | 6 votes |
def test_jwt_auth_init_accepts_rsa_private_key_data(rsa_private_key_bytes, rsa_passphrase, rsa_private_key_data_type): if rsa_private_key_data_type is text_type: rsa_private_key_data = text_type(rsa_private_key_bytes.decode('ascii')) elif rsa_private_key_data_type is RSAPrivateKey: rsa_private_key_data = serialization.load_pem_private_key( rsa_private_key_bytes, password=rsa_passphrase, backend=default_backend(), ) else: rsa_private_key_data = rsa_private_key_data_type(rsa_private_key_bytes) JWTAuth( rsa_private_key_data=rsa_private_key_data, rsa_private_key_passphrase=rsa_passphrase, client_id=None, client_secret=None, jwt_key_id=None, enterprise_id=None, )
Example #3
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 #4
Source File: jwt.py From dcos with Apache License 2.0 | 6 votes |
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
Example #5
Source File: rsa_sign.py From jws with Apache License 2.0 | 6 votes |
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)
Example #6
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 #7
Source File: tls.py From dcos-e2e with Apache License 2.0 | 6 votes |
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 ) )
Example #8
Source File: _certificate_generator.py From webviz-config with MIT License | 6 votes |
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
Example #9
Source File: Trust.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #10
Source File: tls.py From dcos-e2e with Apache License 2.0 | 6 votes |
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 ) )
Example #11
Source File: tls.py From dcos-e2e with Apache License 2.0 | 6 votes |
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 )
Example #12
Source File: Trust.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #13
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 #14
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 #15
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 #16
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 6 votes |
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
Example #17
Source File: smime.py From commandment with MIT License | 6 votes |
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()
Example #18
Source File: tests_command_init_ca.py From django-ca with GNU General Public License v3.0 | 6 votes |
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))
Example #19
Source File: tests_command_regenerate_ocsp_keys.py From django-ca with GNU General Public License v3.0 | 6 votes |
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
Example #20
Source File: test_mdmcert.py From commandment with MIT License | 6 votes |
def csr(private_key: rsa.RSAPrivateKey) -> x509.CertificateSigningRequest: b = x509.CertificateSigningRequestBuilder() req = b.subject_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"Commandment"), ])).sign(private_key, hashes.SHA256(), default_backend()) return req
Example #21
Source File: conftest.py From commandment with MIT License | 6 votes |
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
Example #22
Source File: tls.py From dcos-e2e with Apache License 2.0 | 5 votes |
def serialize_key_to_pem(key): """ Serialize private key to OpenSSL format with PEM encoding. Args: key (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey): Key to serialize Returns: PEM text representing serialized key. """ return key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ).decode('utf-8')
Example #23
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 5 votes |
def public_numbers(self): if isinstance(self.key, rsa.RSAPrivateKey): return self.key.private_numbers().public_numbers else: return self.key.public_numbers()
Example #24
Source File: tls.py From dcos-e2e with Apache License 2.0 | 5 votes |
def generate_root_ca_and_intermediate_ca( number=1, ): """ Helper to create root CA cert and intermediate certs. Args: number (int): Number of intermediate certs. Returns: Certificate chain with each CA certificate followed by its issuer, ending with the self-signed root certificate List[(x509.Certificate, rsa.RSAPrivateKey)] """ chain = [] root_ca_private_key = generate_rsa_private_key() root_ca = sign_cert_builder( ca_cert_builder(root_ca_private_key.public_key()), root_ca_private_key ) chain.append((root_ca, root_ca_private_key)) parent, parent_private_key = root_ca, root_ca_private_key for i in range(0, number): intermediate_ca_private_key = generate_rsa_private_key() intermediate_ca = sign_cert_builder( ca_cert_builder( intermediate_ca_private_key.public_key(), common_name="Intermediate CA {}".format(i), issuer=parent.subject, ), parent_private_key ) chain.append((intermediate_ca, intermediate_ca_private_key)) parent, parent_private_key = intermediate_ca, intermediate_ca_private_key return list(reversed(chain))
Example #25
Source File: tests_command_import_ca.py From django-ca with GNU General Public License v3.0 | 5 votes |
def test_der(self): cas = {name: data for name, data in certs.items() if data.get('key_der_filename') and data['type'] == 'ca'} for name, data in cas.items(): if data.get('password'): continue # TODO: cmd can't parse this yet key_path = os.path.join(settings.FIXTURES_DIR, data['key_der_filename']) pem_path = os.path.join(settings.FIXTURES_DIR, data['pub_der_filename']) out, err = self.cmd('import_ca', name, key_path, pem_path) self.assertEqual(out, '') self.assertEqual(err, '') ca = CertificateAuthority.objects.get(name=name) ca.full_clean() # assert e.g. max_length in serials if not data.get('parent'): self.assertSignature(reversed(ca.bundle), ca) self.assertBasic(ca.x509, algo=data['algorithm']) # test the private key key = ca.key(None) self.assertIsInstance(key, RSAPrivateKey) self.assertEqual(key.key_size, data['key_size']) self.assertEqual(ca.serial, data['serial'])
Example #26
Source File: tests_command_import_ca.py From django-ca with GNU General Public License v3.0 | 5 votes |
def test_basic(self): cas = {name: data for name, data in certs.items() if data['type'] == 'ca' and data.get('key_filename')} for name, data in cas.items(): if data.get('password'): continue # TODO: cmd can't parse this yet key_path = os.path.join(settings.FIXTURES_DIR, data['key_filename']) pem_path = os.path.join(settings.FIXTURES_DIR, data['pub_filename']) out, err = self.cmd('import_ca', name, key_path, pem_path) self.assertEqual(out, '') self.assertEqual(err, '') ca = CertificateAuthority.objects.get(name=name) ca.full_clean() # assert e.g. max_length in serials if not data.get('parent'): self.assertSignature([ca], ca) self.assertBasic(ca.x509, algo=data['algorithm']) # test the private key key = ca.key(data['password']) self.assertIsInstance(key, RSAPrivateKey) self.assertEqual(key.key_size, data['key_size']) self.assertEqual(ca.serial, data['serial'])
Example #27
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 #28
Source File: runtime_credentials.py From calvin-base with Apache License 2.0 | 5 votes |
def sign_data(self, data): from OpenSSL import crypto from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import dsa, rsa from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.serialization import load_pem_private_key private_key_str = self.get_private_key() # The pyOpenSSL sign operation seems broken and corrupts memory, atleast for EC, so let's use # the cryptography package instead # try: # private_key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, # private_key_str, '') # signature = OpenSSL.crypto.sign(private_key, # data, # "sha256") # except Exception as err: # _log.error("Failed to sign data, err={}".format(err)) # raise try: private_key = load_pem_private_key(private_key_str, password=None, backend=default_backend()) if isinstance(private_key, ec.EllipticCurvePrivateKey): signature = private_key.sign(data, ec.ECDSA(hashes.SHA256())) elif isinstance(private_key, rsa.RSAPrivateKey): signature = sign_with_rsa_key(private_key, message) elif isinstance(private_key, dsa.DSAPrivateKey): signature = sign_with_dsa_key(private_key, message) else: raise TypeError except Exception as err: _log.error("Failed to sign data, err={}".format(err)) raise return signature
Example #29
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 #30
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 5 votes |
def _decode_key(self, data): try: key = serialization.load_der_private_key( data, password=None, backend=default_backend() ) except ValueError as e: raise SSHException(str(e)) assert isinstance(key, rsa.RSAPrivateKey) self.key = key