List of usage examples for org.bouncycastle.openssl PEMParser PEMParser
public PEMParser(Reader reader)
From source file:net.etfbl.cryptodigitalcertificate.tool.util.CryptoPEMExtractor.java
public Object loadObject(String filePath) throws FileNotFoundException, IOException { PEMParser reader = new PEMParser(new InputStreamReader(new FileInputStream(filePath))); Object keyObject = reader.readObject(); reader.close();// w ww .j a v a 2s. com return keyObject; }
From source file:net.etfbl.cryptodigitalcertificate.tool.util.CryptoPEMExtractor.java
public Object loadObject(InputStream stream) throws FileNotFoundException, IOException { PEMParser reader = new PEMParser(new InputStreamReader(stream)); Object keyObject = reader.readObject(); reader.close();//w w w.ja va 2s .c om return keyObject; }
From source file:net.etfbl.cryptodigitalcertificate.tool.util.CryptoPEMExtractor.java
public KeyPair loadKeyPair(String filePath) throws FileNotFoundException, IOException { PEMParser reader = new PEMParser(new InputStreamReader(new FileInputStream(filePath))); Object keyObject = reader.readObject(); reader.close();/*from ww w. j a v a2s .c om*/ PEMKeyPair pemPair = (PEMKeyPair) keyObject; KeyPair pair = new JcaPEMKeyConverter().getKeyPair(pemPair); return pair; }
From source file:net.etfbl.cryptodigitalcertificate.tool.util.CryptoPEMExtractor.java
public KeyPair loadKeyPair(InputStream stream) throws FileNotFoundException, IOException { PEMParser reader = new PEMParser(new InputStreamReader(stream)); Object keyObject = reader.readObject(); reader.close();/*from w ww. ja v a 2s.c o m*/ PEMKeyPair pemPair = (PEMKeyPair) keyObject; KeyPair pair = new JcaPEMKeyConverter().getKeyPair(pemPair); return pair; }
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); }/*from w ww . j a v 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:net.sf.portecle.crypto.X509CertUtil.java
License:Open Source License
/** * Load one or more certificates from the specified URL. * /*from w ww. j a v a2 s. c o m*/ * @param url The URL to load certificates from * @param encoding The certification path encoding. If null, treat as a normal certificate, not * certification path. Use one of the <code>*_ENCODING</code> constants here. * @return The certificates * @throws CryptoException Problem encountered while loading the certificate(s) * @throws FileNotFoundException If the certificate file does not exist, is a directory rather than a * regular file, or for some other reason cannot be opened for reading * @throws IOException An I/O error occurred */ private static X509Certificate[] loadCertificates(URL url, String encoding) throws CryptoException, IOException { // TODO: connect/read timeouts Collection certs; try (InputStream in = NetUtil.openGetStream(url)) { if (OPENSSL_PEM_ENCODING.equals(encoding)) { // Special case; this is not a real JCE supported encoding. try (PEMParser pr = new PEMParser(new InputStreamReader(in))) { certs = new ArrayList<X509Certificate>(); Object cert; CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE); while (true) { cert = pr.readObject(); if (cert == null) { break; } if (cert instanceof X509CertificateHolder) { ByteArrayInputStream bais = new ByteArrayInputStream( ((X509CertificateHolder) cert).getEncoded()); certs.add(cf.generateCertificate(bais)); } // Skip other stuff, at least for now. } } } else { CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE); if (encoding != null) { // Try it as a certification path of the specified type certs = cf.generateCertPath(in, encoding).getCertificates(); } else { // "Normal" certificate(s) certs = cf.generateCertificates(in); } // Note that we rely on cf.generateCert() above to never return null nor a collection // containing nulls. } } // Some RuntimeExceptions which really should be CertificateExceptions may be thrown from // cf.generateCert* above, for example Oracle's PKCS #7 parser tends to throw them... :P catch (Exception ex) { // TODO: don't throw if vCerts non-empty (eg. OpenSSL PEM above)? throw new CryptoException(RB.getString("NoLoadCertificate.exception.message"), ex); } return (X509Certificate[]) certs.toArray(new X509Certificate[certs.size()]); }
From source file:net.sf.portecle.crypto.X509CertUtil.java
License:Open Source License
/** * Load a CSR from the specified URL./* w ww . j a va2s .com*/ * * @param url The URL to load CSR from * @return The CSR * @throws CryptoException Problem encountered while loading the CSR * @throws FileNotFoundException If the CSR file does not exist, is a directory rather than a regular * file, or for some other reason cannot be opened for reading * @throws IOException An I/O error occurred */ public static PKCS10CertificationRequest loadCSR(URL url) throws CryptoException, IOException { // TODO: handle DER encoded requests too? try (PEMParser pr = new PEMParser(new InputStreamReader(NetUtil.openGetStream(url)))) { PKCS10CertificationRequest csr = (PKCS10CertificationRequest) pr.readObject(); ContentVerifierProvider prov = new JcaContentVerifierProviderBuilder() .build(csr.getSubjectPublicKeyInfo()); if (!csr.isSignatureValid(prov)) { throw new CryptoException(RB.getString("NoVerifyCsr.exception.message")); } return csr; } catch (ClassCastException | OperatorCreationException | PKCSException ex) { throw new CryptoException(RB.getString("NoLoadCsr.exception.message"), ex); } }
From source file:net.sf.portecle.FPortecle.java
License:Open Source License
/** * Let the user import a key pair a PKCS #12 keystore or a PEM bundle. * /*from w w w . ja v a 2 s. c o m*/ * @return True if the import is successful, false otherwise */ private boolean importKeyPair() { assert m_keyStoreWrap != null; assert m_keyStoreWrap.getKeyStore() != null; KeyStore keyStore = m_keyStoreWrap.getKeyStore(); // Let the user choose a file to import from File fKeyPairFile = chooseImportFile(); if (fKeyPairFile == null) { return false; } m_lastDir.updateLastDir(fKeyPairFile); // Not a file? if (!fKeyPairFile.isFile()) { JOptionPane.showMessageDialog(this, MessageFormat.format(RB.getString("FPortecle.NotFile.message"), fKeyPairFile), RB.getString("FPortecle.ImportKeyPair.Title"), JOptionPane.WARNING_MESSAGE); return false; } ArrayList<Exception> exceptions = new ArrayList<>(); PasswordFinder passwordFinder = new PasswordFinder() { private int passwordNumber = 1; @Override public char[] getPassword() { // Get the user to enter the private key password DGetPassword dGetPassword = new DGetPassword(FPortecle.this, MessageFormat.format(RB.getString("FPortecle.PrivateKeyPassword.Title"), new Object[] { String.valueOf(passwordNumber) })); dGetPassword.setLocationRelativeTo(FPortecle.this); SwingHelper.showAndWait(dGetPassword); char[] cPassword = dGetPassword.getPassword(); passwordNumber++; return cPassword; } }; KeyStore tempStore = null; try (PEMParser reader = new PEMParser(new FileReader(fKeyPairFile.getPath()))) { tempStore = KeyStoreUtil.loadEntries(reader, passwordFinder); if (tempStore.size() == 0) { tempStore = null; } } catch (Exception e) { exceptions.add(e); } // Treat as PKCS #12 keystore if (tempStore == null) { // Get the user to enter the PKCS #12 keystore's password DGetPassword dGetPassword = new DGetPassword(this, RB.getString("FPortecle.Pkcs12Password.Title")); dGetPassword.setLocationRelativeTo(this); SwingHelper.showAndWait(dGetPassword); char[] cPkcs12Password = dGetPassword.getPassword(); if (cPkcs12Password == null) { return false; } // Load the PKCS #12 keystore try { tempStore = KeyStoreUtil.loadKeyStore(fKeyPairFile, cPkcs12Password, KeyStoreType.PKCS12); } catch (Exception e) { exceptions.add(e); } } if (tempStore == null && !exceptions.isEmpty()) { int iSelected = SwingHelper.showConfirmDialog(this, MessageFormat.format(RB.getString("FPortecle.NoOpenKeyPairFile.message"), fKeyPairFile), RB.getString("FPortecle.ImportKeyPairFile.Title")); if (iSelected == JOptionPane.YES_OPTION) { for (Exception e : exceptions) { DThrowable.showAndWait(this, null, e); } } return false; } try { // Display the import key pair dialog supplying the PKCS #12 keystore to it DImportKeyPair dImportKeyPair = new DImportKeyPair(this, tempStore); dImportKeyPair.setLocationRelativeTo(this); SwingHelper.showAndWait(dImportKeyPair); // Get the private key and certificate chain of the key pair Key privateKey = dImportKeyPair.getPrivateKey(); Certificate[] certs = dImportKeyPair.getCertificateChain(); if (privateKey == null || certs == null) { // User did not select a key pair for import return false; } // Get an alias for the new keystore entry String sAlias = dImportKeyPair.getAlias(); if (sAlias == null) { sAlias = X509CertUtil.getCertificateAlias(X509CertUtil.convertCertificate(certs[0])); } sAlias = getNewEntryAlias(keyStore, sAlias, "FPortecle.KeyPairEntryAlias.Title", false); if (sAlias == null) { return false; } // Get a password for the new keystore entry if applicable char[] cPassword = KeyStoreUtil.DUMMY_PASSWORD; if (m_keyStoreWrap.getKeyStoreType().isEntryPasswordSupported()) { DGetNewPassword dGetNewPassword = new DGetNewPassword(this, RB.getString("FPortecle.KeyEntryPassword.Title")); dGetNewPassword.setLocationRelativeTo(this); SwingHelper.showAndWait(dGetNewPassword); cPassword = dGetNewPassword.getPassword(); if (cPassword == null) { return false; } } // Delete old entry first if (keyStore.containsAlias(sAlias)) { keyStore.deleteEntry(sAlias); } // Place the private key and certificate chain into the keystore and update the keystore wrapper keyStore.setKeyEntry(sAlias, privateKey, cPassword, certs); m_keyStoreWrap.setEntryPassword(sAlias, cPassword); m_keyStoreWrap.setChanged(true); // Update the frame's components and title selectedAlias = sAlias; updateControls(); updateTitle(); // Display success message JOptionPane.showMessageDialog(this, RB.getString("FPortecle.KeyPairImportSuccessful.message"), RB.getString("FPortecle.ImportKeyPair.Title"), JOptionPane.INFORMATION_MESSAGE); return true; } catch (Exception ex) { DThrowable.showAndWait(this, null, ex); return false; } }
From source file:net.sf.sahi.ssl.SSLHelper.java
License:Apache License
private PrivateKey readPrivateKey(String privateKeyPath) throws IOException { PEMKeyPair keyPair = (PEMKeyPair) new PEMParser(new FileReader(privateKeyPath)).readObject(); return new JcaPEMKeyConverter().getKeyPair(keyPair).getPrivate(); }
From source file:net.sf.sahi.ssl.SSLHelper.java
License:Apache License
private Object readWithPemParser(String source) throws IOException { PEMParser parser = new PEMParser(new FileReader(source)); return parser.readObject(); }