List of usage examples for org.bouncycastle.util Store getMatches
Collection<T> getMatches(Selector<T> selector) throws StoreException;
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 . j av a 2 s . c o 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.certra.CertRAClient.java
License:Open Source License
private byte[] getCmsData(byte[] cms) throws Exception { CMSSignedData cmsSignedData = new CMSSignedData(cms); SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); Store certificateStore = cmsSignedData.getCertificates(); Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId); X509CertificateHolder certificateHolder = certificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded())); // we trust SSL here, no need for explicit verification of CMS signing // certificate LOG.debug("CMS signing certificate subject: " + certificate.getSubjectX500Principal()); SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(certificate);//w w w.j a v a 2s . com boolean signatureResult = signer.verify(signerInformationVerifier); if (false == signatureResult) { throw new SecurityException("woops"); } CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] responseData = (byte[]) signedContent.getContent(); return responseData; }
From source file:be.e_contract.mycarenet.etee.EncryptionToken.java
License:Open Source License
private X509Certificate parseEncryptionCertificate(byte[] encodedEncryptionToken) throws CMSException, CertificateException, IOException, OperatorCreationException { CMSSignedData cmsSignedData = new CMSSignedData(encodedEncryptionToken); // get signer identifier SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); // get signer certificate Store certificateStore = cmsSignedData.getCertificates(); LOG.debug("certificate store type: " + certificateStore.getClass().getName()); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> signingCertificateCollection = certificateStore.getMatches(signerId); X509CertificateHolder signingCertificateHolder = signingCertificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate signingCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(signingCertificateHolder.getEncoded())); LOG.debug("signing certificate: " + signingCertificate.getSubjectX500Principal()); // verify CMS signature SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(signingCertificate);/* www. j av a 2 s. co m*/ boolean signatureResult = signer.verify(signerInformationVerifier); if (false == signatureResult) { throw new SecurityException("ETK signature invalid"); } // get encryption certificate CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); X509Certificate encryptionCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(data)); LOG.debug("all available certificates:"); logCertificates(certificateStore, null); // get authentication certificate CustomSelector authenticationSelector = new CustomSelector(); authenticationSelector.setSubject(encryptionCertificate.getIssuerX500Principal()); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> authenticationCertificates = certificateStore .getMatches(authenticationSelector); if (authenticationCertificates.size() != 1) { LOG.debug("no authentication certificate match"); } X509CertificateHolder authenticationCertificateHolder = authenticationCertificates.iterator().next(); this.authenticationCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(authenticationCertificateHolder.getEncoded())); verifyProxyCertificate(encryptionCertificate, this.authenticationCertificate); return encryptionCertificate; }
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()); }/*w w w . j a v a 2s.c o m*/ }
From source file:be.e_contract.mycarenet.etee.Unsealer.java
License:Open Source License
private byte[] getVerifiedContent(byte[] cmsData) throws CertificateException, CMSException, IOException, OperatorCreationException { CMSSignedData cmsSignedData = new CMSSignedData(cmsData); SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); Store certificateStore = cmsSignedData.getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId); if (null == this.senderCertificate) { if (certificateCollection.isEmpty()) { throw new SecurityException("no sender certificate present"); }//w w w . java2s. co m X509CertificateHolder certificateHolder = certificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded())); this.senderCertificate = certificate; LOG.debug("signer certificate subject: " + certificate.getSubjectX500Principal()); } /* * By reusing the sender certificate we have the guarantee that the * outer signature and inner signature share the same origin. */ SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(this.senderCertificate); boolean signatureResult = signer.verify(signerInformationVerifier); if (false == signatureResult) { throw new SecurityException("woops"); } CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); return data; }
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();/*w w w. j a v a 2s . c o 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.AssinaturaDigital.java
License:Open Source License
/** * Interpreta um dado do tipo otherName. Obs. O JDK 5.0 no tem classes que * lidem com um dado do tipo OtherName. necessrio usar o BouncyCastle. * //from w w w . j a va 2s . c om * @param encoded * O dado em ASN.1. * @return Um par contendo o OID e o contedo. */ /* * @SuppressWarnings("unchecked") private static Pair<DERObjectIdentifier, * String> getOtherName(byte[] encoded) throws IOException { // O JDK 5.0 * no tem classes que lidem com um dado do tipo OtherName. // necessrio * usar o BouncyCastle. ASN1InputStream inps = new ASN1InputStream(encoded); * DERSequence seq = null; DERObjectIdentifier oid = null; String conteudo = * ""; seq = (DERSequence) inps.readObject(); inps.close(); Enumeration en = * seq.getObjects(); oid = (DERObjectIdentifier) en.nextElement(); DERObject * obj = ((ASN1TaggedObject) ((ASN1TaggedObject) en * .nextElement()).getObject()).getObject(); if (obj instanceof DERString) { * // Certificados antigos SERASA - // incorretos conteudo = ((DERString) * obj).getString(); } else if (obj instanceof DEROctetString) { // * Certificados corretos conteudo = new String(((DEROctetString) * obj).getOctets(), "ISO-8859-1"); } return new Pair<DERObjectIdentifier, * String>(oid, conteudo); } */ @SuppressWarnings("unchecked") protected static Properties recuperaNomesAlternativos(final byte[] assinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, CMSException, CertStoreException { final CMSSignedData signedData = new CMSSignedData(assinatura); // CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); @SuppressWarnings("unused") String sCN = ""; while (it.hasNext()) { SignerInformation signer = it.next(); // Collection certCollection = certs.getCertificates(signer.getSID()); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); @SuppressWarnings("unused") String ss = signer.getDigestAlgOID(); @SuppressWarnings("unused") String sss = signer.getDigestAlgorithmID().getObjectId().getId(); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder certHolder = certIt.next(); X509Certificate cert = AssinaturaDigital.getX509Certificate(certHolder); /* * *** cdigo comentado movido para * Certificado.recuperarPropriedadesNomesAlteranativos(cert)***** * ATENO: Cdigo sempre retorna na primeira iterao do for ?!!*** * (LAGS) Properties props = new Properties(); for (List<?> * subjectAlternativeName : cert .getSubjectAlternativeNames()) { * String email; Pair<DERObjectIdentifier, String> otherName; * * @SuppressWarnings("unused") int pos; * * // O primeiro elemento um Integer com o valor 0 = otherName, 1 * // = // rfc822name etc. // O segundo valor um byte array ou uma * String. Veja o javadoc // de // getSubjectAlternativeNames. * switch (((Number) subjectAlternativeName.get(0)).intValue()) { * case 0: // OtherName - contm CPF, CNPJ etc. // o OID fica em * otherName.first otherName = getOtherName((byte[]) * subjectAlternativeName .get(1)); * props.put(otherName.first.getId(), otherName.second); break; case * 1: // rfc822Name - usado para email email = (String) * subjectAlternativeName.get(1); props.put("email", email); break; * default: break; } } return props; */ return CertificadoUtil.recuperarPropriedadesNomesAlteranativos(cert); } return null; }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static Store buscarCrlParaCadaCertificado(Store certs) throws CertStoreException, Exception { X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certs.getMatches(null)); List certList = new ArrayList(); for (X509Certificate cert : cadeiaTotal) certList.add(cert);/*from www. j av a2 s . co m*/ for (X509CRLObject crl : (Collection<X509CRLObject>) X509ChainValidator.getCRLs(cadeiaTotal)) certList.add(crl); // certList.add(ASN1Object.fromByteArray(crl.getEncoded())); return new JcaCertStore(certList); }
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 {/*w w w .j a 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:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static String validarAssinaturaCMSeCarimboDeTempo(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { String nome = validarAssinaturaCMS(digest, digestAlgorithm, assinatura, dtAssinatura); Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);/*from w w w . j a va 2 s .c om*/ final CMSSignedData s = new CMSSignedData(map, assinatura); Collection ss = s.getSignerInfos().getSigners(); SignerInformation si = (SignerInformation) ss.iterator().next(); Attribute attr = si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); CMSSignedData cmsTS = new CMSSignedData(attr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded()); TimeStampToken tok = new TimeStampToken(cmsTS); Store cs = tok.getCertificates(); SignerId signer_id = tok.getSID(); BigInteger cert_serial_number = signer_id.getSerialNumber(); Collection certs = cs.getMatches(null); Iterator iter = certs.iterator(); X509Certificate certificate = null; while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert_serial_number != null) { if (cert.getSerialNumber().equals(cert_serial_number)) { certificate = cert; } } else { if (certificate == null) { certificate = cert; } } } tok.validate(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate)); // Nato: falta validar as CRLs do carimbo de tempo if (!Arrays.equals(tok.getTimeStampInfo().getMessageImprintDigest(), MessageDigest.getInstance("SHA1").digest(si.getSignature()))) { throw new Exception("Carimbo de tempo no confere com o resumo do documento"); } try { validarAssinaturaCMS(null, null, cmsTS.getEncoded(), tok.getTimeStampInfo().getGenTime()); } catch (Exception e) { throw new Exception("Carimbo de tempo invlido!", e); } return nome; }