List of usage examples for java.security.cert CertStore getInstance
public static CertStore getInstance(String type, CertStoreParameters params, Provider provider) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException
From source file:createSod.java
/** * @param args/*from w ww. j a v a 2 s. c o m*/ * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:mitm.common.security.certpath.CertPathBuilderSpeedTest.java
@BeforeClass public static void setUpBeforeClass() throws Exception { PropertyConfigurator.configure("conf/log4j.properties"); InitializeBouncycastle.initialize(); sessionSource = new StandardHibernateSessionSourceImpl(hibernateConfig); sessionManager = new SessionManagerImpl(sessionSource); MITMProvider.initialize(sessionManager); certStoreParams = new X509CertStoreParameters( new X509CertStoreExtAutoCommitFactory(sessionSource, "certificates").create(), new X509CRLStoreExtAutoCommitFactory(sessionSource, "certificates").create()); certStore = CertStore.getInstance(MITMProvider.DATABASE_CERTSTORE, certStoreParams, "mitm"); rootStoreParams = new X509CertStoreParameters( new X509CertStoreExtAutoCommitFactory(sessionSource, "roots").create()); }
From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java
@Override public void afterPropertiesSet() throws Exception { if (this.keystore == null) { this.logger.warn("No S/MIME KeyStore configured. Email update notifications will NOT be signed"); } else {//from www . j a v a 2s . com Security.addProvider(new BouncyCastleProvider()); final KeyStore signingKeyStore = KeyStore.getInstance("JKS"); final InputStream keyStoreStream = this.keystore.getInputStream(); try { signingKeyStore.load(keyStoreStream, this.keystorePassword.toCharArray()); } finally { IOUtils.closeQuietly(keyStoreStream); } final List<Certificate> certList = new ArrayList<Certificate>(1); for (final Enumeration<String> aliasesEnum = signingKeyStore.aliases(); aliasesEnum .hasMoreElements();) { final String alias = aliasesEnum.nextElement(); final Certificate cert = signingKeyStore.getCertificate(alias); if (cert != null) { certList.add(cert); } } final PrivateKey signingKey = (PrivateKey) signingKeyStore.getKey(this.certificateAlias, this.keystorePassword.toCharArray()); final X509Certificate signingCert = (X509Certificate) signingKeyStore .getCertificate(this.certificateAlias); // create a CertStore containing the certificates we want carried // in the signature final CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); // create the generator for creating an smime/signed message smimeSignedGenerator = new SMIMESignedGenerator(); // add a signer to the generator - this specifies we are using SHA1 and // adding the smime attributes above to the signed attributes that // will be generated as part of the signature. The encryption algorithm // used is taken from the key - in this RSA with PKCS1Padding smimeSignedGenerator.addSigner(signingKey, signingCert, SMIMESignedGenerator.DIGEST_SHA1); // add our pool of certs and cerls (if any) to go with the signature smimeSignedGenerator.addCertificatesAndCRLs(certsAndcrls); } }
From source file:mitm.common.security.certpath.CertPathBuilderTest.java
@BeforeClass public static void setUpBeforeClass() throws Exception { PropertyConfigurator.configure("conf/log4j.properties"); InitializeBouncycastle.initialize(); sessionSource = new StandardHibernateSessionSourceImpl(hibernateConfig); sessionManager = new SessionManagerImpl(sessionSource); MITMProvider.initialize(sessionManager); certStoreParams = new X509CertStoreParameters( new X509CertStoreExtAutoCommitFactory(sessionSource, "certificates").create(), new X509CRLStoreExtAutoCommitFactory(sessionSource, "certificates").create()); certStore = CertStore.getInstance(MITMProvider.DATABASE_CERTSTORE, certStoreParams, "mitm"); rootStoreParams = new X509CertStoreParameters( new X509CertStoreExtAutoCommitFactory(sessionSource, "roots").create()); rootStore = CertStore.getInstance(MITMProvider.DATABASE_CERTSTORE, rootStoreParams, "mitm"); }
From source file:mitm.common.security.crl.PKITSTest.java
@BeforeClass public static void setUpBeforeClass() throws Exception { PropertyConfigurator.configure("conf/log4j.properties"); InitializeBouncycastle.initialize(); sessionSource = new StandardHibernateSessionSourceImpl(hibernateConfig); SessionManager sessionManager = new SessionManagerImpl(sessionSource); MITMProvider.initialize(sessionManager); certStoreParams = new X509CertStoreParameters( new X509CertStoreExtAutoCommitFactory(sessionSource, "certificates").create(), new X509CRLStoreExtAutoCommitFactory(sessionSource, "certificates").create()); certStore = CertStore.getInstance(MITMProvider.DATABASE_CERTSTORE, certStoreParams, "mitm"); rootStoreParams = new X509CertStoreParameters( new X509CertStoreExtAutoCommitFactory(sessionSource, "roots").create()); trustAnchorBuilder = new CertStoreTrustAnchorBuilder(rootStoreParams.getCertStore(), 0 /* seconds */); testDate = TestUtils.parseDate("01-Dec-2007 16:38:35 GMT"); }
From source file:org.apache.synapse.transport.certificatevalidation.pathvalidation.CertificatePathValidator.java
/** * Certificate Path Validation process/*from ww w. ja va 2s. c o m*/ * * @throws CertificateVerificationException * if validation process fails. */ public void validatePath() throws CertificateVerificationException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain); try { CertStore store = CertStore.getInstance("Collection", params, "BC"); // create certificate path CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath certPath = fact.generateCertPath(certChain); TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null); Set<TrustAnchor> trust = Collections.singleton(trustAnchor); // perform validation CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertPathChecker(pathChecker); param.setRevocationEnabled(false); param.addCertStore(store); param.setDate(new Date()); validator.validate(certPath, param); log.info("Certificate path validated"); } catch (CertPathValidatorException e) { throw new CertificateVerificationException("Certificate Path Validation failed on certificate number " + e.getIndex() + ", details: " + e.getMessage(), e); } catch (Exception e) { throw new CertificateVerificationException("Certificate Path Validation failed", e); } }
From source file:org.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java
/** * Certificate Path Validation process// www. java 2 s . c om * * @throws CertificateVerificationException * if validation process fails. */ public void validatePath() throws CertificateVerificationException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain); try { CertStore store = CertStore.getInstance("Collection", params, "BC"); // create certificate path CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath certPath = fact.generateCertPath(certChain); TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null); Set<TrustAnchor> trust = Collections.singleton(trustAnchor); // perform validation CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertPathChecker(pathChecker); param.setRevocationEnabled(false); param.addCertStore(store); param.setDate(new Date()); validator.validate(certPath, param); log.debug("Certificate path validated"); } catch (CertPathValidatorException e) { throw new CertificateVerificationException("Certificate Path Validation failed on " + "certificate number " + e.getIndex() + ", details: " + e.getMessage(), e); } catch (Exception e) { throw new CertificateVerificationException("Certificate Path Validation failed", e); } }
From source file:org.ejbca.extra.db.ExtRAMsgHelper.java
/** * Method that signes the given data using the algorithm specified in the init method. * //from w w w . j av a 2 s. c om * @param signKey, the key used to sign the data * @param signCert the certificate * @param data * @return the signed data or null if signature failed */ public static byte[] signData(PrivateKey signKey, X509Certificate signCert, byte[] data) { byte[] retdata = null; try { ArrayList certList = new ArrayList(); certList.add(signCert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), provider); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificatesAndCRLs(certs); gen.addSigner(signKey, signCert, signAlg); CMSSignedData signedData = gen.generate(new CMSProcessableByteArray(data), true, provider); retdata = signedData.getEncoded(); } catch (Exception e) { log.error("Error signing data : ", e); } return retdata; }
From source file:org.ejbca.extra.ra.ScepRAServlet.java
private byte[] createPKCS7(Certificate[] chain, PrivateKey pk, X509Certificate cert) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CMSException, IOException { Collection<Certificate> certList = Arrays.asList(chain); CMSProcessable msg = new CMSProcessableByteArray(new byte[0]); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificatesAndCRLs(certs);/* w ww .j a v a 2 s . c om*/ // it is possible to sign the pkcs7, but it's not currently used CMSSignedData s = null; if ((pk != null) && (cert != null)) { gen.addSigner(pk, cert, CMSSignedDataGenerator.DIGEST_MD5); s = gen.generate(msg, true, "BC"); } else { s = gen.generate(msg, "BC"); } return s.getEncoded(); }
From source file:org.globus.gsi.proxy.ProxyPathValidator.java
/** * Performs certificate path validation. Does <B>not</B> check * the cert signatures but it performs all other checks like * the extension checking, validity checking, restricted policy * checking, CRL checking, etc./*from ww w. j ava 2 s . c om*/ * * @param certPath the certificate path to validate. * @param trustedCerts the trusted (CA) certificates. If null, * the default trusted certificates will be used. * @param crlsList the certificate revocation list. If null, * the default certificate revocation list will be used. * @exception ProxyPathValidatorException if certificate * path validation fails. */ protected synchronized void validate(X509Certificate[] certPath, TrustedCertificates trustedCerts, CertificateRevocationLists crlsList, Boolean enforceSigningPolicy) throws ProxyPathValidatorException { if (certPath == null) { throw new IllegalArgumentException(i18n.getMessage("certsNull")); } if (crlsList == null) { crlsList = CertificateRevocationLists.getDefaultCertificateRevocationLists(); } if (trustedCerts == null) { trustedCerts = TrustedCertificates.getDefault(); } try { SimpleMemoryKeyStoreLoadStoreParameter ksParams = new SimpleMemoryKeyStoreLoadStoreParameter(); SimpleMemoryCertStoreParams csParams = new SimpleMemoryCertStoreParams(null, crlsList.getCrls()); ksParams.setCerts(trustedCerts.getCertificates()); Map<String, ProxyPolicyHandler> initHandlers = new HashMap<String, ProxyPolicyHandler>(); if (this.proxyPolicyHandlers != null) { initHandlers.putAll(proxyPolicyHandlers); } KeyStore ks = KeyStore.getInstance(SimpleMemoryProvider.KEYSTORE_TYPE, SimpleMemoryProvider.PROVIDER_NAME); CertStore cs = CertStore.getInstance(SimpleMemoryProvider.CERTSTORE_TYPE, csParams, SimpleMemoryProvider.PROVIDER_NAME); SimpleMemorySigningPolicyStore spStore = new SimpleMemorySigningPolicyStore( trustedCerts.getSigningPolicies()); ks.load(ksParams); X509ProxyCertPathParameters params = new X509ProxyCertPathParameters(ks, cs, spStore, this.rejectLimitedProxyCheck, initHandlers); validator.engineValidate(CertificateUtil.getCertPath(certPath), params); this.identityCert = validator.getIdentityCertificate(); this.limited = validator.isLimited(); } catch (Exception e) { throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, e); } }