List of usage examples for org.bouncycastle.openssl.jcajce JcaPEMWriter JcaPEMWriter
public JcaPEMWriter(Writer out)
From source file:org.apache.sshd.server.keyprovider.PEMHostKeyProvider.java
License:Apache License
protected void doWriteKeyPair(KeyPair kp, OutputStream os) throws Exception { try (JcaPEMWriter w = new JcaPEMWriter(new OutputStreamWriter(os))) { w.writeObject(kp);//from w ww . j av a 2 s .c o m w.flush(); } }
From source file:org.apache.zookeeper.common.X509TestHelpers.java
License:Apache License
/** * PEM-encodes the given private key (compatible with OpenSSL), optionally protecting it with a password, and * returns the result as a String./*from ww w .j a v a 2 s.co m*/ * @param key the private key. * @param password an optional key password. If empty or null, the private key will not be encrypted. * @return a String containing the PEM encoding of the private key. * @throws IOException if converting the key to PEM format fails. * @throws OperatorCreationException if constructing the encryptor from the given password fails. */ public static String pemEncodePrivateKey(PrivateKey key, String password) throws IOException, OperatorCreationException { StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter); OutputEncryptor encryptor = null; if (password != null && password.length() > 0) { encryptor = new JceOpenSSLPKCS8EncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC) .setProvider(BouncyCastleProvider.PROVIDER_NAME).setRandom(PRNG) .setPasssword(password.toCharArray()).build(); } pemWriter.writeObject(new JcaPKCS8Generator(key, encryptor)); pemWriter.close(); return stringWriter.toString(); }
From source file:org.apache.zookeeper.common.X509TestHelpers.java
License:Apache License
/** * PEM-encodes the given X509 certificate (compatible with OpenSSL) and returns the result as a String. * @param cert the certificate.// w ww . j a v a2 s . c o m * @return a String containing the PEM encoding of the certificate. * @throws IOException if converting the certificate to PEM format fails. */ public static String pemEncodeX509Certificate(X509Certificate cert) throws IOException { StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter); pemWriter.writeObject(cert); pemWriter.close(); return stringWriter.toString(); }
From source file:org.cesecore.keys.util.KeyTools.java
License:Open Source License
/** @return a buffer with the public key in PEM format */ public static String getAsPem(final PublicKey publicKey) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final JcaPEMWriter pemWriter = new JcaPEMWriter(new OutputStreamWriter(baos)); pemWriter.writeObject(publicKey);/*from w w w. j a va 2 s .c om*/ pemWriter.close(); return new String(baos.toByteArray(), "UTF8"); }
From source file:org.curioswitch.common.server.framework.armeria.SslContextKeyConverter.java
License:Open Source License
public static SslContextBuilder execute(InputStream keyCertChainFile, InputStream keyFile, BiFunction<InputStream, InputStream, SslContextBuilder> operation) { final byte[] key; final byte[] keyCertChain; try {/*w w w .j a v a2 s . co m*/ key = ByteStreams.toByteArray(keyFile); keyCertChain = ByteStreams.toByteArray(keyCertChainFile); } catch (IOException e) { throw new UncheckedIOException("Could not read file to bytes.", e); } try { return operation.apply(new ByteArrayInputStream(keyCertChain), new ByteArrayInputStream(key)); } catch (Exception e) { // Try to convert the key to PCKS8. PrivateKey privateKey = KeyUtil.loadPrivateKey(key); final PemObject encoded; try { JcaPKCS8Generator generator = new JcaPKCS8Generator(privateKey, null); encoded = generator.generate(); } catch (PemGenerationException ex) { throw new IllegalStateException("Could not generate PKCS8", ex); } StringWriter sw = new StringWriter(); try (JcaPEMWriter pw = new JcaPEMWriter(sw)) { pw.writeObject(encoded); } catch (IOException ex) { throw new UncheckedIOException("Could not write key to String, can't happen.", ex); } byte[] pkcs8key = sw.toString().getBytes(StandardCharsets.UTF_8); return operation.apply(new ByteArrayInputStream(keyCertChain), new ByteArrayInputStream(pkcs8key)); } }
From source file:org.dcache.gsi.X509DelegationHelper.java
License:Open Source License
private static String pemEncode(Object item) throws IOException { StringWriter writer = new StringWriter(); try (JcaPEMWriter pem = new JcaPEMWriter(writer)) { pem.writeObject(item);//from w w w .j a v a2 s .c o m } return writer.toString(); }
From source file:org.ejbca.ui.cli.keybind.InternalKeyBindingExportCertificateCommand.java
License:Open Source License
@Override public CommandResult executeCommand(Integer internalKeyBindingId, ParameterContainer parameters) throws AuthorizationDeniedException, CertificateImportException { final InternalKeyBindingMgmtSessionRemote internalKeyBindingMgmtSession = EjbRemoteHelper.INSTANCE .getRemoteSession(InternalKeyBindingMgmtSessionRemote.class); final CertificateStoreSessionRemote certStoreSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CertificateStoreSessionRemote.class); final String filename = parameters.get(PEM_FILE_KEY); try {//www . j a v a 2s .com final InternalKeyBindingInfo info = internalKeyBindingMgmtSession.getInternalKeyBindingInfo(getAdmin(), internalKeyBindingId); if (info == null) { getLogger().error("Internal key binding with id " + internalKeyBindingId + " does not exist."); return CommandResult.FUNCTIONAL_FAILURE; } final String fp = info.getCertificateId(); if (fp == null) { getLogger().error("There is no certificate bound to Internal key binding with id " + internalKeyBindingId + "."); return CommandResult.FUNCTIONAL_FAILURE; } final Certificate cert = certStoreSession.findCertificateByFingerprint(fp); if (cert == null) { getLogger().error("Certificate with fingerprint " + fp + " does not exist."); return CommandResult.FUNCTIONAL_FAILURE; } JcaPEMWriter pw = new JcaPEMWriter(new FileWriter(filename)); pw.writeObject(cert); pw.close(); getLogger().info("Operation completed successfully."); return CommandResult.SUCCESS; } catch (IOException e) { throw new IllegalStateException( "Failed to write PEM format certificate to \"" + filename + "\". " + e.getMessage()); } }
From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateTool.java
License:Open Source License
/** * This method handles the deletion of a file in the case of a partial write * @param file the file that is being written to * @param writer writes the contents of the file *//*from w w w .j a va 2s .c o m*/ private static void fullyWriteFile(Path file, Writer writer) throws Exception { boolean success = false; try (OutputStream outputStream = Files.newOutputStream(file, StandardOpenOption.CREATE_NEW); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream, StandardCharsets.UTF_8); JcaPEMWriter pemWriter = new JcaPEMWriter( new OutputStreamWriter(zipOutputStream, StandardCharsets.UTF_8))) { writer.write(zipOutputStream, pemWriter); // set permissions to 600 PosixFileAttributeView view = Files.getFileAttributeView(file, PosixFileAttributeView.class); if (view != null) { view.setPermissions( Sets.newHashSet(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); } success = true; } finally { if (success == false) { Files.deleteIfExists(file); } } }
From source file:org.elasticsearch.xpack.core.ssl.CertificateTool.java
License:Open Source License
/** * This method handles the deletion of a file in the case of a partial write * * @param file the file that is being written to * @param writer writes the contents of the file *///from w w w. j a v a2s . c o m private static void fullyWriteZipFile(Path file, Writer writer) throws Exception { fullyWriteFile(file, outputStream -> { try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream, StandardCharsets.UTF_8); JcaPEMWriter pemWriter = new JcaPEMWriter( new OutputStreamWriter(zipOutputStream, StandardCharsets.UTF_8))) { writer.write(zipOutputStream, pemWriter); } }); }
From source file:org.hyperledger.fabric.sdk.security.certgen.TLSCertificateKeyPair.java
License:Open Source License
/*** * Creates a TLSCertificateKeyPair out of the given {@link X509Certificate} and {@link KeyPair} * encoded in PEM and also in DER for the certificate * @param x509Cert the certificate to process * @param keyPair the key pair to process * @return a TLSCertificateKeyPair/*from w w w .jav a 2 s. c o m*/ * @throws IOException upon failure */ static TLSCertificateKeyPair fromX509CertKeyPair(X509Certificate x509Cert, KeyPair keyPair) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); JcaPEMWriter w = new JcaPEMWriter(writer); w.writeObject(x509Cert); w.flush(); w.close(); byte[] pemBytes = baos.toByteArray(); InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(pemBytes)); PemReader pr = new PemReader(isr); PemObject pem = pr.readPemObject(); byte[] derBytes = pem.getContent(); baos = new ByteArrayOutputStream(); PrintWriter wr = new PrintWriter(baos); wr.println("-----BEGIN PRIVATE KEY-----"); wr.println(new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()))); wr.println("-----END PRIVATE KEY-----"); wr.flush(); wr.close(); byte[] keyBytes = baos.toByteArray(); return new TLSCertificateKeyPair(pemBytes, derBytes, keyBytes); }