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

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

Introduction

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

Prototype

JcaPEMKeyConverter

Source Link

Usage

From source file:com.trustly.api.security.KeyChain.java

License:Open Source License

/**
 * Loads the merchant private key./*from   w  ww .  jav  a 2  s . co  m*/
 * @param privateKeyFilename path to and name of private key.
 * @param password Password for the private key. "" or null if key requires no password.
 * @throws KeyException if key failed to load. For example if the path is incorrect.
 */
void loadMerchantPrivateKey(final String privateKeyFilename, final String password) throws KeyException {
    try {
        final File privateKeyFile = new File(privateKeyFilename); // private key file in PEM format
        final PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
        final Object object = pemParser.readObject();

        final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter();

        final KeyPair kp;
        if (object instanceof PEMEncryptedKeyPair) { // Password required
            kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
        } else {
            kp = converter.getKeyPair((PEMKeyPair) object);
        }

        merchantPrivateKey = kp.getPrivate();
    } catch (final IOException e) {
        throw new KeyException("Failed to load private key", e);
    }
}

From source file:com.trustly.api.security.KeyChain.java

License:Open Source License

/**
 * Loads the Trustly public key./*w  ww  .ja  v a2s.  c  o  m*/
 * @param testEnvironment whether to load the key for test environment or not.
 */
private void loadTrustlyPublicKey(final boolean testEnvironment) {
    try {
        final File file = testEnvironment ? new File(TEST_TRUSTLY_PUBLIC_KEY_PATH)
                : new File(LIVE_TRUSTLY_PUBLIC_KEY_PATH);

        final PEMParser pemParser = new PEMParser(new FileReader(file));
        final PemObject object = pemParser.readPemObject();

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

        final byte[] encoded = object.getContent();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(encoded));

        trustlyPublicKey = converter.getPublicKey(subjectPublicKeyInfo);
    } catch (final IOException e) {
        throw new TrustlyAPIException("Failed to load Trustly public key", e);
    }
}

From source file:com.vmware.admiral.common.util.CertificateUtil.java

License:Open Source License

/**
 * Utility method to decode a PEM encoded private key string to a PrivateKey instance
 *
 * @param key/*from   ww  w .j  av  a2s  . c o m*/
 *            - a PEM encoded private key string
 * @return - decoded PrivateKey instance
 */
public static KeyPair createKeyPair(String key) {
    AssertUtil.assertNotNull(key, "key");
    String decryptedKey = EncryptionUtils.decrypt(key);
    try (PEMParser parser = new PEMParser(new StringReader(decryptedKey))) {

        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        PEMKeyPair keyPair = (PEMKeyPair) parser.readObject();
        if (keyPair == null) {
            throw new RuntimeException("A valid key pair was not found");
        }
        return converter.getKeyPair(keyPair);

    } catch (IOException e) {
        throw new RuntimeException("Failed to create key pair", e);
    }
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static PublicKey loadPublicKey(Reader r) throws CryptoException {
    try (org.bouncycastle.openssl.PEMParser pemReader = new org.bouncycastle.openssl.PEMParser(r)) {
        PublicKey pubKey = null;//from  w  w w.ja  v a  2s  .  com
        Object pemObj = pemReader.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        SubjectPublicKeyInfo keyInfo = null;
        X9ECParameters ecParam = null;

        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 Public 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 org.bouncycastle.cert.X509CertificateHolder) {
            keyInfo = ((org.bouncycastle.cert.X509CertificateHolder) pemObj).getSubjectPublicKeyInfo();
        } else {
            keyInfo = (SubjectPublicKeyInfo) pemObj;
        }
        pubKey = pemConverter.getPublicKey(keyInfo);

        if (ecParam != null && ECDSA.equals(pubKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(),
                    ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BC_PROVIDER);
            ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) pubKey).getQ(), ecSpec);
            pubKey = (PublicKey) keyFactory.generatePublic(keySpec);
        }
        return pubKey;
    } catch (PEMException e) {
        throw new CryptoException(e);
    } catch (NoSuchProviderException e) {
        LOG.error(
                "loadPublicKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(
                "loadPublicKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
        throw new CryptoException(e);
    } catch (InvalidKeySpecException e) {
        LOG.error("loadPublicKey: Caught InvalidKeySpecException, invalid key spec is being used.");
        throw new CryptoException("InvalidKeySpecException");
    } catch (IOException e) {
        throw new CryptoException(e);
    }
}

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;/*from ww  w.  j a v a 2 s  .  c o  m*/

        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:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static String extractX509CSRPublicKey(PKCS10CertificationRequest certReq) {

    JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
    PublicKey publicKey = null;//from  w  w  w  .  j ava 2 s . co  m
    try {
        publicKey = pemConverter.getPublicKey(certReq.getSubjectPublicKeyInfo());
    } catch (PEMException ex) {
        LOG.error("extractX509CSRPublicKey: unable to get public key: {}", ex.getMessage());
        return null;
    }

    return convertToPEMFormat(publicKey);
}

From source file:craterdog.security.RsaCertificateManager.java

License:Open Source License

/**
 * This method signs a certificate signing request (CSR) using the specified certificate
 * authority (CA).   This is a convenience method that really should be part of the
 * <code>CertificateManagement</code> interface except that it depends on a Bouncy Castle
 * class in the signature.  The java security framework does not have a similar class so it
 * has been left out of the interface.// ww  w  .  j  a  v  a 2  s.c o m
 *
 * @param caPrivateKey The private key for the certificate authority.
 * @param caCertificate The certificate containing the public key for the certificate authority.
 * @param request The certificate signing request (CSR) to be signed.
 * @param serialNumber The serial number for the new certificate.
 * @param lifetime How long the certificate should be valid.
 *
 * @return The newly signed certificate.
 */
public X509Certificate signCertificateRequest(PrivateKey caPrivateKey, X509Certificate caCertificate,
        PKCS10CertificationRequest request, BigInteger serialNumber, long lifetime) {
    try {
        logger.entry();

        logger.debug("Extract public key and subject from the CSR...");
        PublicKey publicKey = new JcaPEMKeyConverter().getPublicKey(request.getSubjectPublicKeyInfo());
        String subject = request.getSubject().toString();

        logger.debug("Generate and sign the certificate...");
        X509Certificate result = createCertificate(caPrivateKey, caCertificate, publicKey, subject,
                serialNumber, lifetime);

        logger.exit();
        return result;

    } catch (PEMException e) {
        RuntimeException exception = new RuntimeException(
                "An unexpected exception occurred while attempting to sign a certificate.", e);
        throw logger.throwing(exception);
    }
}

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

License:Open Source License

private KeyPair keyFromPEMObject(Object pemObject, PasswordCallback password, String resource)
        throws IOException {
    PEMKeyPair keyPair = null;//from   ww w.  j av a2s  .  c o m

    if (pemObject instanceof PEMEncryptedKeyPair) {
        PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) pemObject;
        JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
        String passwordInput = (password != null ? password.queryPassword(resource) : null);
        Exception invalidPasswordException = null;

        while (keyPair == null) {
            if (passwordInput == null) {
                throw new PasswordRequiredException("Password required for PEM object: '" + resource + "'",
                        invalidPasswordException);
            }

            assert password != null;

            PEMDecryptorProvider decryptorProvider = decryptorBuilder.build(passwordInput.toCharArray());

            try {
                keyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider);
            } catch (EncryptionException e) {
                invalidPasswordException = e;
                passwordInput = password.requeryPassword(resource, e);
            }
        }
    } else {
        keyPair = (PEMKeyPair) pemObject;
    }

    JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter();

    return keyConverter.getKeyPair(keyPair);
}

From source file:de.mendelson.util.security.PEMKeys2Keystore.java

/**
 * @param pemReader Reader that accesses the RSA key in PEM format
 * @param keypass Passphrase for the keys stored in the PEM file
 * @param certificateStream Stream that accesses the certificate for the
 * keys//from   ww  w  .  ja  va 2 s .  c  om
 * @param alias Alias to use in the new keystore
 *
 */
public void importKey(Reader pemReader, char[] keypass, InputStream certificateStream, String alias)
        throws Exception {
    this.keypass = keypass;
    PEMParser pemParser = new PEMParser(pemReader);
    Object readObject = pemParser.readObject();

    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keypass);
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    PrivateKey privateKey = null;
    if (readObject instanceof PEMEncryptedKeyPair) {
        //Encrypted key - use provided password
        KeyPair keyPair = converter
                .getKeyPair(((PEMEncryptedKeyPair) readObject).decryptKeyPair(decryptorProvider));
        privateKey = keyPair.getPrivate();
    } else if (readObject instanceof PrivateKeyInfo) {
        //PKCS#8 format, the object will be an instanceof PrivateKeyInfo
        privateKey = converter.getPrivateKey((PrivateKeyInfo) readObject);
    } else {
        //Unencrypted key - no password needed
        KeyPair keyPair = converter.getKeyPair((PEMKeyPair) readObject);
        privateKey = keyPair.getPrivate();
    }
    X509Certificate cert = this.readCertificate(certificateStream);
    KeyStore store = this.keystore;
    if (store == null) {
        store = this.generateKeyStore();
    }
    //PKCS12 keys dont have a password, anyway take the given keystore pass as key pass for JKS
    store.setKeyEntry(alias, privateKey, keypass, new X509Certificate[] { cert });
}

From source file:de.mendelson.util.security.PEMKeys2PKCS12.java

/**
 * @param pemReader Reader that accesses the RSA key in PEM format
 * @param keypass Passphrase for the keys stored in the PEM file
 * @param certificateStream Stream that accesses the certificate for the
 * keys/*from ww w .  j  a  v  a2 s . c o  m*/
 * @param alias Alias to use in the new keystore
 *
 */
public void importKey(Reader pemReader, char[] keypass, InputStream certificateStream, String alias)
        throws Exception {
    this.keypass = keypass;
    PEMParser pemParser = new PEMParser(pemReader);
    Object readObject = pemParser.readObject();
    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keypass);
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    PrivateKey privateKey = null;
    if (readObject instanceof PEMEncryptedKeyPair) {
        //Encrypted key - use provided password
        KeyPair keyPair = converter
                .getKeyPair(((PEMEncryptedKeyPair) readObject).decryptKeyPair(decryptorProvider));
        privateKey = keyPair.getPrivate();
    } else if (readObject instanceof PrivateKeyInfo) {
        //PKCS#8 format, the object will be an instanceof PrivateKeyInfo
        privateKey = converter.getPrivateKey((PrivateKeyInfo) readObject);
    } else {
        //Unencrypted key - no password needed
        KeyPair keyPair = converter.getKeyPair((PEMKeyPair) readObject);
        privateKey = keyPair.getPrivate();
    }
    X509Certificate cert = this.readCertificate(certificateStream);
    KeyStore store = this.keystore;
    if (store == null) {
        store = this.generateKeyStore();
    }
    //PKCS12 keys dont have a password
    store.setKeyEntry(alias, privateKey, "dummy".toCharArray(), new X509Certificate[] { cert });
}