Example usage for org.bouncycastle.openssl.jcajce JceOpenSSLPKCS8DecryptorProviderBuilder JceOpenSSLPKCS8DecryptorProviderBuilder

List of usage examples for org.bouncycastle.openssl.jcajce JceOpenSSLPKCS8DecryptorProviderBuilder JceOpenSSLPKCS8DecryptorProviderBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.openssl.jcajce JceOpenSSLPKCS8DecryptorProviderBuilder JceOpenSSLPKCS8DecryptorProviderBuilder.

Prototype

public JceOpenSSLPKCS8DecryptorProviderBuilder() 

Source Link

Usage

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

License:Open Source License

/**
 * Construct a new key factory.//from  w  ww. j av a  2s  .c o  m
 */
public KeyFactory() {
    BouncyCastleProvider provider = new BouncyCastleProvider();

    this.pemParserFactory = new PemParserFactory();
    this.bcKeyParametersFactory = new BcKeyParametersFactory();

    this.pemDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
    this.pemDecryptorProviderBuilder.setProvider(provider);
    this.pkcs8DecryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
    this.pkcs8DecryptorProviderBuilder.setProvider(provider);

    this.keyGenerator = new RSAKeyPairGenerator();
    this.random = new SecureRandom();
}

From source file:com.aqnote.shared.cryptology.cert.io.PKCSReader.java

License:Open Source License

public static PrivateKey readPrivateKey(InputStream istream, final char[] pwd) {
    if (istream == null || pwd == null)
        return null;

    try {/*from   www .  java2s . c o m*/
        Object object = readFile(istream);
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(pwd);
            return keyConverter
                    .getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) object).decryptPrivateKeyInfo(provider));
        } else if (object instanceof PrivateKeyInfo) {
            return keyConverter.getPrivateKey((PrivateKeyInfo) object);
        } else if (object instanceof PEMEncryptedKeyPair) {
            PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(pwd);
            return keyConverter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(provider))
                    .getPrivate();
        } else if (object instanceof PEMKeyPair) {
            return keyConverter.getKeyPair((PEMKeyPair) object).getPrivate();
        }
    } catch (Throwable t) {
        logger.error(MSG(R.F, "readPrivateKey", t.getMessage()), t);
    }
    return null;
}

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

License:Apache License

public static PrivateKey decodePrivateKey(String privateKeyString, String password) throws KeyParseException {
    try {//  w  w w.j a va2 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.hypersocket.certs.X509CertificateUtils.java

License:Open Source License

public static KeyPair loadKeyPairFromPEM(InputStream keyfile, char[] passphrase)
        throws InvalidPassphraseException, CertificateException, FileFormatException {

    PEMParser parser = new PEMParser(new InputStreamReader(keyfile));
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
    try {//w w w  .ja  v  a 2 s .c  om

        Object privatekey = parser.readObject();

        if (privatekey instanceof PEMEncryptedKeyPair) {
            try {
                privatekey = ((PEMEncryptedKeyPair) privatekey)
                        .decryptKeyPair(new JcePEMDecryptorProviderBuilder().build(passphrase));
            } catch (Exception e) {
                throw new InvalidPassphraseException(e);
            }
        } else if (privatekey instanceof PKCS8EncryptedPrivateKeyInfo) {
            try {
                privatekey = converter
                        .getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) privatekey).decryptPrivateKeyInfo(
                                new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase)));
            } catch (Exception e) {
                throw new InvalidPassphraseException(e);
            }
        }

        if (privatekey instanceof PEMKeyPair) {
            return loadKeyPair((PEMKeyPair) privatekey);
        } else if (privatekey instanceof RSAPrivateCrtKey) {
            return loadKeyPair((RSAPrivateCrtKey) privatekey);
        } else if (privatekey instanceof PrivateKeyInfo) {
            PrivateKeyInfo i = (PrivateKeyInfo) privatekey;
            PrivateKey prv = converter.getPrivateKey(i);
            if (prv instanceof RSAPrivateCrtKey) {
                return loadKeyPair((RSAPrivateCrtKey) prv);
            } else {
                throw new FileFormatException("Unsupported private key type");
            }
        } else {
            throw new FileFormatException(
                    "The file doesn't seem to have any supported key types obj=" + privatekey);
        }

    } catch (IOException ex) {
        throw new CertificateException("Failed to read from key file", ex);
    } finally {
        try {
            parser.close();
        } catch (IOException e) {
        }
    }
}

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

public byte[] decryptFileKey(String filekey, String privateKey) {
    try {/*from  ww w . j  a va 2s  . c  om*/
        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.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static PrivateKey loadPrivateKey(Reader reader, String pwd) throws CryptoException {

    try (PEMParser pemReader = new PEMParser(reader)) {
        PrivateKey privKey = null;
        X9ECParameters ecParam = null;// ww w  .j av  a2 s .  c om

        Object pemObj = pemReader.readObject();

        if (pemObj instanceof ASN1ObjectIdentifier) {

            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Private Key

            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: "
                        + ((ASN1ObjectIdentifier) pemObj).getId());
            }

            pemObj = pemReader.readObject();

        } else if (pemObj instanceof X9ECParameters) {

            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }

        if (pemObj instanceof PEMKeyPair) {

            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo();
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(pKeyInfo);

        } else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {

            PKCS8EncryptedPrivateKeyInfo pKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
            if (pwd == null) {
                throw new CryptoException("No password specified to decrypt encrypted private key");
            }

            // Decrypt the private key with the specified password

            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .setProvider(BC_PROVIDER).build(pwd.toCharArray());

            PrivateKeyInfo privateKeyInfo = pKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(privateKeyInfo);
        }

        // if our private key is EC type and we have parameters specified
        // then we need to set it accordingly

        if (ecParam != null && ECDSA.equals(privKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(),
                    ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BC_PROVIDER);
            ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privKey).getS(), ecSpec);
            privKey = (PrivateKey) keyFactory.generatePrivate(keySpec);
        }

        return privKey;

    } catch (PEMException e) {
        LOG.error("loadPrivateKey: Caught PEMException, problem with format of key detected.");
        throw new CryptoException(e);
    } catch (NoSuchProviderException e) {
        LOG.error(
                "loadPrivateKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(
                "loadPrivateKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
        throw new CryptoException(e);
    } catch (InvalidKeySpecException e) {
        LOG.error("loadPrivateKey: Caught InvalidKeySpecException, invalid key spec is being used.");
        throw new CryptoException(e);
    } catch (OperatorCreationException e) {
        LOG.error(
                "loadPrivateKey: Caught OperatorCreationException when creating JceOpenSSLPKCS8DecryptorProviderBuilder.");
        throw new CryptoException(e);
    } catch (PKCSException e) {
        LOG.error("loadPrivateKey: Caught PKCSException when decrypting private key.");
        throw new CryptoException(e);
    } catch (IOException e) {
        LOG.error("loadPrivateKey: Caught IOException, while trying to read key.");
        throw new CryptoException(e);
    }
}

From source file:craterdog.security.RsaCertificateManager.java

License:Open Source License

@Override
public PrivateKey decodePrivateKey(String pem, char[] password) {
    logger.entry();/*from   w  ww.  j a  va2s .c  o  m*/
    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: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  a2 s.co 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:net.jsign.PrivateKeyUtils.java

License:Apache License

private static PrivateKey readPrivateKeyPEM(File file, String password)
        throws IOException, GeneralSecurityException, OperatorCreationException, PKCSException {
    try (FileReader reader = new FileReader(file)) {
        PEMParser parser = new PEMParser(reader);
        Object object = parser.readObject();

        if (object == null) {
            throw new IllegalArgumentException("No key found in " + file);
        }//ww w  .  j av a2 s.c o m

        BouncyCastleProvider provider = new BouncyCastleProvider();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(provider);

        if (object instanceof PEMEncryptedKeyPair) {
            // PKCS1 encrypted key
            PEMDecryptorProvider decryptionProvider = new JcePEMDecryptorProviderBuilder().setProvider(provider)
                    .build(password.toCharArray());
            PEMKeyPair keypair = ((PEMEncryptedKeyPair) object).decryptKeyPair(decryptionProvider);
            return converter.getPrivateKey(keypair.getPrivateKeyInfo());

        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            // PKCS8 encrypted key
            InputDecryptorProvider decryptionProvider = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .setProvider(provider).build(password.toCharArray());
            PrivateKeyInfo info = ((PKCS8EncryptedPrivateKeyInfo) object)
                    .decryptPrivateKeyInfo(decryptionProvider);
            return converter.getPrivateKey(info);

        } else if (object instanceof PEMKeyPair) {
            // PKCS1 unencrypted key
            return converter.getKeyPair((PEMKeyPair) object).getPrivate();

        } else if (object instanceof PrivateKeyInfo) {
            // PKCS8 unencrypted key
            return converter.getPrivateKey((PrivateKeyInfo) object);

        } else {
            throw new UnsupportedOperationException(
                    "Unsupported PEM object: " + object.getClass().getSimpleName());
        }
    }
}

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 w  w  .j  ava  2s.co  m*/
 *            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;
}