Decode a PEM encoded private key string to an RSA PrivateKey

@param pemEncoded - PEM string for private key
@return PrivateKey
@throws Exception on decode failure
974624
public static PrivateKey decodePrivateKey(String pemEncoded) throws Exception {
        pemEncoded = removeBeginEnd(pemEncoded);
        byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pemEncoded);

        // extract the private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(keySpec);
        return privKey;
    }
835058
static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect,
            X509Certificate... chain) throws CertificateEncodingException {

        if (chain == null || chain.length == 0) {
            throw new IllegalArgumentException("X.509 certificate chain can't be null or empty");
        }

        // We can take a shortcut if there is only one certificate and
        // it already happens to be a PemEncoded instance. This is the
        // ideal case and reason why all this exists. It allows the user
        // to pass pre-encoded bytes straight into OpenSSL without having
        // to do any of the extra work.
        if (chain.length == 1) {
            X509Certificate first = chain[0];
            if (first instanceof PemEncoded) {
                return ((PemEncoded) first).retain();
            }
        }

        boolean success = false;
        ByteBuf pem = null;
        try {
            for (X509Certificate cert : chain) {

                if (cert == null) {
                    throw new IllegalArgumentException("Null element in chain: " + Arrays.toString(chain));
                }

                if (cert instanceof PemEncoded) {
                    pem = append(allocator, useDirect, (PemEncoded) cert, chain.length, pem);
                } else {
                    pem = append(allocator, useDirect, cert, chain.length, pem);
                }
            }

            PemValue value = new PemValue(pem, false);
            success = true;
            return value;
        } finally {
            // Make sure we never leak the PEM's ByteBuf in the event of an Exception
            if (!success && pem != null) {
                pem.release();
            }
        }
    }
1182229
private X509Certificate getX509Certificate(byte[] pemCertificate) throws CryptoException {
        X509Certificate ret = null;
        CryptoException rete = null;

        List<Provider> providerList = new LinkedList<>(Arrays.asList(Security.getProviders()));
        if (SECURITY_PROVIDER != null) { //Add if overridden
            providerList.add(SECURITY_PROVIDER);
        }
        try {
            providerList.add(BouncyCastleProvider.class.newInstance()); // bouncy castle is there always.
        } catch (Exception e) {
            logger.warn(e);

        }
        for (Provider provider : providerList) {
            try {
                if (null == provider) {
                    continue;
                }
                CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT, provider);
                if (null != certFactory) {
                    try (ByteArrayInputStream bis = new ByteArrayInputStream(pemCertificate)) {
                        Certificate certificate = certFactory.generateCertificate(bis);

                        if (certificate instanceof X509Certificate) {
                            ret = (X509Certificate) certificate;
                            rete = null;
                            break;
                        }
                    }

                }
            } catch (Exception e) {

                rete = new CryptoException(e.getMessage(), e);

            }

        }

        if (null != rete) {

            throw rete;

        }

        if (ret == null) {

            logger.error("Could not convert pem bytes");

        }

        return ret;

    }
1333897
def rsa_decrypt(encrypted_data, pem, password=None):
    
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encrypted_data = to_binary(encrypted_data)
    pem = to_binary(pem)
    private_key = serialization.load_pem_private_key(pem, password, backend=default_backend())
    data = private_key.decrypt(
        encrypted_data,
        padding=padding.OAEP(
            mgf=padding.MGF1(hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None,
        )
    )
    return data
832429
public static String decryptByPrivateKey(String data, String privateKey) throws Exception {
		return decryptByPrivateKey(data, privateKey, "RSA/ECB/PKCS1Padding");
	}
696052
def decrypt_key(key, password):
    
    private = serialization.load_pem_private_key(key, password=password, backend=default_backend())
    return private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())
565807
public static String privateKey2String(PrivateKey key) {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key.getEncoded());
        return new String(Base64.getEncoder().encode(spec.getEncoded()), StandardCharsets.UTF_8);
    }
539405
byte[] getEncoded() {
		byte[] peerHostBytes = (peerHost == null ? Bytes.EMPTY_BYTES : peerHost.getBytes());
		byte[] peerCertsBytes = encodeCerts(peerCertificates);
		byte[] localCertsBytes = encodeCerts(localCertificates);
		int idLen = id.length;
		int hostLen = peerHostBytes.length;
		int peerCertsLen = peerCertsBytes.length;
		int localCertsLen = localCertsBytes.length;
		byte[] b = new byte[12 + idLen + hostLen + peerCertsLen + localCertsLen];
		b[0] = (byte) idLen;
		b[1] = (byte) hostLen;
		Bytes.setShort(peerCertsLen, b, 2);
		Bytes.setShort(localCertsLen, b, 4);
		System.arraycopy(id, 0, b, 6, id.length);
		Integer cipherId_ = cipherName2Id.get(cipherSuite);
		Bytes.setShort(cipherId_ == null ? 0 : cipherId_.intValue(), b, 6 + idLen);
		Integer ver_ = proto2Ver.get(protocol);
		Bytes.setShort(ver_ == null ? -1 : ver_.intValue(), b, 8 + idLen);
		System.arraycopy(peerHostBytes, 0, b, 10 + idLen, hostLen);
		Bytes.setShort(peerPort, b, 10 + idLen + hostLen);
		System.arraycopy(peerCertsBytes, 0, b, 12 + idLen + hostLen, peerCertsLen);
		System.arraycopy(localCertsBytes, 0, b,
				12 + idLen + hostLen + peerCertsLen, localCertsLen);
		return b;
	}
792547
def parse_private_key(data, password):
    
    # PEM
    if is_pem(data):
        if b'ENCRYPTED' in data:
            if password is None:
                raise TypeError('No password provided for encrypted key.')
        try:
            return serialization.load_pem_private_key(
                data, password, backend=default_backend())
        except ValueError:
            # Cryptography raises ValueError if decryption fails.
            raise
        except Exception:
            pass

    # PKCS12
    if is_pkcs12(data):
        try:
            p12 = crypto.load_pkcs12(data, password)
            data = crypto.dump_privatekey(
                crypto.FILETYPE_PEM, p12.get_privatekey())
            return serialization.load_pem_private_key(
                data, password=None, backend=default_backend())
        except crypto.Error as e:
            raise ValueError(e)

    # DER
    try:
        return serialization.load_der_private_key(
            data, password, backend=default_backend())
    except Exception:
        pass

    # All parsing failed
    raise ValueError('Could not parse private key.')
1053575
public KeyPair getKeyPair() throws GeneralSecurityException, IOException {
        if (privateKeyAsSeed == null) {
            throw new IllegalStateException("Public-only NKey");
        }

        DecodedSeed decoded = decodeSeed(privateKeyAsSeed);
        byte[] seedBytes = new byte[ED25519_SEED_SIZE];
        byte[] pubBytes = new byte[ED25519_PUBLIC_KEYSIZE];

        System.arraycopy(decoded.bytes, 0, seedBytes, 0, seedBytes.length);
        System.arraycopy(decoded.bytes, seedBytes.length, pubBytes, 0, pubBytes.length);

        EdDSAPrivateKeySpec privKeySpec = new EdDSAPrivateKeySpec(seedBytes, NKey.ed25519);
        EdDSAPrivateKey privKey = new EdDSAPrivateKey(privKeySpec);
        EdDSAPublicKeySpec pubKeySpec = new EdDSAPublicKeySpec(pubBytes, NKey.ed25519);
        EdDSAPublicKey pubKey = new EdDSAPublicKey(pubKeySpec);

        return new KeyPair(pubKey, privKey);
    }
595636
private PublicKey readKey(InputStream is) {
        InputStreamReader isr = new InputStreamReader(is);
        PEMParser r = new PEMParser(isr);
        try {
            Object o = r.readObject();
            if (o instanceof PEMKeyPair) {
                PEMKeyPair keyPair = (PEMKeyPair) o;
                if (keyPair.getPublicKeyInfo() != null &&
                        keyPair.getPublicKeyInfo().getEncoded().length > 0) {
                    return provider.getPublicKey(keyPair.getPublicKeyInfo());
                }
            } else if (o instanceof SubjectPublicKeyInfo) {
                return provider.getPublicKey((SubjectPublicKeyInfo) o);
            }
        } catch (IOException e) {
            // Ignoring, returning null
            log.warn("Failed to get key from PEM file", e);
        } finally {
            IoUtils.closeQuietly(isr,r);
        }

        return null;
    }
1194856
def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key):
    """"""
    algorithm = RsaAlgorithmIdentifier()
    algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID

    pkcs8_key = PKCS8PrivateKey()
    pkcs8_key["version"] = 0
    pkcs8_key["privateKeyAlgorithm"] = algorithm
    pkcs8_key["privateKey"] = pkcs1_key

    return encoder.encode(pkcs8_key)
1017418
public PrivateKey getPrivateKey_PKCS8Encoded(byte[] keyBytes){  
        try {
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);  
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);  
            return keyFactory.generatePrivate(spec); 
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		} 
    	return null;
    }
53766
private RSAPrivateKey loadPrivateKeyFromPEMFile(String filename) {
        try {
            String publicKeyFile = FileReader.readFileFromClassPathOrPath(filename);
            byte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(publicKeyFile.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", ""));
            return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(publicKeyBytes));
        } catch (Exception e) {
            throw new RuntimeException("Exception reading private key from PEM file", e);
        }
    }
401797
def private_encrypt(key, message):
    '''
    
    '''
    if HAS_M2:
        return key.private_encrypt(message, salt.utils.rsax931.RSA_X931_PADDING)
    else:
        signer = salt.utils.rsax931.RSAX931Signer(key.exportKey('PEM'))
        return signer.sign(message)
433067
public byte[] getEncoded() throws SshException {
		ByteArrayWriter baw = new ByteArrayWriter();
		try {

			baw.writeString(getAlgorithm());
			baw.writeBigInteger(pubkey.getParams().getP());
			baw.writeBigInteger(pubkey.getParams().getQ());
			baw.writeBigInteger(pubkey.getParams().getG());
			baw.writeBigInteger(pubkey.getY());

			return baw.toByteArray();
		} catch (IOException ioe) {
			throw new SshException("Failed to encoded DSA key",
					SshException.INTERNAL_ERROR, ioe);
		} finally {
			try {
				baw.close();
			} catch (IOException e) {
			}
		}
	}
961601
public static RSAPrivateKey buildPrivateKey(final byte[] keyData)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM);
        PrivateKey generatePrivate = keyFactory.generatePrivate(privateKeySpec);
        return (RSAPrivateKey) generatePrivate;
    }