List of usage examples for org.bouncycastle.openssl.jcajce JcaPEMKeyConverter getPrivateKey
public PrivateKey getPrivateKey(PrivateKeyInfo privateKeyInfo) throws PEMException
From source file:co.lqnt.lockbox.key.PrivateKey.java
License:Open Source License
/** * Get the JCE private key./*from w w w. j a v a2 s . co m*/ * * @param keyConverter The key converter to use. * * @return The JCE private key. */ public java.security.PrivateKey jcePrivateKey(final JcaPEMKeyConverter keyConverter) { java.security.PrivateKey jcePrivateKey; try { jcePrivateKey = keyConverter.getPrivateKey(this.bcPrivateKeyInfo()); } catch (PEMException e) { throw new RuntimeException(e); } return jcePrivateKey; }
From source file:com.google.examples.JOSEToolBase.java
License:Apache License
public static PrivateKey decodePrivateKey(String privateKeyString, String password) throws KeyParseException { try {/* ww w . ja v a 2s. c om*/ JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); privateKeyString = reformIndents(privateKeyString); PEMParser pemParser = new PEMParser(new StringReader(privateKeyString)); Object object = pemParser.readObject(); if (object == null) { throw new KeyParseException("unable to read anything when decoding private key"); } KeyPair kp = null; //LOGGER.info(String.format("decodePrivateKey, %s", object.getClass().getName())); if (object instanceof PKCS8EncryptedPrivateKeyInfo) { // produced by "openssl genpkey" or the series of commands reqd to sign an ec key //LOGGER.info("decodePrivateKey, encrypted PrivateKeyInfo"); PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object; JceOpenSSLPKCS8DecryptorProviderBuilder decryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder(); InputDecryptorProvider decryptorProvider = decryptorProviderBuilder.build(password.toCharArray()); PrivateKeyInfo privateKeyInfo = pkcs8EncryptedPrivateKeyInfo .decryptPrivateKeyInfo(decryptorProvider); return (PrivateKey) converter.getPrivateKey(privateKeyInfo); } if (object instanceof PrivateKeyInfo) { // produced by openssl genpkey without encryption return (PrivateKey) converter.getPrivateKey((PrivateKeyInfo) object); } if (object instanceof PEMEncryptedKeyPair) { // produced by "openssl genrsa" or "openssl ec -genkey" // LOGGER.info("decodePrivateKey, encrypted keypair"); PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) object; PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder() .build(password.toCharArray()); kp = converter.getKeyPair(encryptedKeyPair.decryptKeyPair(decryptorProvider)); } else if (object instanceof PEMKeyPair) { //LOGGER.info("decodePrivateKey, un-encrypted keypair"); PEMKeyPair unencryptedKeyPair = (PEMKeyPair) object; kp = converter.getKeyPair(unencryptedKeyPair); } else { //LOGGER.error("decodePrivateKey, unknown object type {}", object.getClass().getName()); throw new KeyParseException("unknown object type when decoding private key"); } return (PrivateKey) kp.getPrivate(); } catch (KeyParseException exc0) { throw exc0; } catch (Exception exc1) { throw new KeyParseException("cannot instantiate private key", exc1); } }
From source file:com.hypersocket.certs.X509CertificateUtils.java
License:Open Source License
public static KeyPair loadKeyPairFromPEM(InputStream keyfile, char[] passphrase) throws InvalidPassphraseException, CertificateException, FileFormatException { PEMParser parser = new PEMParser(new InputStreamReader(keyfile)); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); try {/*from w w w .j av a2 s . c om*/ Object privatekey = parser.readObject(); if (privatekey instanceof PEMEncryptedKeyPair) { try { privatekey = ((PEMEncryptedKeyPair) privatekey) .decryptKeyPair(new JcePEMDecryptorProviderBuilder().build(passphrase)); } catch (Exception e) { throw new InvalidPassphraseException(e); } } else if (privatekey instanceof PKCS8EncryptedPrivateKeyInfo) { try { privatekey = converter .getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) privatekey).decryptPrivateKeyInfo( new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase))); } catch (Exception e) { throw new InvalidPassphraseException(e); } } if (privatekey instanceof PEMKeyPair) { return loadKeyPair((PEMKeyPair) privatekey); } else if (privatekey instanceof RSAPrivateCrtKey) { return loadKeyPair((RSAPrivateCrtKey) privatekey); } else if (privatekey instanceof PrivateKeyInfo) { PrivateKeyInfo i = (PrivateKeyInfo) privatekey; PrivateKey prv = converter.getPrivateKey(i); if (prv instanceof RSAPrivateCrtKey) { return loadKeyPair((RSAPrivateCrtKey) prv); } else { throw new FileFormatException("Unsupported private key type"); } } else { throw new FileFormatException( "The file doesn't seem to have any supported key types obj=" + privatekey); } } catch (IOException ex) { throw new CertificateException("Failed to read from key file", ex); } finally { try { parser.close(); } catch (IOException e) { } } }
From source file:com.jcs_java_sdk.Utils.java
License:Open Source License
public static PrivateKey readPrivateKey(String privateKeyPath, String keyPassword) throws IOException { FileReader fileReader = new FileReader(privateKeyPath); PEMParser keyReader = new PEMParser(fileReader); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(keyPassword.toCharArray()); Object keyPair = keyReader.readObject(); PrivateKeyInfo keyInfo;/*from ww w.j a va 2s . com*/ if (keyPair instanceof PEMEncryptedKeyPair) { PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProv); keyInfo = decryptedKeyPair.getPrivateKeyInfo(); } else { keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo(); } keyReader.close(); return converter.getPrivateKey(keyInfo); }
From source file:com.liferay.sync.engine.lan.util.LanPEMParserUtil.java
License:Open Source License
public static PrivateKey parsePrivateKey(String privateKey) throws Exception { StringBuilder sb = new StringBuilder(); sb.append("-----BEGIN PRIVATE KEY-----\n"); sb.append(privateKey);/* www . j a v a 2 s .c o m*/ if (!privateKey.endsWith("\n")) { sb.append("\n"); } sb.append("-----END PRIVATE KEY-----"); PEMParser pemParser = new PEMParser(new StringReader(sb.toString())); JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter(); return jcaPEMKeyConverter.getPrivateKey((PrivateKeyInfo) pemParser.readObject()); }
From source file:com.oath.auth.Utils.java
License:Apache License
/** * @param athenzPublicCert the location on the public certificate file * @param athenzPrivateKey the location of the private key file * @return a KeyStore with loaded key and certificate * @throws Exception KeyStore generation can throw Exception for many reasons *//* w w w . jav a 2s . co m*/ public static KeyStore createKeyStore(final String athenzPublicCert, final String athenzPrivateKey) throws Exception { X509Certificate certificate; PrivateKey privateKey = null; KeyStore keyStore = null; File certFile = null; File keyFile = null; try { if (Paths.get(athenzPublicCert).isAbsolute() && Paths.get(athenzPrivateKey).isAbsolute()) { certFile = new File(athenzPublicCert); keyFile = new File(athenzPrivateKey); long startTime = System.currentTimeMillis(); while (!certFile.exists() || !keyFile.exists()) { long durationInMillis = System.currentTimeMillis() - startTime; if (durationInMillis > KEY_WAIT_TIME_MILLIS) { throw new RuntimeException("Keyfresher waited " + durationInMillis + " ms for valid public or private key files. Giving up."); } LOG.error("Missing Athenz public certificate or private key files. Waiting {} ms", durationInMillis); Thread.sleep(1000); } } else { certFile = new File(Resources.getResource(athenzPublicCert).getFile()); keyFile = new File(Resources.getResource(athenzPrivateKey).getFile()); } } catch (Throwable t) { throw new IllegalArgumentException(t); } try (InputStream publicCertStream = new FileInputStream(certFile); InputStream privateKeyStream = new FileInputStream(keyFile); PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); Object key = pemParser.readObject(); if (key instanceof PEMKeyPair) { PrivateKeyInfo pKeyInfo = ((PEMKeyPair) key).getPrivateKeyInfo(); privateKey = pemConverter.getPrivateKey(pKeyInfo); } else if (key instanceof PrivateKeyInfo) { privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) key); } else { throw new IllegalStateException("Unknown object type: " + key.getClass().getName()); } certificate = (X509Certificate) cf.generateCertificate(publicCertStream); keyStore = KeyStore.getInstance("JKS"); String alias = certificate.getSubjectX500Principal().getName(); keyStore.load(null); keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD, new X509Certificate[] { certificate }); } catch (IOException e) { throw new IllegalArgumentException(e); } return keyStore; }
From source file:com.oth.jasds.crypto.Crypto.java
public byte[] decryptFileKey(String filekey, String privateKey) { try {//from ww w . jav a 2s . co 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.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 w w w .ja v a 2 s . co 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: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 .ja v a 2 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, 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 . 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 }); }