List of usage examples for org.bouncycastle.openssl PEMParser readObject
public Object readObject() throws IOException
From source file:com.nimbusds.jose.jwk.PEMEncodedKeyParser.java
License:Apache License
/** * Parses one or more PEM-encoded certificates, public and / or private * keys. The input is assumed to be not password-protected. * * @param pemEncodedKeys String of one or more PEM-encoded keys. * * @return The found keys./*from w w w . ja va 2 s .c o m*/ * * @throws JOSEException If parsing failed. */ static List<KeyPair> parseKeys(final String pemEncodedKeys) throws JOSEException { // Strips the "---- {BEGIN,END} {CERTIFICATE,PUBLIC/PRIVATE KEY} -----"-like header and footer lines, // base64-decodes the body, // then uses the proper key specification format to turn it into a JCA Key instance final Reader pemReader = new StringReader(pemEncodedKeys); final PEMParser parser = new PEMParser(pemReader); final List<KeyPair> keys = new ArrayList<>(); try { Object pemObj; do { pemObj = parser.readObject(); // if public key, use as-is if (pemObj instanceof SubjectPublicKeyInfo) { keys.add(toKeyPair((SubjectPublicKeyInfo) pemObj)); continue; } // if certificate, use the public key which is signed if (pemObj instanceof X509CertificateHolder) { keys.add(toKeyPair((X509CertificateHolder) pemObj)); continue; } // if EC private key given, it arrives here as a keypair if (pemObj instanceof PEMKeyPair) { keys.add(toKeyPair((PEMKeyPair) pemObj)); continue; } // if (RSA) private key given, return it if (pemObj instanceof PrivateKeyInfo) { keys.add(toKeyPair((PrivateKeyInfo) pemObj)); // continue implicitly } } while (pemObj != null); return keys; } catch (Exception e) { throw new JOSEException(e.getMessage(), e); } }
From source file:com.oth.jasds.crypto.Crypto.java
public byte[] decryptFileKey(String filekey, String privateKey) { try {// ww w . ja v a2 s . c o m 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.rovemonteux.silvertunnel.netlib.layer.tor.util.Encryption.java
License:Open Source License
/** * makes RSA private key from PEM string. * * @param s PEM string that contains the key * @return/*ww w . j a va 2s . co m*/ * @see JCERSAPublicKey */ public static RSAKeyPair extractRSAKeyPair(final String s) { RSAKeyPair rsaKeyPair; try { // parse final PEMParser parser = new PEMParser(new StringReader(s)); final Object o = parser.readObject(); parser.close(); // check types if (!(o instanceof PEMKeyPair)) { throw new IOException("Encryption.extractRSAKeyPair: no private key found in string '" + s + "'"); } final PEMKeyPair keyPair = (PEMKeyPair) o; if (keyPair.getPrivateKeyInfo() == null) { throw new IOException( "Encryption.extractRSAKeyPair: no private key found in key pair of string '" + s + "'"); } if (keyPair.getPublicKeyInfo() == null) { throw new IOException( "Encryption.extractRSAKeyPair: no public key found in key pair of string '" + s + "'"); } // convert keys and pack them together into a key pair final RSAPrivateCrtKey privateKey = new TempJCERSAPrivateCrtKey(keyPair.getPrivateKeyInfo()); LOG.debug("JCEPrivateKey={}", privateKey); final RSAPublicKey publicKey = new TempJCERSAPublicKey(keyPair.getPublicKeyInfo()); rsaKeyPair = new RSAKeyPair(publicKey, privateKey); } catch (final Exception e) { LOG.warn("Encryption.extractPrivateRSAKey: Caught exception:" + e.getMessage()); rsaKeyPair = null; } return rsaKeyPair; }
From source file:com.stormpath.spring.cloud.zuul.config.PemResourceKeyResolver.java
License:Apache License
private Key doApply(Resource resource) throws IOException, CertificateException { try (Reader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"))) { PEMParser pemParser = new PEMParser(reader); Object o;/*ww w. ja va 2 s. co m*/ boolean encryptedPrivateFound = false; while ((o = pemParser.readObject()) != null) { if (o instanceof PKCS8EncryptedPrivateKeyInfo) { encryptedPrivateFound = true; } if (o instanceof PEMKeyPair) { PEMKeyPair pemKeyPair = (PEMKeyPair) o; return findPrivate ? pemKeyConverter.getPrivateKey(pemKeyPair.getPrivateKeyInfo()) : pemKeyConverter.getPublicKey(pemKeyPair.getPublicKeyInfo()); } if (o instanceof PrivateKeyInfo && findPrivate) { PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) o; return pemKeyConverter.getPrivateKey(privateKeyInfo); } if (o instanceof SubjectPublicKeyInfo && !findPrivate) { SubjectPublicKeyInfo info = (SubjectPublicKeyInfo) o; return pemKeyConverter.getPublicKey(info); } if (o instanceof X509CertificateHolder && !findPrivate) { X509CertificateHolder holder = (X509CertificateHolder) o; X509Certificate cert = x509Converter.getCertificate(holder); return cert.getPublicKey(); } } //if we haven't returned yet, we couldn't find a key based on our preferences. String msg; if (encryptedPrivateFound && findPrivate) { msg = "Key resource [" + resource + "] contains a PKCS8 Encrypted PrivateKey. Only unencrypted " + "private keys are supported."; } else { msg = "Key resource [" + resource + "] did not contain a " + (findPrivate ? "private " : "public ") + "key."; } throw new IllegalArgumentException(msg); } }
From source file:com.trustly.api.security.KeyChain.java
License:Open Source License
/** * Loads the merchant private key./* w ww. ja va 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:craterdog.security.RsaCertificateManager.java
License:Open Source License
@Override public PrivateKey decodePrivateKey(String pem, char[] password) { logger.entry();/* w w w . j a va 2 s. co 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:de.mendelson.util.security.KeyStoreUtil.java
/** * Tries to read a certificate from a byte array, may return null if reading * the data fails/*from ww w .ja v a 2 s . c o m*/ */ private List<X509Certificate> readCertificates(byte[] data, Provider provider) throws CertificateException { CertificateFactory factory; List<X509Certificate> certList = null; if (provider != null) { factory = CertificateFactory.getInstance("X.509", provider); } else { factory = CertificateFactory.getInstance("X.509"); } try { //try to read p7b files first - all other read methods will ignore certificates if there is stored more than one //cert in the p7b file Collection<? extends Certificate> tempCertList = factory .generateCertPath(new ByteArrayInputStream(data), "PKCS7").getCertificates(); if (tempCertList != null && !tempCertList.isEmpty()) { certList = new ArrayList<X509Certificate>(); for (Certificate cert : tempCertList) { certList.add((X509Certificate) cert); } } } catch (Exception e) { } try { if (certList == null) { factory = CertificateFactory.getInstance("X.509", provider); Collection<? extends Certificate> tempCertList = factory .generateCertificates(new ByteArrayInputStream(data)); if (tempCertList != null && !tempCertList.isEmpty()) { certList = new ArrayList<X509Certificate>(); for (Certificate cert : tempCertList) { certList.add((X509Certificate) cert); } } } } catch (Exception e) { } try { //still no success, perhaps PEM encoding? Start the PEM reader and see if it could read the cert if (certList == null) { PEMParser pemParser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(data))); X509Certificate cert = (X509Certificate) pemParser.readObject(); if (cert != null) { certList = new ArrayList<X509Certificate>(); certList.add(cert); } } } catch (Exception e) { //ignore so far } return (certList); }
From source file:de.mendelson.util.security.KeyStoreUtil.java
/** * Reads a certificate from a stream and returns it * * @deprecated//from w w w . j av a2 s .c o m */ public X509Certificate readCertificate(InputStream certStream, Provider provider) throws CertificateException { CertificateFactory factory; X509Certificate cert = null; try { if (provider != null) { factory = CertificateFactory.getInstance("X.509", provider); cert = (X509Certificate) factory.generateCertificate(certStream); } //Let the default provider parsing the certificate if (provider == null || cert == null) { factory = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) factory.generateCertificate(certStream); } //still no success, perhaps PEM encoding? Start the PEM reader and see if it could read the cert if (cert == null) { PEMParser pemParser = new PEMParser(new InputStreamReader(certStream)); cert = (X509Certificate) pemParser.readObject(); } } catch (Exception e) { throw new CertificateException("Not a certificate or unsupported encoding: " + e.getMessage()); } if (cert != null) { return (cert); } else { throw new CertificateException("Not a certificate or unsupported encoding."); } }
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 w ww. j av a 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 w w w.ja v a 2 s.com*/ * @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 }); }