List of usage examples for org.bouncycastle.openssl.jcajce JcaPEMKeyConverter JcaPEMKeyConverter
JcaPEMKeyConverter
From source file:edu.wisc.doit.tcrypt.KeyReadingAndWritingTest.java
License:Apache License
@Test public void testCreateWriteAndReadBackKey() throws Exception { // Create ServiceKey final KeyPair kp = this.keysKeeper.createServiceKey("example.com", 2048, "username"); assertNotNull(kp);//from w w w.j av a 2 s . co m // Step 3: Read ServiceKey from filesystem ServiceKey foundKey = keysKeeper.getServiceKey("example.com"); assertNotNull(foundKey); // Compare original ServiceKey content with new ServiceKey read from filesystem assertEquals("example.com", foundKey.getServiceName()); assertEquals("username", foundKey.getCreatedByNetId()); assertEquals(2048, foundKey.getKeyLength()); //Verify created in same minute assertEquals(DateTime.now().minuteOfHour().roundFloorCopy(), foundKey.getDayCreated().minuteOfHour().roundFloorCopy()); assertNotNull(foundKey.getFileEncrypter()); assertNotNull(foundKey.getTokenEncrypter()); final File keyFile = foundKey.getKeyFile(); assertNotNull(keyFile); @SuppressWarnings("resource") PEMParser pemParser = new PEMParser(new FileReader(keyFile)); Object object = pemParser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); final PublicKey actualPublicKey = converter.getPublicKey((SubjectPublicKeyInfo) object); assertArrayEquals(kp.getPublic().getEncoded(), actualPublicKey.getEncoded()); }
From source file:esteidhacker.FakeEstEID.java
License:Open Source License
public void send_key_pem(File f, int num) throws Exception { PEMParser pem = new PEMParser(new InputStreamReader(new FileInputStream(f))); // OpenSSL genrsa makes a key pair. Object o = pem.readObject();// w w w . j a va 2s .co m RSAPrivateCrtKey key; if (o instanceof org.bouncycastle.openssl.PEMKeyPair) { PEMKeyPair pair = (PEMKeyPair) o; JcaPEMKeyConverter convert = new JcaPEMKeyConverter(); key = (RSAPrivateCrtKey) convert.getPrivateKey(pair.getPrivateKeyInfo()); } else { key = (RSAPrivateCrtKey) pem.readObject(); } pem.close(); send_key(key, num); }
From source file:google.registry.testing.sftp.TestSftpServer.java
License:Open Source License
@Nullable private static KeyPair createKeyPair(String key) { try (PEMParser pemParser = new PEMParser(new StringReader(key))) { PEMKeyPair pemPair = (PEMKeyPair) pemParser.readObject(); KeyPair result = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemPair); logger.info("Read key pair " + result); return result; } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't read key pair from string(!)", e); return null; }/*from w w w . ja v a 2 s . co m*/ }
From source file:io.smartspaces.util.net.SslUtils.java
License:Apache License
/** * Get an SSL socket factory that provides a client certificate for the socket * connections./*from w ww .j a va 2 s . c o m*/ * * @param caCrtFile * file path to the certificate authority certificate * @param clientCrtFile * file path to the certificate for the client * @param clientKeyFile * file path to the private key for the client * * @return the socket factory providing the client functionality * * @throws Exception */ public static SSLSocketFactory configureSSLSocketFactory(String caCrtFile, String clientCrtFile, String clientKeyFile) throws Exception { Security.addProvider(new BouncyCastleProvider()); JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter() .setProvider(SECURITY_PROVIDER_BOUNCY_CASTLE); // load CA certificate PEMParser reader = new PEMParser( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))))); X509Certificate caCert = certificateConverter.getCertificate((X509CertificateHolder) reader.readObject()); reader.close(); // load client certificate reader = new PEMParser( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(clientCrtFile))))); X509Certificate cert = certificateConverter.getCertificate((X509CertificateHolder) reader.readObject()); reader.close(); // load client private key JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider(SECURITY_PROVIDER_BOUNCY_CASTLE); reader = new PEMParser( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(clientKeyFile))))); KeyPair key = keyConverter.getKeyPair((PEMKeyPair) reader.readObject()); reader.close(); // CA certificate is used to authenticate server KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType()); caKs.load(null, null); caKs.setCertificateEntry("ca-certificate", caCert); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(caKs); // client key and certificates are sent to server so it can authenticate // the client.F KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("certificate", cert); // This assumes that the client key is not password protected. We need a // password, but it could be anything. char[] password = VIRTUAL_KEYSTORE_PASSWORD.toCharArray(); ks.setKeyEntry("private-key", key.getPrivate(), password, new java.security.cert.Certificate[] { cert }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password); // finally, create SSL socket factory. SSLContext context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:it.zero11.acme.utils.X509Utils.java
License:Apache License
public static KeyPair loadPEMKeyPair(InputStream privateKeyInputStream) throws IOException { try (PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyInputStream))) { PEMKeyPair keyPair = (PEMKeyPair) pemParser.readObject(); return new JcaPEMKeyConverter().getKeyPair(keyPair); }// ww w. ja va 2 s . c om }
From source file:jenkins.bouncycastle.api.PEMEncodable.java
License:Open Source License
/** * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String} * //ww w . j a v a2 s .c o m * @param pem {@link String} with the PEM data * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with * <code>Arrays.fill(passphrase, (char)0)</code> * @return {@link PEMEncodable} object * @throws IOException launched if a problem exists reading the PEM information * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided */ @Nonnull public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase) throws IOException, UnrecoverableKeyException { try (PEMParser parser = new PEMParser(new StringReader(pem));) { Object object = parser.readObject(); JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC"); // handle supported PEM formats. if (object instanceof PEMEncryptedKeyPair) { if (passphrase != null) { PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase); PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object; return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { if (passphrase != null) { InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase); PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object; return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PEMKeyPair) { return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object)); } else if (object instanceof PrivateKeyInfo) { PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object); // JENKINS-35661 in this case we know how to get the public key too if (pk instanceof RSAPrivateCrtKey) { // obtain public key spec from the private key RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk; RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(), rsaPK.getPublicExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK)); } return new PEMEncodable(pk); } else if (object instanceof SubjectPublicKeyInfo) { return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object)); } else if (object instanceof X509CertificateHolder) { JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC"); return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object)); } else { throw new IOException( "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received " + object.getClass().getName()); } } catch (OperatorCreationException e) { throw new IOException(e.getMessage(), e); } catch (PKCSException | InvalidKeySpecException e) { LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e); throw new UnrecoverableKeyException(); } catch (CertificateException e) { throw new IOException("Could not read certificate", e); } catch (NoSuchAlgorithmException e) { throw new AssertionError( "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html"); } }
From source file:net.adamcin.httpsig.ssh.bc.PEMUtil.java
License:Open Source License
/** * Read a single PEM-formatted key//from w ww . ja va2 s . com * @param is * @param passphrase * @return * @throws IOException */ public static Key readKey(InputStream is, final char[] passphrase) throws IOException { JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); PEMParser parser = null; KeyPair keyPair = null; try { parser = new PEMParser(new InputStreamReader(is)); Object o = parser.readObject(); if (o instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair _encPair = (PEMEncryptedKeyPair) o; PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(passphrase); keyPair = converter.getKeyPair(_encPair.decryptKeyPair(decryptionProv)); } else if (o instanceof PEMKeyPair) { keyPair = converter.getKeyPair((PEMKeyPair) o); } if (keyPair != null) { if (keyPair.getPrivate() instanceof RSAPrivateKey || keyPair.getPublic() instanceof RSAPublicKey) { return new SSHKey(KeyFormat.SSH_RSA, keyPair); } else if (keyPair.getPrivate() instanceof DSAPrivateKey || keyPair.getPublic() instanceof DSAPublicKey) { return new SSHKey(KeyFormat.SSH_DSS, keyPair); } } return null; } finally { if (parser != null) { try { parser.close(); } catch (IOException ignored) { } } } }
From source file:net.adamcin.httpsig.testutil.KeyTestUtil.java
License:Open Source License
public static KeyPair getPrivateKeyAsKeyPair(String parentName, String keyName, final String passphrase) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); File privateKeyFile = getPrivateKeyAsFile(parentName, keyName); InputStream is = null;//from ww w.j ava2 s . co m PEMParser parser = null; try { is = new FileInputStream(privateKeyFile); parser = new PEMParser(new InputStreamReader(is)); Object o = parser.readObject(); if (o instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair _encPair = (PEMEncryptedKeyPair) o; PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder() .build(passphrase.toCharArray()); return converter.getKeyPair(_encPair.decryptKeyPair(decryptionProv)); } else if (o instanceof PEMKeyPair) { return converter.getKeyPair((PEMKeyPair) o); } } catch (Exception e) { LOGGER.error("failed to parse private key file: parent=" + parentName + " keyName=" + keyName, e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(parser); } return null; }
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 w ww .j av a 2 s. 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();/* w ww . j ava2s . co m*/ PEMKeyPair pemPair = (PEMKeyPair) keyObject; KeyPair pair = new JcaPEMKeyConverter().getKeyPair(pemPair); return pair; }