List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter
public JcaX509CertificateConverter()
From source file:CA.java
License:Apache License
private static Certificate build(ContentSigner sigGen, X500Principal issuer, BigInteger serial, Date notBefore, Date notAfter, X500Principal subject, PublicKey publicKey) throws Exception { X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKey);//ww w . jav a 2s .c om X509CertificateHolder certHolder = certBuilder.build(sigGen); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); Certificate cert = null; cert = converter.getCertificate(certHolder); return cert; }
From source file:ai.susi.SusiServer.java
License:Open Source License
private static void setupHttpServer(int httpPort, int httpsPort) throws Exception { QueuedThreadPool pool = new QueuedThreadPool(); pool.setMaxThreads(500);/* w w w . ja va 2 s .co m*/ SusiServer.server = new Server(pool); SusiServer.server.setStopAtShutdown(true); //http if (!httpsMode.equals(HttpsMode.ONLY)) { HttpConfiguration http_config = new HttpConfiguration(); if (httpsMode.equals(HttpsMode.REDIRECT)) { //redirect http_config.addCustomizer(new SecureRequestCustomizer()); http_config.setSecureScheme("https"); http_config.setSecurePort(httpsPort); } ServerConnector connector = new ServerConnector(SusiServer.server); connector.addConnectionFactory(new HttpConnectionFactory(http_config)); connector.setPort(httpPort); connector.setName("httpd:" + httpPort); connector.setIdleTimeout(20000); // timout in ms when no bytes send / received SusiServer.server.addConnector(connector); } //https //uncommented lines for http2 (jetty 9.3 / java 8) if (httpsMode.isGreaterOrEqualTo(HttpsMode.ON)) { Log.getLog().info("HTTPS activated"); String keySource = DAO.getConfig("https.keysource", "keystore"); KeyStore keyStore; String keystoreManagerPass; //check for key source. Can be a java keystore or in pem format (gets converted automatically) if ("keystore".equals(keySource)) { Log.getLog().info("Loading keystore from disk"); //use native keystore format File keystoreFile = new File(DAO.conf_dir, DAO.getConfig("keystore.name", "keystore.jks")); if (!keystoreFile.exists() || !keystoreFile.isFile() || !keystoreFile.canRead()) { throw new Exception("Could not find keystore"); } keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(keystoreFile.getAbsolutePath()), DAO.getConfig("keystore.password", "").toCharArray()); keystoreManagerPass = DAO.getConfig("keystore.password", ""); } else if ("key-cert".equals(keySource)) { Log.getLog().info("Importing keystore from key/cert files"); //use more common pem format as used by openssl //generate random password char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } String password = keystoreManagerPass = sb.toString(); //get key and cert File keyFile = new File(DAO.getConfig("https.key", "")); if (!keyFile.exists() || !keyFile.isFile() || !keyFile.canRead()) { throw new Exception("Could not find key file"); } File certFile = new File(DAO.getConfig("https.cert", "")); if (!certFile.exists() || !certFile.isFile() || !certFile.canRead()) { throw new Exception("Could not find cert file"); } Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] keyBytes = Files.readAllBytes(keyFile.toPath()); byte[] certBytes = Files.readAllBytes(certFile.toPath()); PEMParser parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(certBytes))); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) parser.readObject()); parser = new PEMParser(new InputStreamReader(new ByteArrayInputStream(keyBytes))); PrivateKey key = new JcaPEMKeyConverter().setProvider("BC") .getPrivateKey((PrivateKeyInfo) parser.readObject()); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert); keyStore.setKeyEntry("defaultKey", key, password.toCharArray(), new Certificate[] { cert }); Log.getLog().info("Successfully imported keystore from key/cert files"); } else { throw new Exception("Invalid option for https.keysource"); } HttpConfiguration https_config = new HttpConfiguration(); https_config.addCustomizer(new SecureRequestCustomizer()); HttpConnectionFactory http1 = new HttpConnectionFactory(https_config); //HTTP2ServerConnectionFactory http2 = new HTTP2ServerConnectionFactory(https_config); //NegotiatingServerConnectionFactory.checkProtocolNegotiationAvailable(); //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); //alpn.setDefaultProtocol(http1.getProtocol()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyManagerPassword(keystoreManagerPass); //sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); //sslContextFactory.setUseCipherSuitesOrder(true); //SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "http/1.1"); //ServerConnector sslConnector = new ServerConnector(LoklakServer.server, ssl, alpn, http2, http1); ServerConnector sslConnector = new ServerConnector(SusiServer.server, ssl, http1); sslConnector.setPort(httpsPort); sslConnector.setName("httpd:" + httpsPort); sslConnector.setIdleTimeout(20000); // timout in ms when no bytes send / received SusiServer.server.addConnector(sslConnector); } }
From source file:at.asitplus.regkassen.core.modules.signature.rawsignatureprovider.NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule.java
License:Apache License
public void intialise() { try {//from ww w . java 2 s . com //create random demonstration ECC keys final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC"); kpg.initialize(256); //256 bit ECDSA key //create a key pair for the demo Certificate Authority final KeyPair caKeyPair = kpg.generateKeyPair(); //create a key pair for the signature certificate, which is going to be used to sign the receipts final KeyPair signingKeyPair = kpg.generateKeyPair(); //get references to private keys for the CA and the signing key final PrivateKey caKey = caKeyPair.getPrivate(); signingKey = signingKeyPair.getPrivate(); //create CA certificate and add it to the certificate chain //NOTE: DO NEVER EVER USE IN A REAL CASHBOX, THIS IS JUST FOR DEMONSTRATION PURPOSES //NOTE: these certificates have random values, just for the demonstration purposes here //However, for testing purposes the most important feature is the EC256 Signing Key, since this is required //by the RK Suite final X509v3CertificateBuilder caBuilder = new X509v3CertificateBuilder(new X500Name("CN=RegKassa ZDA"), BigInteger.valueOf(new SecureRandom().nextLong()), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=RegKassa CA"), SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded())); caBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false)); caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); final X509CertificateHolder caHolder = caBuilder .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey)); final X509Certificate caCertificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(caHolder); certificateChain = new ArrayList<java.security.cert.Certificate>(); certificateChain.add(caCertificate); //create signing cert final long serialNumberCertificate = new SecureRandom().nextLong(); if (!closedSystemSignatureDevice) { serialNumberOrKeyId = Long.toHexString(serialNumberCertificate); } final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name("CN=RegKassa CA"), BigInteger.valueOf(Math.abs(serialNumberCertificate)), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=Signing certificate"), SubjectPublicKeyInfo.getInstance(signingKeyPair.getPublic().getEncoded())); certBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false)); certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); final X509CertificateHolder certHolder = certBuilder .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey)); signingCertificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } catch (final OperatorCreationException e) { e.printStackTrace(); } catch (final CertIOException e) { e.printStackTrace(); } catch (final CertificateException e) { e.printStackTrace(); } }
From source file:ataraxis.crypt.UBERKeyStoreHandlerTest.java
License:Open Source License
public static X509Certificate generateX509V3Cert(KeyPair keyPair) throws Exception { X509v1CertificateBuilder certBldr = new JcaX509v1CertificateBuilder(new X500Name("CN=Root"), BigInteger.valueOf(1), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 1000 * 3600 * 24), new X500Name("CN=Root"), keyPair.getPublic());/*www .jav a2 s . c o m*/ ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC") .build(keyPair.getPrivate()); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); }
From source file:beta01.SimpleGenCert.java
private X509Certificate toX509Certificate(X509CertificateHolder holder) throws CertificateException { JcaX509CertificateConverter conv = new JcaX509CertificateConverter(); conv.setProvider("BC"); X509Certificate cert = conv.getCertificate(holder); return cert;/* ww w. jav a 2s . c om*/ }
From source file:bluecrystal.bcdeps.helper.PkiOps.java
License:Open Source License
public boolean verify(CMSSignedData csd) throws Exception { boolean verified = true; Store certs = csd.getCertificates(); SignerInformationStore signers = csd.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator();//from w w w .java2s .co m while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); SignerId sid = signer.getSID(); Collection certCollection = certs.getMatches(signer.getSID()); if (certCollection.size() > 1) { return false; } Iterator itCert = certCollection.iterator(); X509CertificateHolder signCertHolder = (X509CertificateHolder) itCert.next(); X509Certificate signCert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(signCertHolder); verified = signer.verify(signCert.getPublicKey(), "BC"); if (!verified) { return false; } } return verified; }
From source file:br.gov.jfrj.siga.cd.ac.FachadaDeCertificadosAC.java
License:Open Source License
/** * Monta e ordena uma cadeia de certificados juntamente com os certificados * conhecidos e ncoras confiveis/*w w w.ja va 2 s.c om*/ * * @param certs * cadeia de certificados recebida para a ordenao * @return * @throws Exception */ public static X509Certificate[] montarCadeiaOrdenadaECompleta(Collection<X509CertificateHolder> certs) throws Exception { List<X509Certificate> certsList = new ArrayList<X509Certificate>(); // adiciona os certificados recebidos (parmetro) lista de // certificados for (X509CertificateHolder cert : certs) { // final ByteArrayInputStream bais = new ByteArrayInputStream(cert // .getEncoded()); // final X509Certificate x509 = (X509Certificate) (CertificateFactory // .getInstance("X.509")).generateCertificate(bais); // X509Certificate x509 = new JcaX509CertificateConverter().setProvider("BC").getCertificate(cert); certsList.add(0, x509); } // Acrescenta os certificados faltantes para completar a cadeia // boolean fContinue; do { fContinue = false; for (X509Certificate x509 : certsList) { boolean fFound = false; X500Principal issuer = x509.getIssuerX500Principal(); for (X509Certificate otherX509 : certsList) { if (issuer.equals(otherX509.getSubjectX500Principal())) { fFound = true; break; } } if (!fFound) { for (X509Certificate otherX509 : CertificadoX509ConhecidoEnum.obterCertificados()) { if (issuer.equals(otherX509.getSubjectX500Principal())) { certsList.add(otherX509); fFound = true; fContinue = true; break; } } } if (fContinue) break; if (!fFound) { throw new Exception("No foi possvel montar a cadeia completa de certificao"); } } } while (fContinue); // APARENTEMENTE ISSO EST CORRETO, NO ENTANTO, NO ACROBAT O CARIMBO NO // APARECE. DEVE SER PORQUE EST DANDO ERRO DE VALIDAO POR FALTA DE UM // FLAG "CRICTICAL". int cCerts = certsList.size(); final ArrayList<X509Certificate> certsListSorted = new ArrayList<X509Certificate>(); boolean hasTrustedAnchor = false; for (X509Certificate x509 : certsList) { for (TrustAnchor trustedAnchor : TrustAnchorEnum.obterTrustAnchors()) { if (!hasTrustedAnchor && trustedAnchor.getTrustedCert().equals(x509)) { hasTrustedAnchor = true; certsListSorted.add(trustedAnchor.getTrustedCert()); } } // if (trustedAnchors.contains(x509)) } if (!hasTrustedAnchor) throw new Exception("Cadeia de certificao no est relacionada com a raz da ICP-Brasil"); boolean fExit = false; while (!fExit) { fExit = true; for (X509Certificate x509 : certsList) { if (x509.getIssuerX500Principal().equals(certsListSorted.get(0).getSubjectX500Principal()) && !x509.equals(certsListSorted.get(0))) { certsListSorted.add(0, x509); fExit = false; } } } if (certsListSorted.size() != cCerts) throw new Exception( "Cadeia de certificao no est corretamente encadeada ou no est relacionada com a raz da ICP-Brasil"); // X509Certificate cadeiaTotal[]; final X509Certificate cadeiaTotal[] = new X509Certificate[certsListSorted.size()]; certsListSorted.toArray(cadeiaTotal); return cadeiaTotal; }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
public static X509Certificate getX509Certificate(X509CertificateHolder holder) throws CertificateException { return new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); }
From source file:br.ufpb.dicomflow.integrationAPI.mail.impl.SMTPServiceExtractor.java
License:Open Source License
/** * verify the signature (assuming the cert is contained in the message) *//*from www. j av a2 s. c om*/ private boolean verify(SMIMESigned s) throws Exception { // // extract the information to verify the signatures. // // // certificates and crls passed in the signature - this must happen before // s.getSignerInfos() // Store certs = s.getCertificates(); // // SignerInfo blocks which contain the signatures // SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); // // check each signer // while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509Certificate cert = new JcaX509CertificateConverter() .getCertificate((X509CertificateHolder) certIt.next()); // // verify that the sign is correct and that it was generated // when the certificate was current // if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))) { return true; } else { return false; } } return false; }
From source file:CAModulePackage.CertificateHelper.java
/** * Validates the certificate chain/path. * @param TACerts - Set of Certificates that are the Trust Anchors. * @param certificates - List of certificates in the chain/path. * @return True if the path is valid, False if it's not. *//*from ww w .j ava 2 s. c o m*/ public static boolean validateCertificatePath(Set<X509CertificateHolder> TACerts, ArrayList<X509CertificateHolder> certificates) { Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>(); //Convert all our TA Certificates to normal X509Certificates. for (X509CertificateHolder cert : TACerts) { X509Certificate tempCert = null; try { tempCert = (new JcaX509CertificateConverter()).getCertificate(cert); } catch (CertificateException e) { e.printStackTrace(); } trustAnchors.add(new TrustAnchor(tempCert, null)); } PKIXBuilderParameters params = null; try { params = new PKIXBuilderParameters(trustAnchors, new X509CertSelector()); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } //Build a Certificate Store with the certificates from the chain. JcaCertStoreBuilder builder = new JcaCertStoreBuilder(); for (X509CertificateHolder c : certificates) { System.out.println("---Chain Cert---"); System.out.println("SUBJ: " + c.getSubject().toString()); System.out.println("ISSUER: " + c.getIssuer().toString()); builder.addCertificate(c); } //Add the store to the build parameters try { params.addCertStore(builder.build()); } catch (GeneralSecurityException ex) { Logger.getLogger(CertificateHelper.class.getName()).log(Level.SEVERE, null, ex); } params.setRevocationEnabled(false); //Build the certificate chain - if a result is thrown, we failed. PKIXCertPathBuilderSpi pathBuilder = new PKIXCertPathBuilderSpi(); PKIXCertPathBuilderResult resultPath = null; try { resultPath = (PKIXCertPathBuilderResult) pathBuilder.engineBuild(params); } catch (CertPathBuilderException e) { return false; } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } return true; }