Python cryptography.hazmat.primitives.serialization.load_der_private_key() Examples
The following are 24
code examples of cryptography.hazmat.primitives.serialization.load_der_private_key().
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.serialization
, or try the search function
.
Example #1
Source File: registry_access.py From yotta with Apache License 2.0 | 6 votes |
def _getPrivateKeyObject(registry=None): registry = registry or Registry_Base_URL privatekey_pem = _getPrivateKey(registry) if not privatekey_pem: pubkey_pem, privatekey_pem = _generateAndSaveKeys(registry) else: # settings are unicode, we should be able to safely decode to ascii for # the key though, as it will either be hex or PEM encoded: privatekey_pem = privatekey_pem.encode('ascii') # if the key doesn't look like PEM, it might be hex-encided-DER (which we # used historically), so try loading that: if b'-----BEGIN PRIVATE KEY-----' in privatekey_pem: return serialization.load_pem_private_key( privatekey_pem, None, default_backend() ) else: privatekey_der = binascii.unhexlify(privatekey_pem) return serialization.load_der_private_key( privatekey_der, None, default_backend() )
Example #2
Source File: key_utils.py From aws-ec2-instance-connect-cli with Apache License 2.0 | 6 votes |
def convert_der_to_pem(der_key, is_private=False): """ Converts a given key from DER to PEM format. :param der_key: DER-encoded key bytes :type der_key: bytearray :param is_private: Whether the key is public or private. Default: False :type is_private: bool :return: PEM-encoded key bytes :rtype: bytearray """ if is_private: loaded_key = crypto_serialization.load_der_private_key(der_key, backend=crypto_default_backend()) return serialize_key(loaded_key, encoding='PEM', return_private=is_private) else: loaded_key = crypto_serialization.load_der_public_key(der_key, backend=crypto_default_backend()) return loaded_key.public_bytes(encoding=crypto_serialization.Encoding.PEM, format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo)
Example #3
Source File: test_crypto.py From barbican with Apache License 2.0 | 6 votes |
def test_generate_1024_DSA_key_in_pem_and_reconstruct_key_der(self): generate_dto = plugin.GenerateDTO('dsa', 1024, None, None) kek_meta_dto = self._get_mocked_kek_meta_dto() private_dto, public_dto, passwd_dto = self.plugin.generate_asymmetric( generate_dto, kek_meta_dto, mock.MagicMock() ) decrypt_dto = plugin.DecryptDTO(private_dto.cypher_text) private_dto = self.plugin.decrypt(decrypt_dto, kek_meta_dto, private_dto.kek_meta_extended, mock.MagicMock()) private_key = serialization.load_der_private_key( data=private_dto, password=None, backend=default_backend() ) self.assertEqual(1024, private_key.key_size)
Example #4
Source File: key.py From asap-authentication-python with MIT License | 6 votes |
def load(self, issuer): if not self._data_uri.startswith('data:application/pkcs8;kid='): raise PrivateKeyRetrieverException('Unrecognised data uri format.') splitted = self._data_uri.split(';') key_identifier = KeyIdentifier(unquote_plus( splitted[1][len('kid='):])) key_data = base64.b64decode(splitted[-1].split(',')[-1]) key = serialization.load_der_private_key( key_data, password=None, backend=cryptography.hazmat.backends.default_backend()) private_key_pem = key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ) return key_identifier, private_key_pem.decode('utf-8')
Example #5
Source File: serialization.py From commandment with MIT License | 5 votes |
def rsa_from_der(rsa_der_data: bytes, password: str = None) -> rsa.RSAPrivateKeyWithSerialization: return serialization.load_der_private_key( rsa_der_data, password, default_backend() )
Example #6
Source File: cse.py From aioboto3 with Apache License 2.0 | 5 votes |
def from_der_private_key(data: bytes, password: Optional[str] = None) -> _RSAPrivateKey: """ Convert private key in DER encoding to a Private key object :param data: private key bytes :param password: password the private key is encrypted with """ return serialization.load_der_private_key(data, password, default_backend())
Example #7
Source File: ecc.py From synapse with Apache License 2.0 | 5 votes |
def load(byts): ''' Create a PriKey instance from DER/PKCS8 encoded bytes. Args: byts (bytes): Bytes to load Returns: PriKey: A new PubKey instance. ''' return PriKey(c_ser.load_der_private_key( byts, password=None, backend=default_backend()))
Example #8
Source File: translations.py From barbican with Apache License 2.0 | 5 votes |
def _convert_private_der_to_pem(der): private_key = serialization.load_der_private_key( der, password=None, backend=default_backend() ) pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) return pem
Example #9
Source File: uacrypto.py From opcua-modeling-tool with MIT License | 5 votes |
def load_private_key(path): _, ext = os.path.splitext(path) with open(path, "rb") as f: if ext == ".pem": return serialization.load_pem_private_key(f.read(), password=None, backend=default_backend()) else: return serialization.load_der_private_key(f.read(), password=None, backend=default_backend())
Example #10
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
Example #11
Source File: ecdsakey.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, AssertionError) as e: raise SSHException(str(e)) self.signing_key = key self.verifying_key = key.public_key() curve_class = key.curve.__class__ self.ecdsa_curve = self._ECDSA_CURVES.get_by_curve_class(curve_class)
Example #12
Source File: test_jce.py From aws-dynamodb-encryption-python with Apache License 2.0 | 5 votes |
def _find_rsa_key_length(key): loaded_key = serialization.load_der_private_key(data=key, password=None, backend=default_backend()) return loaded_key.key_size
Example #13
Source File: auth_keypair.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
def authenticate( self, authenticator, service_name, account, user, password): account = account.upper() user = user.upper() now = datetime.utcnow() try: private_key = load_der_private_key(data=self._private_key, password=None, backend=default_backend()) except Exception as e: raise ProgrammingError( msg='Failed to load private key: {}\nPlease provide a valid unencrypted rsa private ' 'key in DER format as bytes object'.format(str(e)), errno=ER_INVALID_PRIVATE_KEY ) if not isinstance(private_key, RSAPrivateKey): raise ProgrammingError( msg='Private key type ({}) not supported.\nPlease provide a valid rsa private ' 'key in DER format as bytes object'.format(private_key.__class__.__name__), errno=ER_INVALID_PRIVATE_KEY ) public_key_fp = self.calculate_public_key_fingerprint(private_key) self._jwt_token_exp = now + self.LIFETIME payload = { self.ISSUER: "{}.{}.{}".format(account, user, public_key_fp), self.SUBJECT: "{}.{}".format(account, user), self.ISSUE_TIME: now, self.EXPIRE_TIME: self._jwt_token_exp } self._jwt_token = jwt.encode(payload, private_key, algorithm=self.ALGORITHM).decode('utf-8') return self._jwt_token
Example #14
Source File: test_engine.py From PyKMIP with Apache License 2.0 | 5 votes |
def load_private_key(key): try: return serialization.load_der_private_key( key, password=None, backend=default_backend() ) except Exception: return serialization.load_pem_private_key( key, password=None, backend=default_backend() )
Example #15
Source File: engine.py From PyKMIP with Apache License 2.0 | 5 votes |
def _create_RSA_private_key(self, bytes): """ Instantiates an RSA key from bytes. Args: bytes (byte string): Bytes of RSA private key. Returns: private_key (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey): RSA private key created from key bytes. """ try: private_key = serialization.load_pem_private_key( bytes, password=None, backend=default_backend() ) return private_key except Exception: private_key = serialization.load_der_private_key( bytes, password=None, backend=default_backend() ) return private_key
Example #16
Source File: cert.py From scapy with GNU General Public License v2.0 | 5 votes |
def import_from_asn1pkt(self, privkey): self.key = serialization.load_der_private_key(raw(privkey), None, backend=default_backend()) # noqa: E501 self.pubkey = self.key.public_key()
Example #17
Source File: der_serializer.py From loopchain with Apache License 2.0 | 5 votes |
def load_private_key(cls, cert_private_key: bytes, password, backend): return serialization.load_der_private_key(cert_private_key, password, backend)
Example #18
Source File: authentication.py From aws-encryption-sdk-python with Apache License 2.0 | 5 votes |
def from_key_bytes(cls, algorithm, key_bytes): """Builds a `Signer` from an algorithm suite and a raw signing key. :param algorithm: Algorithm on which to base signer :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes key_bytes: Raw signing key :rtype: aws_encryption_sdk.internal.crypto.Signer """ key = serialization.load_der_private_key(data=key_bytes, password=None, backend=default_backend()) return cls(algorithm, key)
Example #19
Source File: test_mock_key_manager.py From castellan with Apache License 2.0 | 5 votes |
def get_cryptography_private_key(private_key): crypto_private_key = serialization.load_der_private_key( bytes(private_key.get_encoded()), password=None, backend=backends.default_backend()) return crypto_private_key
Example #20
Source File: barbican_key_manager.py From castellan with Apache License 2.0 | 5 votes |
def _get_normalized_payload(self, encoded_bytes, secret_type): """Normalizes the bytes of the object. Barbican expects certificates, public keys, and private keys in PEM format, but Castellan expects these objects to be DER encoded bytes instead. """ if secret_type == 'public': key = serialization.load_der_public_key( encoded_bytes, backend=backends.default_backend()) return key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) elif secret_type == 'private': key = serialization.load_der_private_key( encoded_bytes, backend=backends.default_backend(), password=None) return key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) elif secret_type == 'certificate': cert = cryptography_x509.load_der_x509_certificate( encoded_bytes, backend=backends.default_backend()) return cert.public_bytes(encoding=serialization.Encoding.PEM) else: return encoded_bytes
Example #21
Source File: startup_thread.py From commandment with MIT License | 4 votes |
def split_pkcs12(app: Flask): """Split up .p12 containers if necessary.""" with app.app_context(): if 'PUSH_CERTIFICATE' not in app.config: app.logger.warn('No push certificate specified, you will not be able to manage devices until this is configured') return push_certificate_path = app.config['PUSH_CERTIFICATE'] if not os.path.exists(push_certificate_path): raise RuntimeError('You specified a push certificate at: {}, but it does not exist.'.format(push_certificate_path)) # We can handle loading PKCS#12 but APNS2Client specifically requests PEM encoded certificates push_certificate_basename, ext = os.path.splitext(push_certificate_path) if ext.lower() == '.p12': pem_key_path = push_certificate_basename + '.key' pem_certificate_path = push_certificate_basename + '.crt' if not os.path.exists(pem_key_path) or not os.path.exists(pem_certificate_path): app.logger.info('You provided a PKCS#12 push certificate, we will have to encode it as PEM to continue...') app.logger.info('.key and .crt files will be saved in the same location: %s, %s', pem_key_path, pem_certificate_path) with open(push_certificate_path, 'rb') as fd: if 'PUSH_CERTIFICATE_PASSWORD' in app.config: key, certificate, intermediates = parse_pkcs12(fd.read(), bytes(app.config['PUSH_CERTIFICATE_PASSWORD'], 'utf8')) else: key, certificate, intermediates = parse_pkcs12(fd.read()) try: crypto_key = serialization.load_der_private_key(key.dump(), None, default_backend()) with open(pem_key_path, 'wb') as fd: fd.write(crypto_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())) crypto_cert = x509.load_der_x509_certificate(certificate.dump(), default_backend()) with open(pem_certificate_path, 'wb') as fd: fd.write(crypto_cert.public_bytes(serialization.Encoding.PEM)) except PermissionError: app.logger.error('Could not write out .key or .crt file. You will not be able to push APNS messages') app.logger.error('This means your MDM is BROKEN until you fix permissions') else: app.logger.info('.p12 already split into PEM/KEY components')
Example #22
Source File: push.py From commandment with MIT License | 4 votes |
def get_apns() -> apns2.APNSClient: apns = getattr(g, '_apns', None) if apns is None: push_certificate_path = current_app.config['PUSH_CERTIFICATE'] if not os.path.exists(push_certificate_path): raise RuntimeError('You specified a push certificate at: {}, but it does not exist.'.format(push_certificate_path)) client_cert = push_certificate_path # can be a single path or tuple of 2 # We can handle loading PKCS#12 but APNS2Client specifically requests PEM encoded certificates push_certificate_basename, ext = os.path.splitext(push_certificate_path) if ext.lower() == '.p12': pem_key_path = push_certificate_basename + '.key' pem_certificate_path = push_certificate_basename + '.crt' if not os.path.exists(pem_key_path) or not os.path.exists(pem_certificate_path): current_app.logger.info('You provided a PKCS#12 push certificate, we will have to encode it as PEM to continue...') current_app.logger.info('.key and .crt files will be saved in the same location') with open(push_certificate_path, 'rb') as fd: if 'PUSH_CERTIFICATE_PASSWORD' in current_app.config: key, certificate, intermediates = parse_pkcs12(fd.read(), bytes(current_app.config['PUSH_CERTIFICATE_PASSWORD'], 'utf8')) else: key, certificate, intermediates = parse_pkcs12(fd.read()) crypto_key = serialization.load_der_private_key(key.dump(), None, default_backend()) with open(pem_key_path, 'wb') as fd: fd.write(crypto_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())) crypto_cert = x509.load_der_x509_certificate(certificate.dump(), default_backend()) with open(pem_certificate_path, 'wb') as fd: fd.write(crypto_cert.public_bytes(serialization.Encoding.PEM)) client_cert = pem_certificate_path, pem_key_path try: apns = g._apns = apns2.APNSClient(mode='prod', client_cert=client_cert) except: raise RuntimeError('Your push certificate is expired or invalid') return apns
Example #23
Source File: detect.py From roca with MIT License | 4 votes |
def process_pem_rsakey(self, data, name, idx): """ Processes PEM encoded RSA key :param data: :param name: :param idx: :return: """ from cryptography.hazmat.primitives.serialization import load_der_public_key from cryptography.hazmat.primitives.serialization import load_der_private_key try: if startswith(data, '-----BEGIN RSA PUBLIC KEY') or startswith(data, '-----BEGIN PUBLIC KEY'): rsa = load_der_public_key(pem_to_der(data), self.get_backend()) public_numbers = rsa.public_numbers() elif startswith(data, '-----BEGIN RSA PRIVATE KEY') or startswith(data, '-----BEGIN PRIVATE KEY'): rsa = load_der_private_key(pem_to_der(data), None, self.get_backend()) public_numbers = rsa.private_numbers().public_numbers else: return None self.num_rsa_keys += 1 self.num_rsa += 1 js = collections.OrderedDict() js['type'] = 'pem-rsa-key' js['fname'] = name js['idx'] = idx js['pem'] = data js['e'] = '0x%x' % public_numbers.e js['n'] = '0x%x' % public_numbers.n if self.has_fingerprint(public_numbers.n): logger.warning('Fingerprint found in PEM RSA key %s ' % name) self.mark_and_add_effort(public_numbers.n, js) if self.do_print: print(json.dumps(js)) return TestResult(js) except Exception as e: logger.debug('Pubkey loading error: %s : %s [%s] : %s' % (name, idx, data[:20], e)) self.trace_logger.log(e)
Example #24
Source File: test_crypto.py From barbican with Apache License 2.0 | 4 votes |
def test_generate_1024_bit_DSA_key_with_passphrase(self): generate_dto = plugin.GenerateDTO('dsa', 1024, None, 'changeme') kek_meta_dto = self._get_mocked_kek_meta_dto() private_dto, public_dto, passwd_dto = self.plugin.generate_asymmetric( generate_dto, kek_meta_dto, mock.MagicMock() ) decrypt_dto = plugin.DecryptDTO(private_dto.cypher_text) private_dto = self.plugin.decrypt(decrypt_dto, kek_meta_dto, private_dto.kek_meta_extended, mock.MagicMock()) decrypt_dto = plugin.DecryptDTO(public_dto.cypher_text) public_dto = self.plugin.decrypt(decrypt_dto, kek_meta_dto, public_dto.kek_meta_extended, mock.MagicMock()) # check we can reload the private and public keys private_key = serialization.load_der_private_key( data=private_dto, password='changeme'.encode(), backend=default_backend() ) public_key = serialization.load_der_public_key( data=public_dto, backend=default_backend() ) self.assertEqual(1024, private_key.key_size) self.assertEqual(1024, public_key.key_size) public_key = public_key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo ) # get the public key from the private key we recovered to compare recovered_key = private_key.public_key().public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo ) self.assertTrue(public_key == recovered_key)