Example usage for org.apache.commons.ssl PKCS8Key PKCS8Key

List of usage examples for org.apache.commons.ssl PKCS8Key PKCS8Key

Introduction

In this page you can find the example usage for org.apache.commons.ssl PKCS8Key PKCS8Key.

Prototype

public PKCS8Key(final byte[] encoded, char[] password) throws GeneralSecurityException, IOException 

Source Link

Usage

From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHKeyPairProvider.java

private KeyPair getKeyPair(FileInputStream is) throws GeneralSecurityException, IOException {
    PKCS8Key pkcs8 = new PKCS8Key(is, password == null ? null : password.toCharArray());
    KeyPair kp = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
    return kp;//from   w  w  w  .j  ava 2s  . c om
}

From source file:org.apache.karaf.shell.ssh.OpenSSHGeneratorFileKeyProvider.java

@Override
protected KeyPair doReadKeyPair(String resourceKey, InputStream is)
        throws IOException, GeneralSecurityException {
    PKCS8Key pkcs8 = new PKCS8Key(is, password == null ? null : password.toCharArray());
    return new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
}

From source file:org.apache.kerby.pkix.PkiLoader.java

private PrivateKey doLoadPrivateKey(InputStream inputStream, String password)
        throws GeneralSecurityException, IOException {
    if (password == null) {
        password = "";
    }/*www  . ja v  a 2 s.com*/
    // If the provided InputStream is encrypted, we need a password to decrypt
    // it. If the InputStream is not encrypted, then the password is ignored
    // (can be null).  The InputStream can be DER (raw ASN.1) or PEM (base64).
    PKCS8Key pkcs8 = new PKCS8Key(inputStream, password.toCharArray());

    // If an unencrypted PKCS8 key was provided, then this actually returns
    // exactly what was originally passed inputStream (with no changes).  If an OpenSSL
    // key was provided, it gets reformatted as PKCS #8 first, and so these
    // bytes will still be PKCS #8, not OpenSSL.
    byte[] decrypted = pkcs8.getDecryptedBytes();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);

    // A Java PrivateKey object is born.
    PrivateKey pk = null;
    if (pkcs8.isDSA()) {
        pk = KeyFactory.getInstance("DSA").generatePrivate(spec);
    } else if (pkcs8.isRSA()) {
        pk = KeyFactory.getInstance("RSA").generatePrivate(spec);
    }

    // For lazier types:
    pk = pkcs8.getPrivateKey();

    return pk;
}

From source file:org.apache.whirr.util.KeyPair.java

public static boolean sameKeyPair(File privateKeyFile, File publicKeyFile) throws IOException {
    try {// w w w  .  j  av a  2  s .  c o m
        PKCS8Key decodedKey = new PKCS8Key(new FileInputStream(privateKeyFile), null);
        PublicKey publicKey = decodedKey.getPublicKey();

        byte[] actual = encodePublicKey((RSAPublicKey) publicKey);
        byte[] expected = IOUtils.toByteArray(new FileReader(publicKeyFile));

        for (int i = 0; i < actual.length; i += 1) {
            if (actual[i] != expected[i]) {
                return false;
            }
        }
        return true;
    } catch (GeneralSecurityException e) {
        LOG.error("Key pair validation failed", e);
        return false;
    }
}

From source file:org.auscope.portal.server.web.controllers.GridLoginController.java

/**
 * Extracts and decrypts the XML response received from the SLCS server
 *///ww  w . j a  v a2s .com
private String extractSlcsResponse(HttpServletRequest request) throws GeneralSecurityException, IOException {
    String responseXML = null;
    String certReqDataHex = request.getParameter("CertificateRequestData");
    String sessionKeyHex = request.getParameter("SessionKey");
    if (certReqDataHex == null || sessionKeyHex == null) {
        logger.error("CertificateRequestData or SessionKey empty!");
    } else {
        // load host key
        FileInputStream in = new FileInputStream(HOST_KEY_FILE);
        PKCS8Key pem = new PKCS8Key(in, null);
        Key privateKey = pem.getPrivateKey();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);

        // unwrap session key and decrypt request data
        byte[] wrappedKey = unhexlify(sessionKeyHex);
        ByteArrayInputStream certReqDataEnc = new ByteArrayInputStream(unhexlify(certReqDataHex));
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        responseXML = decryptString(certReqDataEnc, cipher);
    }
    return responseXML;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;//from ww w  . ja va  2s.c  o  m
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.haox.pki.Pkix.java

public static PrivateKey getPrivateKey(InputStream inputStream, String password)
        throws GeneralSecurityException, IOException {
    if (password == null)
        password = "";
    // If the provided InputStream is encrypted, we need a password to decrypt
    // it. If the InputStream is not encrypted, then the password is ignored
    // (can be null).  The InputStream can be DER (raw ASN.1) or PEM (base64).
    PKCS8Key pkcs8 = new PKCS8Key(inputStream, password.toCharArray());

    // If an unencrypted PKCS8 key was provided, then this actually returns
    // exactly what was originally passed inputStream (with no changes).  If an OpenSSL
    // key was provided, it gets reformatted as PKCS #8 first, and so these
    // bytes will still be PKCS #8, not OpenSSL.
    byte[] decrypted = pkcs8.getDecryptedBytes();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);

    // A Java PrivateKey object is born.
    PrivateKey pk = null;/*from w w w .j  ava 2  s .c om*/
    if (pkcs8.isDSA()) {
        pk = KeyFactory.getInstance("DSA").generatePrivate(spec);
    } else if (pkcs8.isRSA()) {
        pk = KeyFactory.getInstance("RSA").generatePrivate(spec);
    }

    // For lazier types:
    pk = pkcs8.getPrivateKey();

    return pk;
}

From source file:org.opensaml.xml.security.SecurityHelper.java

/**
 * Decodes RSA/DSA private keys in DER, PEM, or PKCS#8 (encrypted or unencrypted) formats.
 * /*from  w w  w  .j  a v a2  s  .  c  o  m*/
 * @param key encoded key
 * @param password decryption password or null if the key is not encrypted
 * 
 * @return deocded private key
 * 
 * @throws KeyException thrown if the key can not be decoded
 */
public static PrivateKey decodePrivateKey(byte[] key, char[] password) throws KeyException {
    try {
        PKCS8Key deocodedKey = new PKCS8Key(key, password);
        return deocodedKey.getPrivateKey();
    } catch (GeneralSecurityException e) {
        throw new KeyException("Unable to decode private key", e);
    }
}