Example usage for org.bouncycastle.openssl PEMParser PEMParser

List of usage examples for org.bouncycastle.openssl PEMParser PEMParser

Introduction

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

Prototype

public PEMParser(Reader reader) 

Source Link

Document

Create a new PEMReader

Usage

From source file:org.sonatype.nexus.ssl.CertificateUtil.java

License:Open Source License

/**
 * Decodes a PEM formatted certificate./*www  .  ja v  a 2  s  .  com*/
 *
 * @param pemFormattedCertificate text to be decoded as a PEM certificate.
 * @return the Certificate decoded from the input text.
 * @throws CertificateParsingException
 *          thrown if the PEM formatted string cannot be parsed into a Certificate.
 */
public static Certificate decodePEMFormattedCertificate(final String pemFormattedCertificate)
        throws CertificateException {
    log.trace("Parsing PEM formatted certificate string:\n{}", pemFormattedCertificate);

    // make sure we have something to parse
    if (pemFormattedCertificate != null) {
        StringReader stringReader = new StringReader(pemFormattedCertificate);
        PEMParser pemReader = new PEMParser(stringReader);
        try {
            Object object = pemReader.readObject();
            log.trace("Object found while paring PEM formatted string: {}", object);

            if (object instanceof X509CertificateHolder) {
                X509CertificateHolder holder = (X509CertificateHolder) object;
                JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
                return converter.getCertificate(holder);
            }
        } catch (IOException e) {
            throw new CertificateParsingException(
                    "Failed to parse valid certificate from expected PEM formatted certificate:\n"
                            + pemFormattedCertificate,
                    e);
        }
    }

    // cert was not a valid object
    throw new CertificateParsingException(
            "Failed to parse valid certificate from expected PEM formatted certificate:\n"
                    + pemFormattedCertificate);
}

From source file:org.soulwing.credo.service.crypto.bc.BcCredentialBag.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  ww.  ja va2s. c  o m*/
 */
@Override
public int addAllObjects(InputStream inputStream) throws IOException {
    List<BcWrapper> objects = new ArrayList<>();
    try (PEMParser parser = new PEMParser(new InputStreamReader(inputStream, "UTF-8"))) {
        Object obj = parser.readObject();
        while (obj != null) {
            if (obj instanceof PKCS8EncryptedPrivateKeyInfo) {
                objects.add(new BcPrivateKeyWrapper(obj, objectBuilderFactory));
            } else if (obj instanceof PEMEncryptedKeyPair) {
                objects.add(new BcPrivateKeyWrapper(obj, objectBuilderFactory));
            } else if (obj instanceof PEMKeyPair) {
                objects.add(new BcPrivateKeyWrapper(obj, objectBuilderFactory));
            } else if (obj instanceof X509CertificateHolder) {
                objects.add(new BcCertificateWrapper((X509CertificateHolder) obj));
            } else {
                logger.info("unrecognized object of type: {}", obj.getClass().getName());
            }
            obj = parser.readObject();
        }
    }

    this.objects.addAll(objects);
    return objects.size();
}

From source file:org.springframework.cloud.context.encrypt.EncryptorFactory.java

License:Apache License

private String normalizePem(String data) {
    PEMKeyPair pemKeyPair = null;/*from   w w  w  .  ja  va 2s.co m*/
    try (PEMParser pemParser = new PEMParser(new StringReader(data))) {
        pemKeyPair = (PEMKeyPair) pemParser.readObject();
        PrivateKeyInfo privateKeyInfo = pemKeyPair.getPrivateKeyInfo();

        StringWriter textWriter = new StringWriter();
        try (PemWriter pemWriter = new PemWriter(textWriter)) {
            PemObjectGenerator pemObjectGenerator = new MiscPEMGenerator(privateKeyInfo);

            pemWriter.writeObject(pemObjectGenerator);
            pemWriter.flush();
            return textWriter.toString();
        }
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.tdmx.client.crypto.certificate.CertificateIOUtils.java

License:Open Source License

public static PKIXCertificate[] pemToX509certs(String input) throws CryptoCertificateException {
    StringReader sr = new StringReader(input);
    PEMParser pp = new PEMParser(sr);

    List<PKIXCertificate> certList = new ArrayList<>();
    Object o = null;//from ww  w . j  a  v  a  2  s .c om
    try {
        while ((o = pp.readObject()) != null) {
            if (o instanceof X509CertificateHolder) {
                X509CertificateHolder ch = (X509CertificateHolder) o;
                PKIXCertificate c = decodeX509(ch.getEncoded());
                certList.add(c);
            }
        }
    } catch (IOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_IO, e);
    } finally {
        try {
            pp.close();
        } catch (IOException e) {
        }
    }
    return certList.toArray(new PKIXCertificate[0]);
}

From source file:org.tdmx.client.crypto.certificate.PrivateKeyIOUtils.java

License:Open Source License

public static KeyPair pemToRSAPrivateKeyPair(String input) throws CryptoCertificateException {
    StringReader sr = new StringReader(input);
    PEMParser pp = new PEMParser(sr);

    Object o = null;/*  www  .j  a v a2s .  c  o m*/
    try {
        while ((o = pp.readObject()) != null) {
            if (o instanceof PEMKeyPair) {
                PEMKeyPair ch = (PEMKeyPair) o;

                byte[] pkbytes = ch.getPublicKeyInfo().getEncoded(ASN1Encoding.DER);
                KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
                EncodedKeySpec eks = new X509EncodedKeySpec(pkbytes);
                PublicKey publicKey = kf.generatePublic(eks);

                byte[] privbytes = ch.getPrivateKeyInfo().getEncoded(ASN1Encoding.DER);
                EncodedKeySpec epks = new PKCS8EncodedKeySpec(privbytes);
                PrivateKey privateKey = kf.generatePrivate(epks);

                KeyPair kp = new KeyPair(publicKey, privateKey);
                return kp;
            }
        }
    } catch (IOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_IO, e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_MISSING_ALGORITHM, e);
    } catch (InvalidKeySpecException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_INVALID_KEY_SPEC, e);
    } finally {
        try {
            pp.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:org.tdmx.client.crypto.certificate.TrustStoreCertificateIOUtils.java

License:Open Source License

public static List<TrustStoreEntry> pemToTrustStoreEntries(String input) throws CryptoCertificateException {
    StringReader sr = new StringReader(input);
    PEMParser pp = new PEMParser(sr);

    List<TrustStoreEntry> certList = new ArrayList<>();
    Object o = null;//from  w w  w . j a va  2s . com
    try {
        while ((o = pp.readObject()) != null) {
            if (o instanceof X509CertificateHolder) {
                X509CertificateHolder ch = (X509CertificateHolder) o;
                PKIXCertificate c = CertificateIOUtils.decodeX509(ch.getEncoded());
                certList.add(new TrustStoreEntry(c));
            }
        }
        pp.close();
    } catch (IOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_IO, e);
    }

    BufferedReader br = new BufferedReader(new StringReader(input));
    String strLine;
    try {
        while ((strLine = br.readLine()) != null) {
            if (strLine.startsWith(TrustStoreEntry.FRIENDLY_NAME)) {
                String restofLine = strLine.substring(TrustStoreEntry.FRIENDLY_NAME.length());
                int separator = restofLine.indexOf(" ");
                if (separator != -1) {
                    String fingerprint = restofLine.substring(0, separator);
                    String text = restofLine.substring(separator + 1);

                    for (TrustStoreEntry e : certList) {

                        if (fingerprint.equals(e.getCertificate().getFingerprint())) {
                            e.setFriendlyName(text);
                        }
                    }
                }
            }
            if (strLine.startsWith(TrustStoreEntry.COMMENT_LINE)) {
                String restofLine = strLine.substring(TrustStoreEntry.COMMENT_LINE.length());
                int separator = restofLine.indexOf(" ");
                if (separator != -1) {
                    String fingerprint = restofLine.substring(0, separator);
                    String text = restofLine.substring(separator + 1);

                    for (TrustStoreEntry e : certList) {
                        if (fingerprint.equals(e.getCertificate().getFingerprint())) {
                            e.addComment(text);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_IO, e);
    }

    return certList;
}

From source file:org.thingsboard.gateway.extensions.mqtt.client.conf.credentials.CertPemClientCredentials.java

License:Apache License

private Object readPEMFile(String filePath) throws Exception {
    PEMParser reader = new PEMParser(new FileReader(filePath));
    Object fileHolder = reader.readObject();
    reader.close();/*from   w  w w  . j  a  v  a  2 s . c o  m*/
    return fileHolder;
}

From source file:org.usrz.libs.crypto.pem.PEMReader.java

License:Apache License

/**
 * Create a {@link PEMReader} loading from an {@link InputStream}.
 *///from   w  w w  .j  a v  a  2 s  . co m
public PEMReader(InputStream input) {
    if (input == null)
        throw new NullPointerException("Null input stream");

    factory = new PEMFactory();
    parser = new PEMParser(new InputStreamReader(input, ASCII));
}

From source file:org.usrz.libs.crypto.pem.PEMReader.java

License:Apache License

/**
 * Create a {@link PEMReader} loading from a {@link Reader}.
 *///w  ww  .  j  a  v  a2  s.  c  o  m
public PEMReader(Reader reader) {
    if (reader == null)
        throw new NullPointerException("Null reader");

    factory = new PEMFactory();
    parser = new PEMParser(reader);
}

From source file:org.usrz.libs.crypto.pem.PEMReader.java

License:Apache License

/**
 * Create a {@link PEMReader} loading from an {@link InputStream}.
 *///from   w w w.  j a  v a  2s .c om
public PEMReader(String provider, InputStream input) throws NoSuchProviderException {
    if (input == null)
        throw new NullPointerException("Null input stream");
    if (provider == null)
        throw new NullPointerException("Null provider");

    factory = new PEMFactory(provider);
    parser = new PEMParser(new InputStreamReader(input, ASCII));
}