Load private key from PEM encoded file
770471
def load_private_key(pem_path, passphrase_bytes=None):
    """"""
    with open(pem_path, "rb") as f:
        return cryptography.hazmat.primitives.serialization.load_pem_private_key(
            data=f.read(),
            password=passphrase_bytes,
            backend=cryptography.hazmat.backends.default_backend(),
        )
197513
private static PrivateKey loadPrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
798168
def _load_private_key(self, private_key, passphrase=None):
        
        key = None
        last_exception = None
        for pkey_class in (RSAKey, DSSKey):
            try:
                key = pkey_class.from_private_key(StringIO(private_key),
                    passphrase)
            except PasswordRequiredException as e:
                # The key file is encrypted and no passphrase was provided.
                # There's no point to continue trying
                raise
            except SSHException as e:
                last_exception = e
                continue
            else:
                break
        if key is None and last_exception:
            raise last_exception
        return key
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
6598
def get_rsa_pub_key(path):
    '''
    
    '''
    log.debug('salt.crypt.get_rsa_pub_key: Loading public key')
    if HAS_M2:
        with salt.utils.files.fopen(path, 'rb') as f:
            data = f.read().replace(b'RSA ', b'')
        bio = BIO.MemoryBuffer(data)
        key = RSA.load_pub_key_bio(bio)
    else:
        with salt.utils.files.fopen(path) as f:
            key = RSA.importKey(f.read())
    return key
173322
def pem_as_string(cert):
    
    if hasattr(cert, 'read'): # File object - return as is
        return cert
    cert = cert.encode('utf-8') if isinstance(cert, unicode) else cert
    if re.match(_PEM_RE, cert):
        return True
    return False
274214
private static byte[] decodePem(File pemFile) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(pemFile));
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("-----BEGIN ")) {
                    return readBytes(pemFile, reader, line.trim().replace("BEGIN", "END"));
                }
            }
            throw new IOException("PEM " + pemFile + " is invalid: no begin marker");
        } finally {
            reader.close();
        }
    }
111339
def deserialize_pem(cert_pem):
    
    if isinstance(cert_pem, str):
        cert_pem = cert_pem.encode("utf-8")
    return cryptography.x509.load_pem_x509_certificate(
        data=cert_pem, backend=cryptography.hazmat.backends.default_backend()
    )
536386
public static PublicKey decodePublicKey(String pemEncoded) throws Exception {
        pemEncoded = removeBeginEnd(pemEncoded);
        byte[] encodedBytes = Base64.getDecoder().decode(pemEncoded);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
687467
def serialize_cert_to_pem(cert_obj):
    
    return cert_obj.public_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM
    )
334846
def key_pair_from_ed25519_key(hex_private_key):
    """"""
    priv_key = crypto.Ed25519SigningKey(bytes.fromhex(hex_private_key)[:32], encoding='bytes')
    public_key = priv_key.get_verifying_key()
    return CryptoKeypair(private_key=priv_key.encode(encoding='base58').decode('utf-8'),
                         public_key=public_key.encode(encoding='base58').decode('utf-8'))
1236944
def import_public_key(self, pem_text):
		
		if isinstance(pem_text, str) is True:
			pem_text = pem_text.encode()
		self.__set_public_key(
			serialization.load_pem_public_key(pem_text, backend=default_backend())
		)
1120631
def import_private_key(self, pem_text, password=None):
		
		if isinstance(pem_text, str) is True:
			pem_text = pem_text.encode()
		if password is not None and isinstance(password, str) is True:
			password = password.encode()

		self.__set_private_key(
			serialization.load_pem_private_key(pem_text, password=password, backend=default_backend())
		)
676077
@CheckForNull
    public static PrivateKey loadPrivateKey(final String keypem) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        try (StringReader certReader = new StringReader(keypem);
             BufferedReader reader = new BufferedReader(certReader)) {
            return loadPrivateKey(reader);
        }
    }
555930
def get_private_key(key_path, password_path=None):
    """"""

    assert key_path, key_path
    if not os.path.exists(key_path):
        log.fatal('%s: no such file', key_path)
        return None

    if not check_permission_safety(key_path):
        log.fatal('Private key file %s must be readable only by its owner.', key_path)
        return None

    if password_path and not check_permission_safety(password_path):
        log.fatal('Password file %s must be readable only by its owner.', password_path)
        return None

    with open(key_path) as keyfile:
        private_key = keyfile.readline().strip()

        if is_hex(private_key) and len(decode_hex(private_key)) == 32:
            log.warning('Private key in raw format. Consider switching to JSON-encoded')
        else:
            keyfile.seek(0)
            try:
                json_data = json.load(keyfile)
                if password_path:
                    with open(password_path) as password_file:
                        password = password_file.readline().strip()
                else:
                    password = getpass.getpass('Enter the private key password: ')
                if json_data['crypto']['kdf'] == 'pbkdf2':
                    password = password.encode()  # type: ignore
                private_key = encode_hex(decode_keyfile_json(json_data, password))
            except ValueError:
                log.fatal('Invalid private key format or password!')
                return None

    return private_key
35208
def load_key(self, key_path, password):
        

        try:
            return paramiko.RSAKey.from_private_key_file(key_path)
        except PasswordRequiredException as ex:
            return paramiko.RSAKey.from_private_key_file(key_path,
                                                         password=password)
925167
def _get_private_key_obj(private_key, passphrase=None):
    '''
    
    '''
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase))
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey