Example usage for org.bouncycastle.pkcs PKCS8EncryptedPrivateKeyInfo decryptPrivateKeyInfo

List of usage examples for org.bouncycastle.pkcs PKCS8EncryptedPrivateKeyInfo decryptPrivateKeyInfo

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS8EncryptedPrivateKeyInfo decryptPrivateKeyInfo.

Prototype

public PrivateKeyInfo decryptPrivateKeyInfo(InputDecryptorProvider inputDecryptorProvider)
            throws PKCSException 

Source Link

Usage

From source file:co.lqnt.lockbox.key.KeyFactory.java

License:Open Source License

/**
 * Decrypts an encrypted PKCS #8 private key.
 *
 * @param encryptedPrivateKey The encrypted private key information.
 * @param password            The password to use.
 *
 * @return The decrypted private key.//from   w  ww. ja  va 2s  .  co  m
 * @throws PrivateKeyReadException If reading of the private key fails.
 */
protected PrivateKey decryptPkcs8PrivateKey(PKCS8EncryptedPrivateKeyInfo encryptedPrivateKey, String password)
        throws PrivateKeyReadException {
    InputDecryptorProvider decryptorProvider;
    try {
        decryptorProvider = this.pkcs8DecryptorProviderBuilder().build(password.toCharArray());
    } catch (OperatorCreationException e) {
        throw new PrivateKeyReadException(e);
    }

    PrivateKeyInfo privateKeyInfo;
    try {
        privateKeyInfo = encryptedPrivateKey.decryptPrivateKeyInfo(decryptorProvider);
    } catch (PKCSException e) {
        throw new PrivateKeyReadException(e);
    }

    return this.convertPrivateKey(privateKeyInfo);
}

From source file:com.google.examples.JOSEToolBase.java

License:Apache License

public static PrivateKey decodePrivateKey(String privateKeyString, String password) throws KeyParseException {
    try {/*from  w  ww  .  j  a  va  2 s  .  c o m*/
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        privateKeyString = reformIndents(privateKeyString);
        PEMParser pemParser = new PEMParser(new StringReader(privateKeyString));
        Object object = pemParser.readObject();
        if (object == null) {
            throw new KeyParseException("unable to read anything when decoding private key");
        }

        KeyPair kp = null;

        //LOGGER.info(String.format("decodePrivateKey, %s", object.getClass().getName()));
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            // produced by "openssl genpkey" or  the series of commands reqd to sign an ec key
            //LOGGER.info("decodePrivateKey, encrypted PrivateKeyInfo");
            PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
            JceOpenSSLPKCS8DecryptorProviderBuilder decryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            InputDecryptorProvider decryptorProvider = decryptorProviderBuilder.build(password.toCharArray());
            PrivateKeyInfo privateKeyInfo = pkcs8EncryptedPrivateKeyInfo
                    .decryptPrivateKeyInfo(decryptorProvider);
            return (PrivateKey) converter.getPrivateKey(privateKeyInfo);
        }

        if (object instanceof PrivateKeyInfo) {
            // produced by openssl genpkey without encryption
            return (PrivateKey) converter.getPrivateKey((PrivateKeyInfo) object);
        }

        if (object instanceof PEMEncryptedKeyPair) {
            // produced by "openssl genrsa" or "openssl ec -genkey"
            // LOGGER.info("decodePrivateKey, encrypted keypair");
            PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) object;
            PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder()
                    .build(password.toCharArray());
            kp = converter.getKeyPair(encryptedKeyPair.decryptKeyPair(decryptorProvider));
        } else if (object instanceof PEMKeyPair) {
            //LOGGER.info("decodePrivateKey, un-encrypted keypair");
            PEMKeyPair unencryptedKeyPair = (PEMKeyPair) object;
            kp = converter.getKeyPair(unencryptedKeyPair);
        } else {
            //LOGGER.error("decodePrivateKey, unknown object type {}", object.getClass().getName());
            throw new KeyParseException("unknown object type when decoding private key");
        }

        return (PrivateKey) kp.getPrivate();
    } catch (KeyParseException exc0) {
        throw exc0;
    } catch (Exception exc1) {
        throw new KeyParseException("cannot instantiate private key", exc1);
    }
}

From source file:com.oth.jasds.crypto.Crypto.java

public byte[] decryptFileKey(String filekey, String privateKey) {
    try {//from w w  w  .j  av  a2s.c  o m
        BASE64Decoder b64 = new BASE64Decoder();
        ByteArrayInputStream in = new ByteArrayInputStream(privateKey.getBytes());
        PEMParser pemRd = new PEMParser(new InputStreamReader(in));

        PrivateKey prvKey = null;

        Object obj = pemRd.readObject();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        if (obj instanceof PKCS8EncryptedPrivateKeyInfo) {
            PKCS8EncryptedPrivateKeyInfo pkcs8 = (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) obj;
            JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .setProvider("BC");
            InputDecryptorProvider decProv = jce.build("Qwer1234!".toCharArray());
            PrivateKeyInfo pkinfo = pkcs8.decryptPrivateKeyInfo(decProv);

            prvKey = converter.getPrivateKey(pkinfo);

        } else {
            throw new Exception("party");
        }

        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
        rsaCipher.init(Cipher.DECRYPT_MODE, prvKey,
                new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
        //rsaCipher.init(Cipher.DECRYPT_MODE, prvKey);

        byte[] decfk = rsaCipher.doFinal(b64.decodeBuffer(filekey));
        /*
        AsymmetricBlockCipher e = new RSAEngine();
                
        e = new PKCS1Encoding(e);
        AsymmetricKeyParameter prv = (AsymmetricKeyParameter) PrivateKeyFactory.createKey(prvKey.getEncoded());
        e.init(true, prv);
                
        byte[] fk = b64.decodeBuffer(filekey);
        byte[] decfk = e.processBlock(fk, 0, fk.length);
        */
        System.out.println("done");
        return decfk;
    } catch (IOException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidCipherTextException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OperatorCreationException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PKCSException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java

License:Apache License

/**
 * Load the key store object from the passed in PKCS#12 encoding, using the passed in password.
 *
 * @param password the password to unlock the key store.
 * @param encoding the ASN.1 encoded bytes representing the PKCS#12 store.
 * @throws IOException on a parsing error.
 * @throws GeneralSecurityException if there's an exception decrypting the store.
 *///from   w  ww.ja va 2  s.  c om
public synchronized void load(char[] password, byte[] encoding) throws IOException, GeneralSecurityException {
    try {
        PKCS12PfxPdu pfx = new PKCS12PfxPdu(encoding);
        InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
                .setProvider("BC").build(password);
        ContentInfo[] infos = pfx.getContentInfos();

        for (int i = 0; i != infos.length; i++) {
            if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();

                Attribute[] attributes = bags[0].getAttributes();

                X509CertificateHolder cert = (X509CertificateHolder) bags[0].getBagValue();

                String keyID = getKeyID(attributes);
                BLS01PublicKeyParameters publicKeyParameters = BLSPublicKeyFactory
                        .createKey(cert.getSubjectPublicKeyInfo());

                paramsMap.put(keyID, publicKeyParameters.getParameters());
                sequenceNoMap.put(keyID, ASN1Integer.getInstance(
                        cert.getExtension(XimixObjectIdentifiers.ximixShareIdExtension).getParsedValue())
                        .getValue().intValue());
                sharedPublicKeyMap.put(keyID, publicKeyParameters.getPk());

                if (KeyUsage.fromExtensions(cert.getExtensions()).hasUsages(KeyUsage.digitalSignature)) {
                    signingKeys.add(keyID);
                }
            } else {
                PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);

                PKCS12SafeBag[] bags = dataFact.getSafeBags();
                String keyID = getKeyID(bags[0].getAttributes());

                PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
                PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);

                sharedPrivateKeyMap.put(keyID, ASN1Integer.getInstance(info.parsePrivateKey()).getValue());
            }
        }
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to load key store: " + e.getMessage(), e);
    }
}

From source file:craterdog.security.RsaCertificateManager.java

License:Open Source License

@Override
public PrivateKey decodePrivateKey(String pem, char[] password) {
    logger.entry();/*from w w  w .  ja  v a2 s.c om*/
    try (StringReader sreader = new StringReader(pem); PemReader preader = new PemReader(sreader)) {
        PEMParser pemParser = new PEMParser(preader);
        PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();
        InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password);
        byte[] keyBytes = pinfo.decryptPrivateKeyInfo(provider).getEncoded();
        KeyFactory factory = KeyFactory.getInstance(ASYMMETRIC_KEY_TYPE, PROVIDER_NAME);
        PrivateKey result = factory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
        logger.exit();
        return result;
    } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException
            | OperatorCreationException | PKCSException e) {
        RuntimeException exception = new RuntimeException(
                "An unexpected exception occurred while attempting to decode a private key.", e);
        throw logger.throwing(exception);
    }
}

From source file:de.carne.certmgr.store.provider.bouncycastle.PKCS12Decoder.java

License:Open Source License

public void decodeKeyBag(PKCS8EncryptedPrivateKeyInfo bagValue, Attribute[] bagAttributes)
        throws PasswordRequiredException {
    PrivateKeyInfo keyInfo = null;//from  w  w  w .  j av a  2  s. c  o  m
    PKCSException decryptException = null;

    while (keyInfo == null) {
        try {
            keyInfo = bagValue.decryptPrivateKeyInfo(getInputDecryptorProvider(decryptException));
        } catch (PKCSException e) {
            decryptException = e;
        }
    }
    decodeKeyBag(keyInfo, bagAttributes);
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java

License:Apache License

/**
 * A method to load BcCredential (consists of certificate chain, end entity 
 * alias and private key of end entity credential) from the PKCS12 file
 * @param pkcs12FileName: the PKCS12 file name
 * @param keyPasswd: the password of the key credential
 * @return/* w w  w . ja  v a2s  .c o  m*/
 * @throws Exception
 */
public static BcCredential loadPKCS12Credential(String pkcs12FileName, char[] keyPasswd, int certType) {

    PKCS12PfxPdu pfxPdu = null;
    //     if(certType == APPS_CERT){
    //        log.info("Reading AppStoreCertInter.p12 file");
    //        InputStream is = PKCS12Utils.class.getResourceAsStream(pkcs12FileName);
    //        log.info("AppStoreCertInter.p12 file has been converted to InputStream");
    //        pfxPdu = new PKCS12PfxPdu(Streams.readAll(is));
    //        log.info("Read the PKCS12PfxPdu...");
    //     }
    //     else if(certType == GW_CERT){
    // Try to put the AppStoreCertInter.p12 in the karaf, so no need to read
    // from the resource, e.g. getResourceAsStream
    log.debug("will start loading PKCS12 file...");
    try {
        pfxPdu = new PKCS12PfxPdu(Streams.readAll(new FileInputStream(pkcs12FileName)));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        log.error("PKCS12 file: " + pkcs12FileName + " is not found!!");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error("IOException in initializing PKCS12PfxPdu...");
        e.printStackTrace();
    }
    log.debug("Loading PKCS12 successfully...");
    //     }
    try {
        if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE),
                keyPasswd)) {
            log.error("PKCS#12 MAC test failed!");
            return null;
        }
    } catch (PKCSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ContentInfo[] infos = pfxPdu.getContentInfos();
    InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder()
            .build(keyPasswd);

    String eeAlias = null;
    AsymmetricKeyParameter privCred = null;
    List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>();
    //    log.info("Start iterating over the ContentInfo...");
    for (int i = 0; i != infos.length; i++) {
        if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = null;
            try {
                dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);
            } catch (PKCSException e) {
                // TODO Auto-generated catch block
                log.error("Error in initiating PKCS12SafeBagFactory...");
                e.printStackTrace();
            }

            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            for (int b = 0; b != bags.length; b++) {
                PKCS12SafeBag bag = bags[b];
                X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue();
                chainList.add(certHldr);
                log.debug("Found a certificate and add it to certificate chain...");
            }
        } else {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();

            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info;
            AsymmetricKeyParameter privKey = null;
            try {
                info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
                privKey = PrivateKeyFactory.createKey(info);
            } catch (PKCSException e) {
                // TODO Auto-generated catch block
                log.error("Error in getting the decrypt private key info...");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("Error in loading private key...");
                e.printStackTrace();
            }

            Attribute[] attributes = bags[0].getAttributes();
            for (int a = 0; a != attributes.length; a++) {
                Attribute attr = attributes[a];
                if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) {
                    eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString();
                    privCred = privKey;
                    log.debug("Get end entity alias");
                    log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString());
                }
            }
        }
    }
    X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()];
    chain = (X509CertificateHolder[]) chainList.toArray(chain);

    BcCredential cred = new BcCredential(eeAlias, privCred, chain);
    log.debug("Credential has been loaded!!");

    return cred;
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java

License:Apache License

/**
 * A method to load BcCredential (consists of certificate chain, end entity 
 * alias and private key of end entity credential) from the PKCS12 file
 * @param pfx: the PKCS#12 file in byte//  w  w w  . j  av  a 2  s .c  o m
 * @param keyPasswd: the password of the key credential
 * @return
 * @throws Exception
 */
public static BcCredential loadPKCS12Credential(byte[] pfx, char[] keyPasswd) throws Exception {

    PKCS12PfxPdu pfxPdu = new PKCS12PfxPdu(pfx);

    if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE),
            keyPasswd)) {
        log.error("PKCS#12 MAC test failed!");
        return null;
    }

    ContentInfo[] infos = pfxPdu.getContentInfos();
    InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder()
            .build(keyPasswd);

    String eeAlias = null;
    AsymmetricKeyParameter privCred = null;
    List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>();
    //    log.debug("Start iterating over the ContentInfo...");
    for (int i = 0; i != infos.length; i++) {
        if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            for (int b = 0; b != bags.length; b++) {
                PKCS12SafeBag bag = bags[b];
                X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue();
                chainList.add(certHldr);
                log.debug("Found a certificate and add it to certificate chain...");
            }
        } else {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();

            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
            AsymmetricKeyParameter privKey = PrivateKeyFactory.createKey(info);

            Attribute[] attributes = bags[0].getAttributes();
            for (int a = 0; a != attributes.length; a++) {
                Attribute attr = attributes[a];
                if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) {
                    eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString();
                    privCred = privKey;
                    log.debug("Get end entity alias");
                    log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString());
                }
            }
        }
    }
    X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()];
    chain = (X509CertificateHolder[]) chainList.toArray(chain);

    BcCredential cred = new BcCredential(eeAlias, privCred, chain);

    return cred;
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

License:Open Source License

/**
 * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String}
 * //from www  .j  av a 2  s.  c  o  m
 * @param pem {@link String} with the PEM data
 * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller
 * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with
 * <code>Arrays.fill(passphrase, (char)0)</code>
 * @return {@link PEMEncodable} object
 * @throws IOException launched if a problem exists reading the PEM information
 * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided
 */
@Nonnull
public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase)
        throws IOException, UnrecoverableKeyException {

    try (PEMParser parser = new PEMParser(new StringReader(pem));) {

        Object object = parser.readObject();

        JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC");

        // handle supported PEM formats.
        if (object instanceof PEMEncryptedKeyPair) {
            if (passphrase != null) {
                PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase);
                PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object;
                return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (passphrase != null) {
                InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase);
                PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object;
                return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PEMKeyPair) {
            return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object));
        } else if (object instanceof PrivateKeyInfo) {
            PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object);

            // JENKINS-35661 in this case we know how to get the public key too
            if (pk instanceof RSAPrivateCrtKey) {
                // obtain public key spec from the private key
                RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk;
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(),
                        rsaPK.getPublicExponent());
                KeyFactory kf = KeyFactory.getInstance("RSA");
                return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK));
            }

            return new PEMEncodable(pk);
        } else if (object instanceof SubjectPublicKeyInfo) {
            return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object));
        } else if (object instanceof X509CertificateHolder) {
            JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC");
            return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object));
        } else {
            throw new IOException(
                    "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received "
                            + object.getClass().getName());
        }
    } catch (OperatorCreationException e) {
        throw new IOException(e.getMessage(), e);
    } catch (PKCSException | InvalidKeySpecException e) {
        LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e);
        throw new UnrecoverableKeyException();
    } catch (CertificateException e) {
        throw new IOException("Could not read certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(
                "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html");
    }
}

From source file:org.albertschmitt.crypto.RSAService.java

License:Open Source License

/**
 * Read the RSA Private Key from the specified input stream using the given password.
 *
 * @param instream/*from w  ww.jav a2 s .  c om*/
 *            The input stream that contains the RSA Private Key.
 * @param password
 *            The password the private key was encrypted with.
 * @return The RSAPrivateKey.
 * @throws IOException
 * @throws OperatorCreationException
 * @throws PKCSException
 */
public RSAPrivateKey readPrivateKey(InputStream instream, char[] password)
        throws IOException, OperatorCreationException, PKCSException {
    RSAPrivateKey key;
    try (InputStreamReader reader = new InputStreamReader(instream)) {
        try (PEMParser pem = new PEMParser(reader)) {
            PKCS8EncryptedPrivateKeyInfo pair = (PKCS8EncryptedPrivateKeyInfo) pem.readObject();
            JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            InputDecryptorProvider decProv = jce.build(password);
            PrivateKeyInfo pki = pair.decryptPrivateKeyInfo(decProv);

            key = new RSAPrivateKey();
            key.setKey(pki);
        }
    }

    return key;
}