List of usage examples for org.bouncycastle.cert X509CertificateHolder getSubject
public X500Name getSubject()
From source file:AAModulePackage.ACHelper.java
public static X509AttributeCertificateHolder generateAttributeCertificate(X509CertificateHolder issuerCert, X509CertificateHolder associatedCert, PrivateKey pk, String role, String record_id, String record_subject, String[] record_types, String[] actions_taken) { //Set up the validity period. Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); //AttributeCertificateHolder is a wrapper class for AttributeCertificates, courtesy of the Legion of Bouncy Castle. AttributeCertificateIssuer certIssuer = new AttributeCertificateIssuer(issuerCert.getSubject()); /*// ww w. jav a2 s . c o m Please note the distinction between AttributeCertificateHolder which appears to be the Entity in possession of the certificate, while X509AttributeCertificateHolder is a wrapper class for the actual certificate itself. */ AttributeCertificateHolder holder = new AttributeCertificateHolder(associatedCert); X509v2AttributeCertificateBuilder builder = new X509v2AttributeCertificateBuilder(holder, certIssuer, BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate); builder.addAttribute(NewAttributeIdentifiers.role, new DERGeneralString(role)); builder.addAttribute(NewAttributeIdentifiers.record_id, new DERGeneralString(record_id)); builder.addAttribute(NewAttributeIdentifiers.record_subject, new DERGeneralString(record_subject)); builder.addAttribute(NewAttributeIdentifiers.time_stamp, new DERGeneralizedTime(new Date())); //record_types ArrayList<ASN1Encodable> rts = new ArrayList(); for (String s : record_types) { rts.add(new DERGeneralString(s)); } ASN1Encodable[] recTypes = rts.toArray(new DERGeneralString[rts.size()]); builder.addAttribute(NewAttributeIdentifiers.record_type, recTypes); //actions_taken ArrayList<ASN1Encodable> acts = new ArrayList(); for (String s : actions_taken) { acts.add(new DERGeneralString(s)); } ASN1Encodable[] actionsTaken = acts.toArray(new DERGeneralString[acts.size()]); builder.addAttribute(NewAttributeIdentifiers.actions_taken, actionsTaken); //Build the certificate X509AttributeCertificateHolder attrCert = null; try { //builds the attribute certificate, and signs it with the owner's private key. attrCert = builder .build(new JcaContentSignerBuilder("SHA256withRSAEncryption").setProvider("BC").build(pk)); } catch (OperatorCreationException e) { e.printStackTrace(); } System.out.println("ATTRIBUTE CERTIFICATE Successfully generated."); return attrCert; }
From source file:be.apsu.extremon.probes.tsp.TSPProbe.java
License:Open Source License
public void probe_forever() { double start = 0, end = 0; BigInteger requestNonce;//from w w w . ja v a 2 s .co m byte[] requestHashedMessage = new byte[20]; List<String> comments = new ArrayList<String>(); STATE result = STATE.OK; log("running"); this.running = true; while (this.running) { comments.clear(); this.random.nextBytes(requestHashedMessage); requestNonce = new BigInteger(512, this.random); TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage, requestNonce); end = 0; start = System.currentTimeMillis(); try { TimeStampResponse response = probe(request); switch (response.getStatus()) { case PKIStatus.GRANTED: comments.add("granted"); result = STATE.OK; break; case PKIStatus.GRANTED_WITH_MODS: comments.add("granted with modifications"); result = STATE.WARNING; break; case PKIStatus.REJECTION: comments.add("rejected"); result = STATE.ALERT; break; case PKIStatus.WAITING: comments.add("waiting"); result = STATE.ALERT; break; case PKIStatus.REVOCATION_WARNING: comments.add("revocation warning"); result = STATE.WARNING; break; case PKIStatus.REVOCATION_NOTIFICATION: comments.add("revocation notification"); result = STATE.ALERT; break; default: comments.add("response outside RFC3161"); result = STATE.ALERT; break; } if (response.getStatus() >= 2) comments.add(response.getFailInfo() != null ? response.getFailInfo().getString() : "(missing failinfo)"); if (response.getStatusString() != null) comments.add(response.getStatusString()); end = System.currentTimeMillis(); TimeStampToken timestampToken = response.getTimeStampToken(); timestampToken.validate(this.signerVerifier); comments.add("validated"); AttributeTable table = timestampToken.getSignedAttributes(); TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo(); BigInteger responseNonce = tokenInfo.getNonce(); byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest(); long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000; long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000; put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000); if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) { comments.add("clock skew > 1s"); result = STATE.ALERT; } Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null); for (X509CertificateHolder certificate : certs) { AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm(); if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) { String cleanDn = certificate.getSubject().toString().replace("=", ":"); comments.add("signature cert \"" + cleanDn + "\" signed using " + getName(sigalg.getAlgorithm().getId())); result = STATE.ALERT; } } if (!responseNonce.equals(requestNonce)) { comments.add("nonce modified"); result = STATE.ALERT; } if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) { comments.add("hashed message modified"); result = STATE.ALERT; } if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) { comments.add("signingcertificate missing"); result = STATE.ALERT; } } catch (TSPException tspEx) { comments.add("validation failed"); comments.add("tspexception-" + tspEx.getMessage().toLowerCase()); result = STATE.ALERT; } catch (IOException iox) { comments.add("unable to obtain response"); comments.add("ioexception-" + iox.getMessage().toLowerCase()); result = STATE.ALERT; } catch (Exception ex) { comments.add("unhandled exception"); result = STATE.ALERT; } finally { if (end == 0) end = System.currentTimeMillis(); } put(RESULT_SUFFIX, result); put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|")); put("responsetime", (end - start)); try { Thread.sleep(this.delay); } catch (InterruptedException ex) { log("interrupted"); } } }
From source file:be.e_contract.mycarenet.etee.EncryptionToken.java
License:Open Source License
private void logCertificates(Store store, Selector selector) { @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certificates = store.getMatches(selector); LOG.debug("match size: " + certificates.size()); Iterator<X509CertificateHolder> certificatesIterator = certificates.iterator(); while (certificatesIterator.hasNext()) { X509CertificateHolder certificateHolder = certificatesIterator.next(); LOG.debug("certificate issuer: " + certificateHolder.getIssuer()); LOG.debug("certificate subject: " + certificateHolder.getSubject()); }//from ww w. j a va 2s . c o m }
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
License:Open Source License
@Override public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy) throws TrustLinkerResultException, Exception { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return TrustLinkerResult.UNDECIDED; }//from w w w.java2s .com LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate, validationDate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return TrustLinkerResult.UNDECIDED; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return TrustLinkerResult.UNDECIDED; } Object responseObject = ocspResp.getResponseObject(); BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts(); for (X509CertificateHolder responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubject()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer()); } algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate); if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the issuing * CA itself. */ ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey()); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return TrustLinkerResult.UNDECIDED; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509CertificateHolder ocspResponderCertificate = responseCertificates[0]; ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return TrustLinkerResult.UNDECIDED; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature algorithm algorithmPolicy.checkSignatureAlgorithm( ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate); X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { // so the OCSP certificate chain only contains a single // entry LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly signed * by the CA. */ issuingCaCertificate = certificate; } else { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); issuingCaCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded())); /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return TrustLinkerResult.UNDECIDED; } } // check certificate signature algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate); PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded())); LOG.debug("OCSP Responder public key fingerprint: " + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded())); publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate, validationDate, revocationData, algorithmPolicy); if (null == x509OcspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return TrustLinkerResult.UNDECIDED; } List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage(); if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return TrustLinkerResult.UNDECIDED; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return TrustLinkerResult.UNDECIDED; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); // and the CA certificate is already trusted at this point } } DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(); CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber()); SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } DateTime thisUpdate = new DateTime(singleResp.getThisUpdate()); DateTime nextUpdate; if (null != singleResp.getNextUpdate()) { nextUpdate = new DateTime(singleResp.getNextUpdate()); } else { LOG.debug("no OCSP nextUpdate"); nextUpdate = thisUpdate; } LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("(OCSP) nextUpdate: " + nextUpdate); DateTime beginValidity = thisUpdate.minus(this.freshnessInterval); DateTime endValidity = nextUpdate.plus(this.freshnessInterval); DateTime validationDateTime = new DateTime(validationDate); if (validationDateTime.isBefore(beginValidity)) { LOG.warn("OCSP response not yet valid"); continue; } if (validationDateTime.isAfter(endValidity)) { LOG.warn("OCSP response expired"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp, ocspUri); return TrustLinkerResult.TRUSTED; } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp, ocspUri); throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return TrustLinkerResult.UNDECIDED; }
From source file:beta01.SimpleRootCA.java
/** * Build a sample V3 certificate to use as an intermediate CA certificate * @param intKey// w ww. j av a2 s.co m * @param caKey * @param caCert * @return * @throws java.lang.Exception */ public static X509CertificateHolder buildIntermediateCert(AsymmetricKeyParameter intKey, AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception { SubjectPublicKeyInfo intKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(intKey); X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD), new X500Name("CN=Test CA Certificate"), intKeyInfo); X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator()); certBldr.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(intKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA"); AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey); return certBldr.build(signer); }
From source file:beta01.SimpleRootCA.java
/** * Build a sample V3 certificate to use as an end entity certificate *//*from ww w.j a va 2 s. co m*/ public static X509CertificateHolder buildEndEntityCert(AsymmetricKeyParameter entityKey, AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception { SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(entityKey); X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD), new X500Name("CN=Test End Entity Certificate"), entityKeyInfo); X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator()); certBldr.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(entityKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA"); AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey); return certBldr.build(signer); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static String validarAssinaturaCMS(byte[] digest, String digestAlgorithm, byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { final CMSSignedData s; if (digest != null) { Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest); s = new CMSSignedData(map, assinatura); } else {/*from w w w. ja va 2 s. c o m*/ s = new CMSSignedData(assinatura); } Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); X509CertificateHolder firstSignerCert = null; while (it.hasNext()) { SignerInformation signer = it.next(); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder cert = certIt.next(); if (firstSignerCert == null) firstSignerCert = cert; if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) throw new Exception("Assinatura invlida!"); System.out.println("\nSigner Info: \n"); System.out.println("Is Signature Valid? true"); System.out.println("Digest: " + asHex(signer.getContentDigest())); System.out.println("Enc Alg Oid: " + signer.getEncryptionAlgOID()); System.out.println("Digest Alg Oid: " + signer.getDigestAlgOID()); System.out.println("Signature: " + asHex(signer.getSignature())); } // X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta((Collection<X509Certificate>) (certs.getCertificates(null))); X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certs.getMatches(null)); List<X509CRLObject> crls = new ArrayList<>(); if (certs.getMatches(null) != null) { Enumeration ec = ASN1Set.getInstance(certs.getMatches(null)).getObjects(); while (ec.hasMoreElements()) { crls.add(new X509CRLObject(CertificateList.getInstance(ec.nextElement()))); } } final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal, /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()), crls.toArray(new X509CRLObject[0])); cadeia.checkCRL(true); try { cadeia.validateChain(dtAssinatura); } catch (Exception e1) { if (e1.getMessage().endsWith("Validation time is in future.")) { String s1 = e1.getMessage() + " Current date: [" + new Date().toString() + "]. Record date: [" + dtAssinatura + "]. LCRs' dates ["; for (X509CRLObject crl : (Collection<X509CRLObject>) certs.getMatches(null)) { String s2 = crl.getIssuerX500Principal().getName(); s2 = s2.split(",")[0]; s1 += s2 + " (" + crl.getThisUpdate() + " - " + crl.getNextUpdate() + ") "; } s1 += "]"; throw new AplicacaoException(s1, 0, e1); } else throw e1; } // String s1 = firstSignerCert.getSubjectDN().getName(); String s1 = firstSignerCert.getSubject().toString(); s1 = obterNomeExibicao(s1); return s1; }
From source file:CAModulePackage.CAService.java
public boolean validateIDCerts() { File dir = new File(pathToUploadedIDCerts); ArrayList<X509CertificateHolder> idCerts = new ArrayList<X509CertificateHolder>(); ArrayList<X509CertificateHolder> chainCerts = null; Set<X509CertificateHolder> taCerts = new HashSet(); taCerts.add(rootCert);// ww w . j a va2s . c o m //dir's files should all be directories containing certificates/their chains ID: for (File d : dir.listFiles()) { System.out.println("d: " + d.getName()); if (d.getName().equalsIgnoreCase(".DS_Store")) { continue; } //d's files should be either an ID_Cert or that Cert's Chain folder for (File idFile : d.listFiles()) { //if its the ds_store or a folder (chain certs folder) if (idFile.getName().equals(".DS_Store") || idFile.isDirectory()) { continue; } //--------- Certificate Chain Validation ----------- chainCerts = new ArrayList(); //temp store the idCert so we can add it to the validated list if its all good. X509CertificateHolder clientIDCert = CertificateHelper.loadCertFromFile(idFile); chainCerts.add(clientIDCert); System.out.println("Preparing to validate " + clientIDCert.getSubject().toString() + "'s ID_Cert"); //Aquire the certificate chain for this particular ID_Cert File chainDir = new File(d.getPath() + "/Chain"); for (File c : chainDir.listFiles()) { if (c.getName().equalsIgnoreCase(".DS_Store")) { continue; } chainCerts.add(CertificateHelper.loadCertFromFile(c)); } System.out.println( "Certificate Chain for " + clientIDCert.getSubject().toString() + " successfully loaded"); if (!CertificateHelper.validateCertificatePath(taCerts, chainCerts)) { System.out.println("Certificate Chain for " + clientIDCert.getSubject().toString() + " couldn't be validated"); d.delete(); //delete the whole directory. continue ID; } System.out.println("Certificate Chain for " + clientIDCert.getSubject().toString() + " successfully validated"); /* This won't work for certificates generated by CA's that aren't THIS Hospital. I believe validating the certificate path is enough. I'm still looking in the source code for it to see if it checks the necessary things (date, signature, etc.) //ValidateCertificate checks the validity period and signature if(!CertificateHelper.validateCertificate(clientIDCert, idCert)) { d.delete(); continue ID; } */ //If it passes the validation. idCerts.add(clientIDCert); } } //If at least one of the ID_Certs was validated, we may proceed. if (idCerts.size() > 0) { return true; } return false; }
From source file:CAModulePackage.CAService.java
/** * This method checks the upload directory for a Certificate Signing * Request. If one exists, we use it to generate a new X.509 Identity * Certificate.//from w w w. j a v a 2 s . com */ public void signCSR() { File dir = new File(pathToUploadedCSR); PKCS10CertificationRequest req = null; System.out.println("Preparing to sign CSR."); for (File f : dir.listFiles()) { if (!f.getName().equalsIgnoreCase(".DS_Store")) { System.out.println("CSR Will be signed with this system's CA_Cert, whose subject is: " + idCert.getSubject().toString()); req = CertificateHelper.loadCSRFromFile(f); X509CertificateHolder newCert = CertificateHelper.signCSR(req, idCert.getSubject().toString(), keys.getPrivate()); System.out.println("The CSR has been signed.\nSubject: " + newCert.getSubject().toString() + "\nIssuer: " + newCert.getIssuer().toString()); CertificateHelper.saveCertToFile(newCert, pathToGeneratedCerts + "/" + newCert.getIssuer().toString() + ".pem"); //Save a copy to the GoodIDCert directory. CertificateHelper.saveCertToFile(newCert, pathToGoodIDCert + "/" + newCert.getIssuer().toString() + ".pem"); File chainDir = new File(pathToGeneratedCerts + "/Chain"); if (!chainDir.exists()) { chainDir.mkdir(); } CertificateHelper.saveCertToFile(idCert, pathToGeneratedCerts + "/Chain/" + "0" + newCert.getIssuer().toString() + ".pem"); } } }
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 a va 2s. 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; }