Search in sources :

Example 1 with PEMWriter

use of org.bouncycastle.openssl.PEMWriter in project webofneeds by researchstudio-sat.

the class TestSigningUtils method printCerificate.

private void printCerificate(final KeyStoreService storeService, final String keyName, final String certUri) throws IOException, CertificateException {
    System.out.println(keyName);
    System.out.println(certUri);
    X509Certificate cert = (X509Certificate) storeService.getCertificate(keyName);
    StringWriter sw = new StringWriter();
    PEMWriter writer = new PEMWriter(sw);
    writer.writeObject(cert);
    writer.close();
    System.out.println(sw.toString());
    PEMParser pemParser = new PEMParser(new StringReader(sw.toString()));
    X509CertificateHolder certHolder = (X509CertificateHolder) pemParser.readObject();
    X509Certificate certRead = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
    System.out.println(certRead.toString());
}
Also used : PEMParser(org.bouncycastle.openssl.PEMParser) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) PEMWriter(org.bouncycastle.openssl.PEMWriter) X509Certificate(java.security.cert.X509Certificate)

Example 2 with PEMWriter

use of org.bouncycastle.openssl.PEMWriter in project oxTrust by GluuFederation.

the class TrustRelationshipWebService method generateCertForGeneratedSP.

/**
 * @return certificate for generated SP
 * @throws IOException
 * @throws CertificateEncodingException
 */
public String generateCertForGeneratedSP(GluuSAMLTrustRelationship trustRelationship) throws IOException {
    X509Certificate cert = null;
    // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    try {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGen.initialize(2048);
        KeyPair pair = keyPairGen.generateKeyPair();
        StringWriter keyWriter = new StringWriter();
        PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
        pemFormatWriter.writeObject(pair.getPrivate());
        pemFormatWriter.close();
        String url = trustRelationship.getUrl().replaceFirst(".*//", "");
        X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
        cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
        org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
        byte[] derCert = cert.getEncoded();
        String pemCertPre = new String(encoder.encode(derCert));
        logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
        logger.debug(pemCertPre);
        logger.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
        shibboleth3ConfService.saveCert(trustRelationship, pemCertPre);
        shibboleth3ConfService.saveKey(trustRelationship, keyWriter.toString());
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Failed to generate certificate", e);
    }
    // String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
    // + "-shib.crt";
    // File certFile = new File(certName);
    // if (certFile.exists()) {
    // cert = SSLService.instance().getPEMCertificate(certName);
    // }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
            logger.info("##### certificate = " + certificate);
        } catch (CertificateEncodingException e) {
            certificate = null;
            // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
            logger.error("Failed to encode certificate to DER", e);
        }
    } else {
    // facesMessages.add(FacesMessage.SEVERITY_ERROR, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }
    return certificate;
}
Also used : KeyPair(java.security.KeyPair) Base64(org.bouncycastle.util.encoders.Base64) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) PEMWriter(org.bouncycastle.openssl.PEMWriter) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) CertificateEncodingException(java.security.cert.CertificateEncodingException) BaseMappingException(org.gluu.persist.exception.mapping.BaseMappingException) IOException(java.io.IOException) StringWriter(java.io.StringWriter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 3 with PEMWriter

use of org.bouncycastle.openssl.PEMWriter in project Gatekeeper by FINRAOS.

the class KeypairService method getPEM.

public String getPEM(PrivateKey privKey) {
    StringWriter stringWriter = new StringWriter();
    PEMWriter pemWriter = new PEMWriter(stringWriter);
    try {
        pemWriter.writeObject(privKey);
        pemWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String privKeyString = stringWriter.toString();
    return privKeyString;
}
Also used : StringWriter(java.io.StringWriter) PEMWriter(org.bouncycastle.openssl.PEMWriter) IOException(java.io.IOException)

Example 4 with PEMWriter

use of org.bouncycastle.openssl.PEMWriter in project gitblit by gitblit.

the class X509Utils method saveCertificate.

/**
 * Saves the certificate to the file system.  If the destination filename
 * ends with the pem extension, the certificate is written in the PEM format,
 * otherwise the certificate is written in the DER format.
 *
 * @param cert
 * @param targetFile
 */
public static void saveCertificate(X509Certificate cert, File targetFile) {
    File folder = targetFile.getAbsoluteFile().getParentFile();
    if (!folder.exists()) {
        folder.mkdirs();
    }
    File tmpFile = new File(folder, Long.toHexString(System.currentTimeMillis()) + ".tmp");
    try {
        boolean asPem = targetFile.getName().toLowerCase().endsWith(".pem");
        if (asPem) {
            // PEM encoded X509
            PEMWriter pemWriter = null;
            try {
                pemWriter = new PEMWriter(new FileWriter(tmpFile));
                pemWriter.writeObject(cert);
                pemWriter.flush();
            } finally {
                if (pemWriter != null) {
                    pemWriter.close();
                }
            }
        } else {
            // DER encoded X509
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(tmpFile);
                fos.write(cert.getEncoded());
                fos.flush();
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }
        // rename tmp file to target
        if (targetFile.exists()) {
            targetFile.delete();
        }
        tmpFile.renameTo(targetFile);
    } catch (Exception e) {
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
        throw new RuntimeException("Failed to save certificate " + cert.getSubjectX500Principal().getName(), e);
    }
}
Also used : FileWriter(java.io.FileWriter) FileOutputStream(java.io.FileOutputStream) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) PEMWriter(org.bouncycastle.openssl.PEMWriter) File(java.io.File) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException)

Example 5 with PEMWriter

use of org.bouncycastle.openssl.PEMWriter in project mica2 by obiba.

the class KeyStoreService method getPEMCertificate.

@NotNull
public String getPEMCertificate(@NotNull String name, String alias) throws KeyStoreException, IOException {
    Certificate[] certificates = getKeyStore(name).getKeyStore().getCertificateChain(alias);
    if (certificates == null || certificates.length == 0)
        throw new IllegalArgumentException("Cannot find certificate for alias: " + alias);
    StringWriter writer = new StringWriter();
    PEMWriter pemWriter = new PEMWriter(writer);
    for (Certificate certificate : certificates) {
        pemWriter.writeObject(certificate);
    }
    pemWriter.flush();
    return writer.getBuffer().toString();
}
Also used : StringWriter(java.io.StringWriter) PEMWriter(org.bouncycastle.openssl.PEMWriter) Certificate(java.security.cert.Certificate) NotNull(javax.validation.constraints.NotNull)

Aggregations

PEMWriter (org.bouncycastle.openssl.PEMWriter)16 StringWriter (java.io.StringWriter)8 IOException (java.io.IOException)7 X509Certificate (java.security.cert.X509Certificate)4 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 FileWriter (java.io.FileWriter)2 OutputStreamWriter (java.io.OutputStreamWriter)2 KeyPair (java.security.KeyPair)2 KeyPairGenerator (java.security.KeyPairGenerator)2 SecureRandom (java.security.SecureRandom)2 CertificateEncodingException (java.security.cert.CertificateEncodingException)2 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)2 FileTransferException (com.axway.ats.common.filetransfer.FileTransferException)1 JSchException (com.jcraft.jsch.JSchException)1 SftpException (com.jcraft.jsch.SftpException)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 Writer (java.io.Writer)1 InvalidKeyException (java.security.InvalidKeyException)1