List of usage examples for org.bouncycastle.cms SignerInformation getSID
public SignerId getSID()
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. * //w ww .j ava 2 s . c o m * @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 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 ww w . j a v a 2 s . com*/ 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") public static String validarAssinaturaPKCS7(final byte[] digest, final String digestAlgorithm, final byte[] assinatura, Date dtAssinatura, boolean verificarLCRs) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, Exception { Map<String, byte[]> map = new HashMap<String, byte[]>(); map.put(digestAlgorithm, digest);//from w ww. ja v a 2 s . c o m final CMSSignedData signedData = new CMSSignedData(map, assinatura); Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); String sCN = ""; while (it.hasNext()) { SignerInformation signer = it.next(); 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); if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder))) throw new Exception("Assinatura invlida!"); X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certCollection); final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal, /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()), null); cadeia.checkCRL(verificarLCRs); cadeia.validateChain(dtAssinatura); String s2 = cert.getSubjectDN().getName(); s2 = obterNomeExibicao(s2); if (sCN.length() != 0) sCN += ", "; sCN += s2; } return sCN.length() == 0 ? null : sCN; }
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) *//* w ww .j a v a2 s.com*/ 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:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java
License:Open Source License
@Override public boolean verify() { try {/*from www .j a v a2 s . c o m*/ // For additional security, you may verify the fingerprint of the root CA and the OIDs of the // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate // is (1 2 840 113635 100 6 11 1). final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute())); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); for (SignerInformation signer : (Iterable<SignerInformation>) signers.getSigners()) { final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID()); for (X509CertificateHolder holder : matches) { if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder() .setProvider(new BouncyCastleProvider()).build(holder))) { return false; } } } // Extract the receipt attributes final CMSProcessable signedContent = s.getSignedContent(); byte[] originalContent = (byte[]) signedContent.getContent(); final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent); byte[] opaque = null; String bundleIdentifier = null; String bundleVersion = null; byte[] hash = null; if (asn instanceof ASN1Set) { // 2 Bundle identifier Interpret as an ASN.1 UTF8STRING. // 3 Application version Interpret as an ASN.1 UTF8STRING. // 4 Opaque value Interpret as a series of bytes. // 5 SHA-1 hash Interpret as a 20-byte SHA-1 digest value. final ASN1Set set = (ASN1Set) asn; final Enumeration enumeration = set.getObjects(); while (enumeration.hasMoreElements()) { Object next = enumeration.nextElement(); if (next instanceof DLSequence) { DLSequence sequence = (DLSequence) next; ASN1Encodable type = sequence.getObjectAt(0); if (type instanceof ASN1Integer) { if (((ASN1Integer) type).getValue().intValue() == 2) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 3) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 4) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { opaque = ((DEROctetString) value).getOctets(); } } else if (((ASN1Integer) type).getValue().intValue() == 5) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { hash = ((DEROctetString) value).getOctets(); } } } } } } else { log.error(String.format("Expected set of attributes for %s", asn)); return false; } if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.identifier"), StringUtils.trim(bundleIdentifier))) { log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier)); return false; } if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.version"), StringUtils.trim(bundleVersion))) { log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion)); } final NetworkInterface en0 = NetworkInterface.getByName("en0"); if (null == en0) { // Interface is not found when link is down #fail log.warn("No network interface en0"); return true; } else { final byte[] mac = en0.getHardwareAddress(); if (null == mac) { log.error("Cannot determine MAC address"); // Continue without validation return true; } final String hex = Hex.encodeHexString(mac); if (log.isDebugEnabled()) { log.debug(String.format("Interface en0 %s", hex)); } // Compute the hash of the GUID final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(mac); if (null == opaque) { log.error(String.format("Missing opaque string in ASN.1 set %s", asn)); return false; } digest.update(opaque); if (null == bundleIdentifier) { log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn)); return false; } digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8"))); final byte[] result = digest.digest(); if (Arrays.equals(result, hash)) { if (log.isInfoEnabled()) { log.info(String.format("Valid receipt for GUID %s", hex)); } guid = hex; return true; } else { log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt", hex)); return false; } } } catch (IOException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (GeneralSecurityException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (SecurityException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (CMSException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (Exception e) { log.error("Unknown receipt validation error", e); return true; } }
From source file:chapter9.SignedDataProcessor.java
/** * Take a CMS SignedData message and a trust anchor and determine if * the message is signed with a valid signature from a end entity * certificate recognized by the trust anchor rootCert. * @param signedData//from ww w . j av a2 s . c om * @param rootCert * @return * @throws Exception */ public static boolean isValid(CMSSignedData signedData, X509Certificate rootCert) throws Exception { CertStore certsAndCRLs = signedData.getCertificatesAndCRLs("Collection", CryptoDefs.Provider.BC.getName()); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); signerConstraints.setKeyUsage(getKeyUsageForSignature()); PKIXCertPathBuilderResult result = Utils.buildPath(rootCert, signer.getSID(), certsAndCRLs); return signer.verify(result.getPublicKey(), CryptoDefs.Provider.BC.getName()); } return false; }
From source file:com.blackberry.bidhelper.BidCertificateVerifierAndroid.java
License:Apache License
@Override public boolean verifyReport(byte[] tzReport, byte[] signature) throws CertificateException { if (this.bidCert == null) { throw new IllegalStateException("Certificate not yet set"); }//w ww.j a v a 2s. c o m try { CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(tzReport), signature); Store certStore = cms.getCertificates(); SignerInformationStore signers = cms.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); if (c.size() != 1) { return false; } while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); // If there is no certificate part of the signature then the report may have been created before // the certificate was cut. if (certCollection.size() == 0) { return signer .verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(this.bidCert)); } X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certHolder); return signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)); } } catch (CMSException e) { throw new CertificateException(e.toString()); } catch (OperatorCreationException oce) { throw new CertificateException(oce.toString()); } catch (Exception ex) { throw ex; } return false; }
From source file:com.cordys.coe.ac.emailio.util.smime.SMIMEUtil.java
License:Apache License
/** * verify the signature (assuming the cert is contained in the message). * * @param sSigned The signed content. * * @throws Exception In case of any exceptions. *///from w w w . ja va 2 s . com private static void verify(SMIMESigned sSigned) throws Exception { // Get all certificates from the mail itself CertStore certs = sSigned.getCertificatesAndCRLs("Collection", "BC"); // SignerInfo blocks which contain the signatures SignerInformationStore signers = sSigned.getSignerInfos(); Collection<?> c = signers.getSigners(); Iterator<?> it = c.iterator(); // Check each signer while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection<?> certCollection = certs.getCertificates(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate) certIt.next(); // Verify that the signature is correct and that it was generated // when the certificate was current if (signer.verify(cert, "BC")) { if (LOG.isDebugEnabled()) { LOG.debug("Signature for " + signer.getSID().getSubjectAsString() + " is valid."); } } else { throw new EmailIOException( EmailIOExceptionMessages.EIOE_VALIDATION_OF_THE_SIGNATURE_FOR_CERTIFICATE_0_FAILED, signer.getSID().getSubjectAsString()); } } }
From source file:com.cordys.coe.test.smime.TestSMIMEBouncyCastle.java
License:Apache License
/** * verify the signature (assuming the cert is contained in the message). * * @param s DOCUMENTME//from w ww . ja v a 2s .co m * * @throws Exception DOCUMENTME */ private static void verify(SMIMESigned s) throws Exception { CertStore certs = s.getCertificatesAndCRLs("Collection", "BC"); // // 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.getCertificates(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509Certificate cert = (X509Certificate) certIt.next(); // // verify that the sig is correct and that it was generated // when the certificate was current // if (signer.verify(cert, "BC")) { System.out.println("signature verified"); } else { System.out.println("signature failed!"); } } }
From source file:com.google.code.p.keytooliui.ktl.util.jarsigner.CmsVerif.java
License:LGPL
public boolean doJob() { String strMethod = "doJob()"; try {/*ww w. ja va2 s. com*/ //_validateCmsSignature(); CMSSignedData cms = _getSignPkcs7(); SignerInformationStore sis = cms.getSignerInfos(); Collection colSignerInfo = sis.getSigners(); Iterator itrSignerInfo = colSignerInfo.iterator(); SignerInformation sin = (SignerInformation) itrSignerInfo.next(); //rcupration du certificat du signataire CertStore cse = cms.getCertificatesAndCRLs("Collection", CmsVerif._STR_KST_PROVIDER_BC); Iterator itrCert = cse.getCertificates(sin.getSID()).iterator(); X509Certificate crt = (X509Certificate) itrCert.next(); // Verifie la signature boolean blnCoreValidity = sin.verify(crt, CmsVerif._STR_KST_PROVIDER_BC); if (blnCoreValidity) { MySystem.s_printOutTrace(this, strMethod, "blnCoreValidity=true"); String strBody = "CMS Detached signature is OK!"; strBody += "\n\n" + ". CMS signature file location:"; strBody += "\n " + super._strPathAbsFileSig_; strBody += "\n\n" + ". Data file location:"; strBody += "\n " + super._strPathAbsFileData_; OPAbstract.s_showDialogInfo(super._frmOwner_, strBody); //SignerInfo sio = sin.toSignerInfo(); SignerId sid = sin.getSID(); if (sid != null) { System.out.println("sid.getSerialNumber()=" + sid.getSerialNumber()); System.out.println("sid.getIssuerAsString()=" + sid.getIssuerAsString()); System.out.println("sid.getSubjectAsString()=" + sid.getSubjectAsString()); } /*System.out.println("sin.getDigestAlgOID()=" + sin.getDigestAlgOID()); System.out.println("sin.getEncryptionAlgOID()=" + sin.getEncryptionAlgOID()); System.out.println("sin.toString()=" + sin.toString()); System.out.println("sin.getVersion()=" + sin.getVersion());*/ } else { MySystem.s_printOutWarning(this, strMethod, "blnCoreValidity=true"); String strBody = "CMS Detached signature is WRONG!"; strBody += "\n\n" + ". CMS signature file location:"; strBody += "\n " + super._strPathAbsFileSig_; strBody += "\n\n" + ". Data file location:"; strBody += "\n " + super._strPathAbsFileData_; OPAbstract.s_showDialogWarning(super._frmOwner_, strBody); } } catch (Exception exc) { exc.printStackTrace(); MySystem.s_printOutError(this, strMethod, "exc caught"); String strBody = "Failed to verify CMS detached signature."; strBody += "\n\n" + "Possible reason: wrong data file"; strBody += "\n\n" + "got exception."; strBody += "\n" + exc.getMessage(); strBody += "\n\n" + "More: see your session.log"; OPAbstract.s_showDialogError(super._frmOwner_, strBody); return false; } // TODO return true; }