List of usage examples for org.bouncycastle.cms SignerInformation getDigestAlgOID
public String getDigestAlgOID()
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 ww . j a v a 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 w w w. j av a 2s. c om 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 w w . ja v a 2 s.co 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:de.mendelson.util.security.BCCryptoHelper.java
/** * Returns the digest OID algorithm from a signature that signes the passed * message part The return value for sha1 is e.g. "1.3.14.3.2.26". *//*ww w .ja v a 2 s .c om*/ public String getDigestAlgOIDFromSignature(Part part) throws Exception { if (part == null) { throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Part is absent"); } if (part.isMimeType("multipart/signed")) { MimeMultipart signedMultiPart = null; if (part.getContent() instanceof MimeMultipart) { signedMultiPart = (MimeMultipart) part.getContent(); } else { //assuming it is an inputstream now signedMultiPart = new MimeMultipart( new ByteArrayDataSource((InputStream) part.getContent(), part.getContentType())); } SMIMESigned signed = new SMIMESigned(signedMultiPart); SignerInformationStore signerStore = signed.getSignerInfos(); Iterator iterator = signerStore.getSigners().iterator(); while (iterator.hasNext()) { SignerInformation signerInfo = (SignerInformation) iterator.next(); return (signerInfo.getDigestAlgOID()); } throw new GeneralSecurityException( "getDigestAlgOIDFromSignature: Unable to identify signature algorithm."); } throw new GeneralSecurityException("Content-Type indicates data isn't signed"); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * Returns the digest OID algorithm from a pkcs7 signature The return value * for sha1 is e.g. "1.3.14.3.2.26"./*from w w w .j av a 2 s.c om*/ */ public String getDigestAlgOIDFromSignature(byte[] signature) throws Exception { if (signature == null) { throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Signature is absent"); } CMSSignedData signedData = new CMSSignedData(signature); SignerInformationStore signers = signedData.getSignerInfos(); Collection signerCollection = signers.getSigners(); Iterator iterator = signerCollection.iterator(); while (iterator.hasNext()) { SignerInformation signerInfo = (SignerInformation) iterator.next(); return (signerInfo.getDigestAlgOID()); } throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Unable to identify signature algorithm."); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * Returns the digest OID algorithm from a signature. The return value * for sha1 is e.g. "1.3.14.3.2.26".//from w ww . j a va2 s. co m */ public String getDigestAlgOIDFromSignature(InputStream signed, Certificate cert) throws Exception { CMSSignedDataParser parser = new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed); parser.getSignedContent().drain(); SignerInformationStore signers = parser.getSignerInfos(); Collection signerCollection = signers.getSigners(); Iterator it = signerCollection.iterator(); boolean verified = false; X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded()); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC") .build(certHolder); while (it.hasNext()) { SignerInformation signerInformation = (SignerInformation) it.next(); if (!verified) { verified = signerInformation.verify(verifier); if (verified) { return (signerInformation.getDigestAlgOID()); } } } throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Unable to identify signature algorithm."); }
From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectParser.java
License:BSD License
private boolean verifySigner(SignerInformation signer, X509Certificate certificate) { validationResult.rejectIfFalse(DIGEST_ALGORITHM_OID.equals(signer.getDigestAlgOID()), CMS_SIGNER_INFO_DIGEST_ALGORITHM); validationResult.rejectIfFalse(RSA_ENCRYPTION_OID.equals(signer.getEncryptionAlgOID()) || SHA256WITHRSA_ENCRYPTION_OID.equals(signer.getEncryptionAlgOID()), ENCRYPTION_ALGORITHM); if (!validationResult.rejectIfNull(signer.getSignedAttributes(), SIGNED_ATTRS_PRESENT)) { return false; }//ww w . jav a 2 s . com validationResult.rejectIfNull(signer.getSignedAttributes().get(CMSAttributes.contentType), CONTENT_TYPE_ATTR_PRESENT); validationResult.rejectIfNull(signer.getSignedAttributes().get(CMSAttributes.messageDigest), MSG_DIGEST_ATTR_PRESENT); //http://tools.ietf.org/html/rfc6488#section-2.1.6.4 //MUST include contentType and messageDigest //MAY include signingTime, binary-signing-time, or both //Other attributes MUST NOT be included //Check if the signedAttributes are allowed verifyOptionalSignedAttributes(signer); SignerId signerId = signer.getSID(); try { validationResult.rejectIfFalse(signerId.match(new JcaX509CertificateHolder(certificate)), SIGNER_ID_MATCH); } catch (CertificateEncodingException e) { throw new AbstractX509CertificateWrapperException(e); } return true; }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java
License:BSD License
/** * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.3 *//* w w w .ja v a2 s.c o m*/ @Test public void shouldCmsObjectHaveCorrectDigestAlgorithmOID() throws Exception { Collection<?> signers = signedDataParser.getSignerInfos().getSigners(); SignerInformation signer = (SignerInformation) signers.iterator().next(); assertEquals(DIGEST_SHA256, signer.getDigestAlgOID()); }
From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java
License:BSD License
/** * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.3 *//*from w w w. j a v a2s .c o m*/ private void verifyDigestAlgorithm(SignerInformation signer) { validationResult.rejectIfFalse(CMSSignedGenerator.DIGEST_SHA256.equals(signer.getDigestAlgOID()), CMS_SIGNER_INFO_DIGEST_ALGORITHM); }
From source file:org.ejbca.core.model.ca.caadmin.CmsCAServiceTest.java
License:Open Source License
@Test public void testCmsCAServiceActive() throws Exception { // Activate the service first testActivateCmsCAService();// w w w . ja v a 2s. c o m CmsCAServiceRequest request = new CmsCAServiceRequest(doc, CmsCAServiceRequest.MODE_SIGN); CmsCAServiceResponse resp = null; // Try the request again boolean active = true; try { resp = (CmsCAServiceResponse) caAdminSession.extendedService(admin, getTestCAId(), request); } catch (ExtendedCAServiceNotActiveException e) { active = false; } // By default the CA service is not active assertTrue(active); assertNotNull(resp); byte[] respdoc = resp.getCmsDocument(); assertNotNull(resp); CMSSignedData csd = new CMSSignedData(respdoc); SignerInformationStore infoStore = csd.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> signers = infoStore.getSigners(); Iterator<SignerInformation> iter = signers.iterator(); if (iter.hasNext()) { SignerInformation si = iter.next(); assertNotNull(si); // log.info("Digest alg is: "+si.getDigestAlgOID()); assertEquals(CMSSignedGenerator.DIGEST_SHA1, si.getDigestAlgOID()); SignerId sid = si.getSID(); // log.info(sid.toString()); X500Name issuer = sid.getIssuer(); assertNotNull(issuer); assertEquals("CN=TEST", issuer.toString()); } Store store = csd.getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certs = store.getMatches(null); assertEquals(2, certs.size()); CMSProcessable cp = csd.getSignedContent(); Object o = cp.getContent(); byte[] ob = (byte[]) o; assertEquals(new String(doc), new String(ob)); }