List of usage examples for org.bouncycastle.cms SignerInformation getSignature
public byte[] getSignature()
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESService.java
License:Open Source License
/** * This method countersigns a signature identified through its SignerId * * @param toCounterSignDocument the original signature document containing the signature to countersign * @param parameters the signature parameters * @param selector the SignerId identifying the signature to countersign * @return the updated signature document, in which the countersignature has been embedded *//*from w w w. j a va2 s .com*/ public DSSDocument counterSignDocument(final DSSDocument toCounterSignDocument, final SignatureParameters parameters, SignerId selector) { final SignatureTokenConnection token = parameters.getSigningToken(); if (token == null) { throw new DSSNullException(SignatureTokenConnection.class, "", "The connection through available API to the SSCD must be set."); } try { //Retrieve the original signature final InputStream inputStream = toCounterSignDocument.openStream(); final CMSSignedData cmsSignedData = new CMSSignedData(inputStream); DSSUtils.closeQuietly(inputStream); SignerInformationStore signerInfos = cmsSignedData.getSignerInfos(); SignerInformation signerInformation = signerInfos.get(selector); //Generate a signed digest on the contents octets of the signature octet String in the identified SignerInfo value //of the original signature's SignedData byte[] dataToSign = signerInformation.getSignature(); byte[] signatureValue = token.sign(dataToSign, parameters.getDigestAlgorithm(), parameters.getPrivateKeyEntry()); //Set the countersignature builder CounterSignatureBuilder builder = new CounterSignatureBuilder(certificateVerifier); builder.setCmsSignedData(cmsSignedData); builder.setSelector(selector); final SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm(); final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(), signatureValue); SignerInfoGeneratorBuilder signerInformationGeneratorBuilder = builder .getSignerInfoGeneratorBuilder(parameters, true); CMSSignedDataGenerator cmsSignedDataGenerator = builder.createCMSSignedDataGenerator(parameters, customContentSigner, signerInformationGeneratorBuilder, null); CMSTypedData content = cmsSignedData.getSignedContent(); CMSSignedData signedData = cmsSignedDataGenerator.generate(content); final CMSSignedData countersignedCMSData = builder.signDocument(signedData); final CMSSignedDocument signature = new CMSSignedDocument(countersignedCMSData); return signature; } catch (CMSException e) { throw new DSSException("Cannot parse CMS data", e); } }
From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBaselineT.java
License:Open Source License
private AttributeTable addSignatureTimestampAttribute(SignerInformation signerInformation, AttributeTable unsignedAttributes, CAdESSignatureParameters parameters) { ASN1Object signatureTimeStamp = getTimeStampAttributeValue(signatureTsa, signerInformation.getSignature(), parameters);/*from www . j a v a 2 s . c o m*/ return unsignedAttributes.add(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, signatureTimeStamp); }
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.6 *///from w ww . j a v a2 s .co m @Test public void shouldCmsObjectHaveValidSignature() throws Exception { Collection<?> signers = signedDataParser.getSignerInfos().getSigners(); SignerInformation signer = (SignerInformation) signers.iterator().next(); assertNotNull(signer.getSignature()); assertTrue("signature verify", signer.verify(new JcaSignerInfoVerifierBuilder(BouncyCastleUtil.DIGEST_CALCULATOR_PROVIDER) .build(ProvisioningCmsCertificateBuilderTest.TEST_CMS_CERT.getCertificate()))); }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
License:Open Source License
private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException { Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners(); // get signature of first signer (should be the only one) SignerInformation si = signerInfos.iterator().next(); byte[] signature = si.getSignature(); // send request to TSA byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1); // create new SignerInformation with TS attribute Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, new DERSet(ASN1Primitive.fromByteArray(token))); ASN1EncodableVector timestampVector = new ASN1EncodableVector(); timestampVector.add(tokenAttr);//from w ww . ja v a 2 s . c om AttributeTable at = new AttributeTable(timestampVector); si = SignerInformation.replaceUnsignedAttributes(si, at); signerInfos.clear(); signerInfos.add(si); SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos); // create new signed data CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore); return newSignedData; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESChecker.java
License:Open Source License
/** * Validation is done only on digital signatures with a single signer. Valid * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 = * OID Data 1.2.840.113549.1.7.1/*from w ww .ja va 2 s . co m*/ * * @param content Is only necessary to inform if the PKCS7 package is NOT * ATTACHED type. If it is of type attached, this parameter will be * replaced by the contents of the PKCS7 package. * @param signedData Value in bytes of the PKCS7 package, such as the * contents of a ".p7s" file. It is not only signature as in the * case of PKCS1. */ // TODO: Implementar validao de co-assinaturas public boolean check(byte[] content, byte[] signedData) throws SignerException { Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = null; try { if (content == null) { if (this.checkHash) { cmsSignedData = new CMSSignedData(this.hashes, signedData); this.checkHash = false; } else { cmsSignedData = new CMSSignedData(signedData); } } else { if (this.getAttached(signedData, false) != null) { cmsSignedData = new CMSSignedData(signedData); } else { cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData); } } } catch (CMSException ex) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex); } // Quantidade inicial de assinaturas validadas int verified = 0; Store<?> certStore = cmsSignedData.getCertificates(); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); // Realizao da verificao bsica de todas as assinaturas while (it.hasNext()) { SignatureInformations signatureInfo = new SignatureInformations(); try { SignerInformation signerInfo = (SignerInformation) it.next(); SignerInformationStore signerInfoStore = signerInfo.getCounterSignatures(); logger.info("Foi(ram) encontrada(s) " + signerInfoStore.size() + " contra-assinatura(s)."); @SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signerInfo.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder); CRLValidator cV = new CRLValidator(); try { cV.validate(varCert); } catch (CertificateValidatorCRLException cvce) { signatureInfo.getValidatorErrors().add(cvce.getMessage()); logger.info(cvce.getMessage()); } catch (CertificateRevocationException cre) { signatureInfo.getValidatorErrors().add(cre.getMessage()); logger.info("certificado revogado"); } PeriodValidator pV = new PeriodValidator(); try { pV.validate(varCert); } catch (CertificateValidatorException cve) { signatureInfo.getValidatorErrors().add(cve.getMessage()); } if (signerInfo.verify( new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) { verified++; logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified)); } // recupera atributos assinados logger.info(cadesMessagesBundle.getString("info.signed.attribute")); String varOIDPolicy = PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId(); AttributeTable signedAttributes = signerInfo.getSignedAttributes(); if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); logger.info(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); //throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); } else { //Validando atributos assinados de acordo com a politica Attribute idSigningPolicy = null; idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(varOIDPolicy)); if (idSigningPolicy == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", varOIDPolicy)); } else { for (Enumeration<?> p = idSigningPolicy.getAttrValues().getObjects(); p .hasMoreElements();) { String policyOnSignature = p.nextElement().toString(); for (PolicyFactory.Policies pv : PolicyFactory.Policies.values()) { if (policyOnSignature.contains(pv.getUrl())) { setSignaturePolicy(pv); break; } } } } } Date dataHora = null; if (signedAttributes != null) { // Valida o atributo ContentType Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType); if (attributeContentType == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); //throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); logger.info( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.content.not.data")); //throw new SignerException(cadesMessagesBundle.getString("error.content.not.data")); logger.info(cadesMessagesBundle.getString("error.content.not.data")); } // Validando o atributo MessageDigest Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest")); } // Mostra data e hora da assinatura, no carimbo de tempo Attribute timeAttribute = signedAttributes.get(CMSAttributes.signingTime); if (timeAttribute != null) { dataHora = (((ASN1UTCTime) timeAttribute.getAttrValues().getObjectAt(0)).getDate()); logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora)); } else { logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D")); } } if (signaturePolicy == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.policy.on.component.not.found", varOIDPolicy)); logger.info(cadesMessagesBundle.getString("error.policy.on.component.not.found")); } else { if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules() .getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) { String oi = objectIdentifier.getValue(); Attribute signedAtt = signedAttributes.get(new ASN1ObjectIdentifier(oi)); logger.info(oi); if (signedAtt == null) { signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString( "error.signed.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue())); } } } } // recupera os atributos NO assinados logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); AttributeTable unsignedAttributes = signerInfo.getUnsignedAttributes(); if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) { // Apenas info pois a RB no tem atributos no assinados logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found")); } if (signaturePolicy != null) { // Validando atributos NO assinados de acordo com a politica if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules() .getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) { String oi = objectIdentifier.getValue(); Attribute unSignedAtt = unsignedAttributes.get(new ASN1ObjectIdentifier(oi)); logger.info(oi); if (unSignedAtt == null) { signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString( "error.unsigned.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue())); } if (oi.equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) { //Verificando timeStamp try { byte[] varSignature = signerInfo.getSignature(); Timestamp varTimeStampSigner = validateTimestamp(unSignedAtt, varSignature); signatureInfo.setTimeStampSigner(varTimeStampSigner); } catch (Exception ex) { signatureInfo.getValidatorErrors().add(ex.getMessage()); // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo. } } if (oi.equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) { logger.info("++++++++++ EscTimeStamp ++++++++++++"); } } } } LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance() .getCertificateChain(varCert); if (varChain.size() < 3) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN())); logger.info(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN())); } signatureInfo.setSignDate(dataHora); signatureInfo.setChain(varChain); signatureInfo.setSignaturePolicy(signaturePolicy); this.getSignaturesInfo().add(signatureInfo); } catch (OperatorCreationException | java.security.cert.CertificateException ex) { signatureInfo.getValidatorErrors().add(ex.getMessage()); logger.info(ex.getMessage()); } catch (CMSException ex) { // When file is mismatch with sign if (ex instanceof CMSSignerDigestMismatchException) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signature.mismatch")); logger.info(cadesMessagesBundle.getString("error.signature.mismatch")); throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex); } else { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signature.invalid")); logger.info(cadesMessagesBundle.getString("error.signature.invalid")); throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex); } } catch (ParseException e) { signatureInfo.getValidatorErrors().add(e.getMessage()); logger.info(e.getMessage()); } } logger.info(cadesMessagesBundle.getString("info.signature.verified", verified)); // TODO Efetuar o parsing da estrutura CMS return true; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
/** * Validation is done only on digital signatures with a single signer. Valid * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 = * OID Data 1.2.840.113549.1.7.1/* w w w .j av a2s .c o m*/ * * @param content Is only necessary to inform if the PKCS7 package is NOT * ATTACHED type. If it is of type attached, this parameter will be * replaced by the contents of the PKCS7 package. * @param signedData Value in bytes of the PKCS7 package, such as the * contents of a ".p7s" file. It is not only signature as in the * case of PKCS1. * @deprecated moved to CadESChecker */ @SuppressWarnings("unchecked") @Override public boolean check(byte[] content, byte[] signedData) throws SignerException { Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = null; try { if (content == null) { if (this.checkHash) { cmsSignedData = new CMSSignedData(this.hashes, signedData); this.checkHash = false; } else { cmsSignedData = new CMSSignedData(signedData); } } else { cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData); } } catch (CMSException ex) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex); } // Quantidade inicial de assinaturas validadas int verified = 0; Store<?> certStore = cmsSignedData.getCertificates(); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); // Realizao da verificao bsica de todas as assinaturas while (it.hasNext()) { try { SignerInformation signer = (SignerInformation) it.next(); SignerInformationStore s = signer.getCounterSignatures(); SignatureInformations si = new SignatureInformations(); logger.info("Foi(ram) encontrada(s) " + s.size() + " contra-assinatura(s)."); Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder); PeriodValidator pV = new PeriodValidator(); try { pV.validate(varCert); } catch (CertificateValidatorException cve) { si.getValidatorErrors().add(cve.getMessage()); } CRLValidator cV = new CRLValidator(); try { cV.validate(varCert); } catch (CertificateValidatorCRLException cvce) { si.getValidatorErrors().add(cvce.getMessage()); } if (signer.verify( new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) { verified++; logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified)); } // Realiza a verificao dos atributos assinados logger.info(cadesMessagesBundle.getString("info.signed.attribute")); AttributeTable signedAttributes = signer.getSignedAttributes(); if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) { throw new SignerException( cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); } // Realiza a verificao dos atributos no assinados logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); AttributeTable unsignedAttributes = signer.getUnsignedAttributes(); if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) { logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found")); } // Mostra data e hora da assinatura, no carimbo de tempo Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime); Date dataHora = null; if (signingTime != null) { dataHora = (((ASN1UTCTime) signingTime.getAttrValues().getObjectAt(0)).getDate()); logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora)); } else { logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D")); } logger.info(cadesMessagesBundle.getString("info.attribute.validation")); // Valida o atributo ContentType Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException(cadesMessagesBundle.getString("error.content.not.data")); } // Validando o atributo MessageDigest Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest")); } // Validando o atributo MessageDigest Attribute idSigningPolicy = null; idSigningPolicy = signedAttributes .get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId())); if (idSigningPolicy == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy")); } //Verificando timeStamp try { Attribute attributeTimeStamp = null; attributeTimeStamp = unsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())); if (attributeTimeStamp != null) { byte[] varSignature = signer.getSignature(); Timestamp varTimeStampSigner = validateTimestamp(attributeTimeStamp, varSignature); si.setTimeStampSigner(varTimeStampSigner); } } catch (Exception ex) { // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo. } LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance() .getCertificateChain(varCert); si.setSignDate(dataHora); si.setChain(varChain); si.setSignaturePolicy(signaturePolicy); this.getSignatureInfo().add(si); } catch (OperatorCreationException | java.security.cert.CertificateException ex) { throw new SignerException(ex); } catch (CMSException ex) { // When file is mismatch with sign if (ex instanceof CMSSignerDigestMismatchException) throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex); else throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex); } catch (ParseException e) { throw new SignerException(e); } } logger.info(cadesMessagesBundle.getString("info.signature.verified", verified)); // TODO Efetuar o parsing da estrutura CMS return true; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
private byte[] doSign(byte[] content, byte[] previewSignature) { try {/*from w w w . j av a 2 s .c o m*/ Security.addProvider(new BouncyCastleProvider()); // Completa os certificados ausentes da cadeia, se houver if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) { this.certificate = (X509Certificate) this.certificateChain[0]; } this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate); if (this.certificateChain.length < 3) { throw new SignerException( cadesMessagesBundle.getString("error.no.ca", this.certificate.getIssuerDN())); } Certificate[] certStore = new Certificate[] {}; CMSSignedData cmsPreviewSignedData = null; // Caso seja co-assinatura ou contra-assinatura // Importar todos os certificados da assinatura anterior if (previewSignature != null && previewSignature.length > 0) { cmsPreviewSignedData = new CMSSignedData(new CMSAbsentContent(), previewSignature); Collection<X509Certificate> previewCerts = this.getSignersCertificates(cmsPreviewSignedData); //previewCerts.add(this.certificate); certStore = previewCerts.toArray(new Certificate[] {}); } setCertificateManager(new CertificateManager(this.certificate)); // Recupera a lista de algoritmos da politica e o tamanho minimo da // chave List<AlgAndLength> listOfAlgAndLength = new ArrayList<AlgAndLength>(); for (AlgAndLength algLength : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy() .getCommonRules().getAlgorithmConstraintSet().getSignerAlgorithmConstraints() .getAlgAndLengths()) { listOfAlgAndLength.add(algLength); } AlgAndLength algAndLength = null; // caso o algoritmo tenha sido informado como parmetro ir // verificar se o mesmo permitido pela politica if (this.pkcs1.getAlgorithm() != null) { String varSetedAlgorithmOID = AlgorithmNames.getOIDByAlgorithmName(this.pkcs1.getAlgorithm()); for (AlgAndLength algLength : listOfAlgAndLength) { if (algLength.getAlgID().getValue().equalsIgnoreCase(varSetedAlgorithmOID)) { algAndLength = algLength; SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum .valueOf(this.pkcs1.getAlgorithm()); String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash(); ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg() .getAlgorithm(); varObjectIdentifier.setValue(varOIDAlgorithmHash); AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg(); varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier); signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier); } } } else { algAndLength = listOfAlgAndLength.get(1); this.pkcs1.setAlgorithm(AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue())); SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm()); String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash(); ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg().getAlgorithm(); varObjectIdentifier.setValue(varOIDAlgorithmHash); AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg(); varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier); signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier); } if (algAndLength == null) { throw new SignerException(cadesMessagesBundle.getString("error.no.algorithm.policy")); } logger.info(cadesMessagesBundle.getString("info.algorithm.id", algAndLength.getAlgID().getValue())); logger.info(cadesMessagesBundle.getString("info.algorithm.name", AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue()))); logger.info(cadesMessagesBundle.getString("info.min.key.length", algAndLength.getMinKeyLength())); // Recupera o tamanho minimo da chave para validacao logger.info(cadesMessagesBundle.getString("info.validating.key.length")); int keyLegth = ((RSAKey) certificate.getPublicKey()).getModulus().bitLength(); if (keyLegth < algAndLength.getMinKeyLength()) { throw new SignerException(cadesMessagesBundle.getString("error.min.key.length", algAndLength.getMinKeyLength().toString(), keyLegth)); } AttributeFactory attributeFactory = AttributeFactory.getInstance(); // Consulta e adiciona os atributos assinados ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); logger.info(cadesMessagesBundle.getString("info.signed.attribute")); if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules() .getMandatedSignedAttr().getObjectIdentifiers()) { SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(objectIdentifier.getValue()); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, content, signaturePolicy, this.hash); signedAttributes.add(signedOrUnsignedAttribute.getValue()); } } // Monta a tabela de atributos assinados AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); // Create the table table generator that will added to the Signer // builder CMSAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator( signedAttributesTable); // Recupera o(s) certificado(s) de confianca para validacao Collection<X509Certificate> trustedCAs = new HashSet<X509Certificate>(); Collection<CertificateTrustPoint> ctp = signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSigningCertTrustCondition() .getSignerTrustTrees().getCertificateTrustPoints(); for (CertificateTrustPoint certificateTrustPoint : ctp) { logger.info(cadesMessagesBundle.getString("info.trust.point", certificateTrustPoint.getTrustpoint().getSubjectDN().toString())); trustedCAs.add(certificateTrustPoint.getTrustpoint()); } // Efetua a validacao das cadeias do certificado baseado na politica Collection<X509Certificate> certificateChainTrusted = new HashSet<X509Certificate>(); for (Certificate certCA : certificateChain) { certificateChainTrusted.add((X509Certificate) certCA); } X509Certificate rootOfCertificate = null; for (X509Certificate tcac : certificateChainTrusted) { logger.info(tcac.getIssuerDN().toString()); if (CAManager.getInstance().isRootCA(tcac)) { rootOfCertificate = tcac; } } if (trustedCAs.contains(rootOfCertificate)) { logger.info(cadesMessagesBundle.getString("info.trust.in.point", rootOfCertificate.getSubjectDN())); } else { // No encontrou na poltica, verificar nas cadeias do // componente chain-icp-brasil provavelmente certificado de // homologao. logger.warn(cadesMessagesBundle.getString("info.trust.poin.homolog")); CAManager.getInstance().validateRootCAs(certificateChainTrusted, certificate); } // validade da politica logger.info(cadesMessagesBundle.getString("info.policy.valid.period")); PolicyValidator pv = new PolicyValidator(this.signaturePolicy, this.policyName); pv.validate(); // Realiza a assinatura do conteudo CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificates(this.generatedCertStore(certStore)); String algorithmOID = algAndLength.getAlgID().getValue(); logger.info(cadesMessagesBundle.getString("info.algorithm.id", algorithmOID)); SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder() .setSignedAttributeGenerator(signedAttributeGenerator).setUnsignedAttributeGenerator(null) .build(AlgorithmNames.getAlgorithmNameByOID(algorithmOID), this.pkcs1.getPrivateKey(), this.certificate); gen.addSignerInfoGenerator(signerInfoGenerator); CMSTypedData cmsTypedData; // para assinatura do hash, content nulo if (content == null) { cmsTypedData = new CMSAbsentContent(); } else { cmsTypedData = new CMSProcessableByteArray(content); } // Efetua a assinatura digital do contedo CMSSignedData cmsSignedData = gen.generate(cmsTypedData, this.attached); setAttached(false); // Consulta e adiciona os atributos no assinados// ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector(); logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); Collection<SignerInformation> vNewSigners = cmsSignedData.getSignerInfos().getSigners(); Iterator<SignerInformation> it = vNewSigners.iterator(); SignerInformation oSi = it.next(); if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules() .getMandatedUnsignedAttr().getObjectIdentifiers()) { SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(objectIdentifier.getValue()); if (signedOrUnsignedAttribute.getOID() .equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) { signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, oSi.getSignature(), signaturePolicy, this.hash); } if (signedOrUnsignedAttribute.getOID().equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) //EscTimeStamp { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(oSi.getSignature()); AttributeTable varUnsignedAttributes = oSi.getUnsignedAttributes(); Attribute varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier( PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); varAttribute = varUnsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_certificateRefs.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); varAttribute = varUnsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_revocationRefs.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); escTimeStampContent = outputStream.toByteArray(); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, escTimeStampContent, signaturePolicy, this.hash); } else { signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, oSi.getSignature(), signaturePolicy, this.hash); } unsignedAttributes.add(signedOrUnsignedAttribute.getValue()); AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes); vNewSigners.remove(oSi); oSi = SignerInformation.replaceUnsignedAttributes(oSi, unsignedAttributesTable); vNewSigners.add(oSi); } } //TODO Estudar este mtodo de contra-assinatura posteriormente if (previewSignature != null && previewSignature.length > 0) { vNewSigners.addAll(cmsPreviewSignedData.getSignerInfos().getSigners()); } SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners); CMSSignedData oSignedData = cmsSignedData; cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore); byte[] result = cmsSignedData.getEncoded(); logger.info(cadesMessagesBundle.getString("info.signature.ok")); return result; } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) { throw new SignerException(ex); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
@Override public byte[] doCounterSign(byte[] previewCMSSignature) { try {/*from w ww. ja v a 2s. c o m*/ Security.addProvider(new BouncyCastleProvider()); // Reading a P7S file that is preview signature. CMSSignedData cmsPreviewSignedData = new CMSSignedData(previewCMSSignature); // Build BouncyCastle object that is a set of signatures Collection<SignerInformation> previewSigners = cmsPreviewSignedData.getSignerInfos().getSigners(); for (SignerInformation previewSigner : previewSigners) { // build a counter-signature per previewSignature byte[] previewSignatureFromSigner = previewSigner.getSignature(); CMSSignedData cmsCounterSignedData = new CMSSignedData(this.doSign(previewSignatureFromSigner)); cmsPreviewSignedData = this.updateWithCounterSignature(cmsCounterSignedData, cmsPreviewSignedData, previewSigner.getSID()); } return cmsPreviewSignedData.getEncoded(); } catch (Throwable error) { throw new SignerException(error); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESTimeStampSigner.java
License:Open Source License
@Override public byte[] doTimeStampForSignature(byte[] signature) throws SignerException { try {/*from w w w.ja va 2s . c om*/ Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = new CMSSignedData(signature); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); SignerInformation signer = (SignerInformation) it.next(); AttributeFactory attributeFactory = AttributeFactory.getInstance(); ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector(); SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.getCertificateChain(), signer.getSignature(), signaturePolicy, null); unsignedAttributes.add(signedOrUnsignedAttribute.getValue()); AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes); List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>(); vNewSigners.add(SignerInformation.replaceUnsignedAttributes(signer, unsignedAttributesTable)); SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners); CMSSignedData oSignedData = cmsSignedData; cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore); byte[] result = cmsSignedData.getEncoded(); return result; } catch (CMSException ex) { throw new SignerException(ex.getMessage()); } catch (IOException ex) { throw new SignerException(ex.getMessage()); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESTimeStampSigner.java
License:Open Source License
@Override public List<Timestamp> checkTimeStampOnSignature(byte[] signature) { try {//from w w w . jav a 2s.c o m Security.addProvider(new BouncyCastleProvider()); List<Timestamp> listOfTimeStamp = new ArrayList<Timestamp>(); CMSSignedData cmsSignedData = new CMSSignedData(signature); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); AttributeTable unsignedAttributes = signer.getUnsignedAttributes(); Attribute attributeTimeStamp = unsignedAttributes .get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())); if (attributeTimeStamp != null) { TimeStampOperator timeStampOperator = new TimeStampOperator(); byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive() .getEncoded(); TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp)); Timestamp timeStampSigner = new Timestamp(timeStampToken); timeStampOperator.validate(signer.getSignature(), varTimeStamp, null); listOfTimeStamp.add(timeStampSigner); } } return listOfTimeStamp; } catch (CertificateCoreException | IOException | TSPException | CMSException e) { throw new SignerException(e); } }