List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signingCertificateV2
ASN1ObjectIdentifier id_aa_signingCertificateV2
To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signingCertificateV2.
Click Source Link
From source file:es.gob.afirma.applet.CMSInformation.java
License:Open Source License
/** * Obtiene los atributos obligatorios de una firma. * * @param attributes Grupo de atributos opcionales * @param binarySignType Identifica el tipo de firma binaria (CMS o CADES) * @return lista de atributos concatenados. *//*from w ww. j av a2 s . c om*/ private static String getsignedAttributes(final ASN1Set attributes, final int binarySignType) { String attributos = ""; //$NON-NLS-1$ final Enumeration<?> e = attributes.getObjects(); while (e.hasMoreElements()) { final ASN1Sequence a = (ASN1Sequence) e.nextElement(); final ASN1ObjectIdentifier derIden = (ASN1ObjectIdentifier) a.getObjectAt(0); // tipo de contenido de la firma. if (derIden.equals(CMSAttributes.contentType)) { attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.22") + SP //$NON-NLS-1$ + a.getObjectAt(1) + CR; } //Message digest de la firma if (derIden.equals(CMSAttributes.messageDigest)) { attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.43") + CR; //$NON-NLS-1$ } //la fecha de firma. obtenemos y casteamos a algo legible. if (derIden.equals(CMSAttributes.signingTime)) { final ASN1Set time = (ASN1Set) a.getObjectAt(1); final DERUTCTime d = (DERUTCTime) time.getObjectAt(0); Date date = null; try { date = d.getDate(); } catch (final ParseException ex) { Logger.getLogger("es.gob.afirma").warning("No es posible convertir la fecha"); //$NON-NLS-1$ //$NON-NLS-2$ } final SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss"); //$NON-NLS-1$ final String ds = formatter.format(date); attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.39") + SP + ds + CR; //$NON-NLS-1$ } if (binarySignType == BINARY_SIGN_CADES) { //atributo signing certificate v2 if (derIden.equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2)) { attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.40") + CR; //$NON-NLS-1$ } //Politica de firma. if (derIden.equals(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId)) { attributos = attributos + TB + TB + AppletMessages.getString("CMSInformation.41") + CR; //$NON-NLS-1$ } } } return attributos; }
From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java
License:Open Source License
/** Método que genera la parte que contiene la información del * Usuario. Se generan los atributos que se necesitan para generar la firma. * @param cert Certificado del firmante//from www . j a v a2s .c o m * @param datos Datos firmados * @param policy Política de firma * @param messageDigest * @return Los datos necesarios para generar la firma referente a los datos * del usuario. * @throws java.security.NoSuchAlgorithmException * @throws java.io.IOException * @throws CertificateEncodingException */ static ASN1EncodableVector generateSignerInfo(final X509Certificate cert, final String digestAlgorithmName, final byte[] datos, final AdESPolicy policy, final byte[] messageDigest) throws NoSuchAlgorithmException, IOException, CertificateEncodingException { // ALGORITMO DE HUELLA DIGITAL final AlgorithmIdentifier digestAlgorithmOID = SigUtils .makeAlgId(AOAlgorithmID.getOID(digestAlgorithmName)); // // ATRIBUTOS // authenticatedAttributes final ASN1EncodableVector contexExpecific = initContexExpecific(digestAlgorithmName, datos, PKCSObjectIdentifiers.data.getId(), messageDigest); // Serial Number // comentar lo de abajo para version del rfc 3852 contexExpecific.add(new Attribute(RFC4519Style.serialNumber, new DERSet(new DERPrintableString(cert.getSerialNumber().toString())))); if (!"SHA1".equals(AOSignConstants.getDigestAlgorithmName(digestAlgorithmName))) { //$NON-NLS-1$ //********************************************/ //***** La Nueva operatividad esta comentada */ //********************************************/ // INICIO SINGING CERTIFICATE-V2 /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber * CertificateSerialNumber */ final TBSCertificateStructure tbs = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate())); /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial * IssuerSerial OPTIONAL } * Hash ::= OCTET STRING */ final byte[] certHash = MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded()); final ESSCertIDv2[] essCertIDv2 = { new ESSCertIDv2(digestAlgorithmOID, certHash, new IssuerSerial(new GeneralNames(new GeneralName(tbs.getIssuer())), tbs.getSerialNumber())) }; /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId, * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo * OPTIONAL } * CertPolicyId ::= OBJECT IDENTIFIER * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */ final SigningCertificateV2 scv2; if (policy.getPolicyIdentifier() != null) { /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL * } */ scv2 = new SigningCertificateV2(essCertIDv2, getPolicyInformation(policy)); // con // politica } else { scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica } // Secuencia con singningCertificate contexExpecific.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2))); // FIN SINGING CERTIFICATE-V2 } else { // INICIO SINGNING CERTIFICATE /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber * CertificateSerialNumber } */ final TBSCertificateStructure tbs = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate())); final IssuerSerial isuerSerial = new IssuerSerial(new GeneralNames(new GeneralName(tbs.getIssuer())), tbs.getSerialNumber()); /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial * OPTIONAL } * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */ final ESSCertID essCertID = new ESSCertID( MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded()), isuerSerial); /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId, * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo * OPTIONAL } * CertPolicyId ::= OBJECT IDENTIFIER * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */ final SigningCertificate scv; if (policy.getPolicyIdentifier() != null) { /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL * } */ /* * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY * CASTLE NO TIENE DICHO CONSTRUCTOR. */ final ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERSequence(essCertID)); v.add(new DERSequence(getPolicyInformation(policy))); scv = SigningCertificate.getInstance(new DERSequence(v)); // con politica } else { scv = new SigningCertificate(essCertID); // Sin politica } /** id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1) * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16) * id-aa(2) 12 } */ // Secuencia con singningCertificate contexExpecific.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(scv))); } // INICIO SIGPOLICYID ATTRIBUTE if (policy.getPolicyIdentifier() != null) { /* * SigPolicyId ::= OBJECT IDENTIFIER Politica de firma. */ final ASN1ObjectIdentifier doiSigPolicyId = new ASN1ObjectIdentifier( policy.getPolicyIdentifier().toLowerCase().replace("urn:oid:", "")); //$NON-NLS-1$ //$NON-NLS-2$ /* * OtherHashAlgAndValue ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * hashValue OCTET STRING } * */ // Algoritmo para el hash final AlgorithmIdentifier hashid; // si tenemos algoritmo de calculo de hash, lo ponemos if (policy.getPolicyIdentifierHashAlgorithm() != null) { hashid = SigUtils.makeAlgId(AOAlgorithmID .getOID(AOSignConstants.getDigestAlgorithmName(policy.getPolicyIdentifierHashAlgorithm()))); } // si no tenemos, ponemos el algoritmo de firma. else { hashid = digestAlgorithmOID; } // hash del documento, descifrado en b64 final byte[] hashed; if (policy.getPolicyIdentifierHash() != null) { hashed = Base64.decode(policy.getPolicyIdentifierHash()); } else { hashed = new byte[] { 0 }; } final DigestInfo otherHashAlgAndValue = new DigestInfo(hashid, hashed); /* * SigPolicyQualifierInfo ::= SEQUENCE { * SigPolicyQualifierId SigPolicyQualifierId, * SigQualifier ANY DEFINED BY policyQualifierId } */ SigPolicyQualifierInfo spqInfo = null; if (policy.getPolicyQualifier() != null) { spqInfo = new SigPolicyQualifierInfo(policy.getPolicyQualifier().toString()); } /* * SignaturePolicyId ::= SEQUENCE { * sigPolicyId SigPolicyId, * sigPolicyHash SigPolicyHash, * sigPolicyQualifiers SEQUENCE SIZE (1..MAX) OF * SigPolicyQualifierInfo OPTIONAL} * */ final ASN1EncodableVector v = new ASN1EncodableVector(); // sigPolicyId v.add(doiSigPolicyId); // sigPolicyHash v.add(otherHashAlgAndValue.toASN1Primitive()); // como sequence // sigPolicyQualifiers if (spqInfo != null) { v.add(spqInfo.toASN1Primitive()); } final DERSequence ds = new DERSequence(v); // Secuencia con singningCertificate contexExpecific.add( new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId, new DERSet(ds.toASN1Primitive()))); // FIN SIGPOLICYID ATTRIBUTE } return contexExpecific; }
From source file:es.gob.afirma.signers.cades.CAdESUtils.java
License:Open Source License
/** Genera una estructura <i>SigningCertificateV2</i> según RFC 5035: * * <pre>/* ww w .j a v a2s . c om*/ * id-aa-signingCertificateV2 OBJECT IDENTIFIER ::= { iso(1) * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) * smime(16) id-aa(2) 47 * } * * SigningCertificateV2 ::= SEQUENCE { * certs SEQUENCE OF ESSCertIDv2, * policies SEQUENCE OF PolicyInformation OPTIONAL * } * </pre> * * @param cert Certificado del firmante * @param digestAlgorithmName Nombre del algoritmo de huella digital a usar * @param policy Política de firma * @return Estructura <i>SigningCertificateV2</i> según RFC 5035 * @throws CertificateEncodingException Si el certificado proporcionado no es válido * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella indicado * @throws IOException Si hay errores en el tratamiento de datos */ private static Attribute getSigningCertificateV2(final X509Certificate cert, final String digestAlgorithmName, final AdESPolicy policy) throws CertificateEncodingException, NoSuchAlgorithmException, IOException { // ALGORITMO DE HUELLA DIGITAL final AlgorithmIdentifier digestAlgorithmOID = SigUtils .makeAlgId(AOAlgorithmID.getOID(digestAlgorithmName)); // INICIO SINGING CERTIFICATE-V2 /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber * CertificateSerialNumber */ final GeneralNames gns = new GeneralNames( new GeneralName(X500Name.getInstance(cert.getIssuerX500Principal().getEncoded()))); final IssuerSerial isuerSerial = new IssuerSerial(gns, cert.getSerialNumber()); /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial * IssuerSerial OPTIONAL } * Hash ::= OCTET STRING */ final byte[] certHash = MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded()); final ESSCertIDv2[] essCertIDv2 = { new ESSCertIDv2(digestAlgorithmOID, certHash, isuerSerial) }; /** PolicyInformation ::= SEQUENCE { * policyIdentifier CertPolicyId, * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo OPTIONAL * } * CertPolicyId ::= OBJECT IDENTIFIER * PolicyQualifierInfo ::= SEQUENCE { * policyQualifierId PolicyQualifierId, * qualifier ANY DEFINED BY policyQualifierId * } */ final SigningCertificateV2 scv2; if (policy != null && policy.getPolicyIdentifier() != null) { /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL * } */ scv2 = new SigningCertificateV2(essCertIDv2, getPolicyInformation(policy)); // con politica } else { scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica } return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2)); }
From source file:es.gob.afirma.signers.cades.CAdESValidator.java
License:Open Source License
/** Verifica que los <code>SignerInfos</code> tengan el parámetro * que identifica que los datos son de tipo CAdES. * @param si <code>SignerInfo</code> para la verificación del parámetro * adecuado./*from w w w . j av a 2s .c o m*/ * @return si contiene el parámetro. */ private static boolean verifySignerInfo(final SignerInfo si) { boolean isSignerValid = false; final ASN1Set attrib = si.getAuthenticatedAttributes(); final Enumeration<?> e = attrib.getObjects(); Attribute atribute; while (e.hasMoreElements()) { final ASN1Sequence seq = (ASN1Sequence) e.nextElement(); atribute = new Attribute((ASN1ObjectIdentifier) seq.getObjectAt(0), (ASN1Set) seq.getObjectAt(1)); // Si tiene la politica es CADES. if (atribute.getAttrType().equals(PKCSObjectIdentifiers.id_aa_signingCertificate) || atribute.getAttrType().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2)) { isSignerValid = true; } } return isSignerValid; }
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESLevelBaselineB.java
License:Open Source License
private void addSigningCertificateAttribute(final SignatureParameters parameters, final ASN1EncodableVector signedAttributes) throws DSSException { final DigestAlgorithm digestAlgorithm = parameters.getDigestAlgorithm(); final X509Certificate signingCertificate = parameters.getSigningCertificate(); final byte[] encoded = DSSUtils.getEncoded(signingCertificate); final byte[] certHash = DSSUtils.digest(digestAlgorithm, encoded); if (LOG.isDebugEnabled()) { LOG.debug("Adding Certificate Hash {} with algorithm {}", DSSUtils.encodeHexString(certHash), digestAlgorithm.getName()); }/*from w ww . j a v a 2 s . co m*/ final IssuerSerial issuerSerial = DSSUtils.getIssuerSerial(signingCertificate); if (digestAlgorithm == DigestAlgorithm.SHA1) { final ESSCertID essCertId = new ESSCertID(certHash, issuerSerial); final SigningCertificate cadesSigningCertificate = new SigningCertificate(essCertId); final DERSet attrValues = new DERSet(cadesSigningCertificate); final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, attrValues); signedAttributes.add(attribute); } else { final ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(digestAlgorithm.getAlgorithmIdentifier(), certHash, issuerSerial); final ESSCertIDv2[] essCertIDv2Array = new ESSCertIDv2[] { essCertIDv2 }; final SigningCertificateV2 cadesSigningCertificateV2 = new SigningCertificateV2(essCertIDv2Array); final DERSet attrValues = new DERSet(cadesSigningCertificateV2); final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, attrValues); signedAttributes.add(attribute); } }
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileBES.java
License:Open Source License
private Attribute makeSigningCertificateAttribute(SignatureParameters parameters) { try {/*from w w w .j a va 2 s . c o m*/ MessageDigest dig = MessageDigest.getInstance(parameters.getDigestAlgorithm().getName(), new BouncyCastleProvider()); byte[] certHash = dig.digest(parameters.getSigningCertificate().getEncoded()); if (parameters.getDigestAlgorithm() == DigestAlgorithm.SHA1) { SigningCertificate sc = new SigningCertificate(new ESSCertID(certHash)); return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(sc)); } else { ESSCertIDv2 essCert = new ESSCertIDv2( new AlgorithmIdentifier(parameters.getDigestAlgorithm().getOid()), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new ESSCertIDv2[] { essCert }); return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2)); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (CertificateException e) { throw new RuntimeException(e); } }
From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java
License:Open Source License
/** * ETSI TS 101 733 V2.2.1 (2013-04)<p/> * 5.6.3 Signature Verification Process<p/> * TODO (Bob 28.05.2014) The position of the signing certificate must be clarified * ...the public key from the first certificate identified in the sequence of certificate identifiers from SigningCertificate shall be the key used to verify the digital * signature./*from www .j a va 2 s . c o m*/ * * @return */ @Override public CandidatesForSigningCertificate getCandidatesForSigningCertificate() { if (candidatesForSigningCertificate != null) { return candidatesForSigningCertificate; } LOG.debug("--> Searching the signing certificate..."); candidatesForSigningCertificate = new CandidatesForSigningCertificate(); final Collection<CertificateToken> keyInfoCertificates = getCertificateSource().getKeyInfoCertificates(); final SignerId sid = signerInformation.getSID(); for (final CertificateToken certificateToken : keyInfoCertificates) { final SigningCertificateValidity signingCertificateValidity = new SigningCertificateValidity( certificateToken); candidatesForSigningCertificate.add(signingCertificateValidity); final X509CertificateHolder x509CertificateHolder = DSSUtils.getX509CertificateHolder(certificateToken); final boolean match = sid.match(x509CertificateHolder); if (match) { this.signingCertificateValidity = signingCertificateValidity; break; } } if (signingCertificateValidity == null) { LOG.debug("--> Signing certificate not found: " + sid); return candidatesForSigningCertificate; } final IssuerSerial signingTokenIssuerSerial = DSSUtils .getIssuerSerial(signingCertificateValidity.getCertificateToken()); final BigInteger signingTokenSerialNumber = signingTokenIssuerSerial.getSerial().getValue(); final GeneralNames signingTokenIssuerName = signingTokenIssuerSerial.getIssuer(); final AttributeTable signedAttributes = getSignedAttributes(signerInformation); final Attribute signingCertificateAttributeV1 = signedAttributes .get(PKCSObjectIdentifiers.id_aa_signingCertificate); if (signingCertificateAttributeV1 != null) { signingCertificateValidity.setAttributePresent(true); verifySigningCertificateV1(signingTokenSerialNumber, signingTokenIssuerName, signingCertificateAttributeV1); return candidatesForSigningCertificate; } final Attribute signingCertificateAttributeV2 = signedAttributes .get(PKCSObjectIdentifiers.id_aa_signingCertificateV2); if (signingCertificateAttributeV2 != null) { signingCertificateValidity.setAttributePresent(true); verifySigningCertificateV2(signingTokenSerialNumber, signingTokenIssuerName, signingCertificateAttributeV2); return candidatesForSigningCertificate; } LOG.debug("--> There is no signed reference to the signing certificate: " + signingCertificateValidity.getCertificateToken().getAbbreviation()); return candidatesForSigningCertificate; }
From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java
License:Open Source License
public boolean isDataForSignatureLevelPresent(final SignatureLevel signatureLevel) { /**/*from w ww . j a v a2s . c o m*/ * This list contains the detail information collected during the check. It is reset for each call. */ info = new ArrayList<String>(); final AttributeTable unsignedAttributes = getUnsignedAttributes(signerInformation); final AttributeTable signedAttributes = getSignedAttributes(signerInformation); boolean dataForProfilePresent = true; switch (signatureLevel) { case CAdES_BASELINE_LTA: dataForProfilePresent = unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV3) != null; // break omitted purposely case CAdES_101733_A: if (signatureLevel != SignatureLevel.CAdES_BASELINE_LTA) { dataForProfilePresent &= unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV2) != null; } // break omitted purposely case CAdES_BASELINE_LT: final Store certificateStore = cmsSignedData.getCertificates(); final Store crlStore = cmsSignedData.getCRLs(); final Store ocspStore = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response); final Store ocspBasicStore = cmsSignedData .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic); final int certificateStoreSize = certificateStore.getMatches(null).size(); final int crlStoreSize = crlStore.getMatches(null).size(); info.add("CRL founds: " + crlStoreSize); final int ocspStoreSize = ocspStore.getMatches(null).size(); info.add("OCSP founds: " + ocspStoreSize); final int basicOcspStoreSize = ocspBasicStore.getMatches(null).size(); info.add("BasicOCSP founds: " + basicOcspStoreSize); final int ltInfoSize = crlStoreSize + ocspStoreSize + basicOcspStoreSize; dataForProfilePresent &= (ltInfoSize > 0); // break omitted purposely case CAdES_101733_X: if (!signatureLevel.toString().contains("BASELINE")) { dataForProfilePresent &= (unsignedAttributes .get(PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp) != null || unsignedAttributes.get(PKCSObjectIdentifiers.id_aa_ets_escTimeStamp) != null); } // break omitted purposely case CAdES_101733_C: if (!signatureLevel.toString().contains("BASELINE")) { dataForProfilePresent &= unsignedAttributes .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs) != null; dataForProfilePresent &= isDataForSignatureLevelPresent(SignatureLevel.CAdES_BASELINE_T); } // break omitted purposely case CAdES_BASELINE_T: dataForProfilePresent &= unsignedAttributes .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken) != null; // break omitted purposely case CAdES_BASELINE_B: dataForProfilePresent &= ((signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificate) != null) || (signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) != null)); break; // break placed purposely case CMS: dataForProfilePresent = true; break; default: throw new IllegalArgumentException("Unknown level " + signatureLevel); } return dataForProfilePresent; }
From source file:it.trento.comune.j4sign.cms.ExternalSignatureSignerInfoGenerator.java
License:Open Source License
/** * Calculates the bytes to be externally signed (digested and encrypted with * signer private key).<br>/*from ww w.j av a2s. co m*/ * The bytes are the DER encoding of authenticated attributes; the current * implementation includes this attributes: * <ul> * <li><b>content Type</b></li> of the provided content. * <li><b>message Digest</b></li> of the content, calculated in this method * with the algorithm specified in the class constructor. * <li><b>signing Time</b>. Note that time (internally stored as UTC) should * be presented to the signer BEFORE applying the external signature * procedure.<br> * This time has not to be confused with a thirdy part (Certification * Authority) certified timestamp ("Marcatura Temporale" in italian * terminology); for the italian digital signature law this attribute is not * mandatory and could be omitted. Nevertheless, the italian law states also * that the signature is valid if the certificate is not expired nor * suspended at the time of signature. So an indication of signing time is * (in my opinion) however useful.</li> * </ul> * * * @param contentType * the <code>org.bouncycastle.asn1.DERObjectIdentifier</code> of * the content. * @param hash * the content hash. * @param sigProvider * the cryptographic provider to use for calculating the digest * of the content. * @return a <code>byte[]</code> containing the raw bytes to be signed. * @throws IOException * @throws SignatureException * @throws InvalidKeyException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateEncodingException * @throws CMSException */ public byte[] getBytesToSign(DERObjectIdentifier contentType, byte[] hash, Date signingDate, String sigProvider) throws IOException, SignatureException, InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException, CertificateEncodingException, CMSException { if (signingDate == null) signingDate = new Date(); AttributeTable attr = this.getSignedAttributes(); if (attr != null) { ASN1EncodableVector v = new ASN1EncodableVector(); if (attr.get(CMSAttributes.contentType) == null) { v.add(new Attribute(CMSAttributes.contentType, new DERSet(contentType))); } else { v.add(attr.get(CMSAttributes.contentType)); } if (attr.get(CMSAttributes.signingTime) == null) { v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(signingDate)))); } else { v.add(attr.get(CMSAttributes.signingTime)); } v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash)))); // CAdES! v.add(buildSigningCertificateV2Attribute(sigProvider)); Hashtable ats = attr.toHashtable(); ats.remove(CMSAttributes.contentType); ats.remove(CMSAttributes.signingTime); ats.remove(CMSAttributes.messageDigest); ats.remove(PKCSObjectIdentifiers.id_aa_signingCertificateV2); Iterator it = ats.values().iterator(); while (it.hasNext()) { v.add(Attribute.getInstance(it.next())); } signedAttr = new DERSet(v); } else { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new Attribute(CMSAttributes.contentType, new DERSet(contentType))); v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(signingDate)))); v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash)))); // CAdES! v.add(buildSigningCertificateV2Attribute(sigProvider)); signedAttr = new DERSet(v); } attr = this.getUnsignedAttributes(); if (attr != null) { Hashtable ats = attr.toHashtable(); Iterator it = ats.values().iterator(); ASN1EncodableVector v = new ASN1EncodableVector(); while (it.hasNext()) { v.add(Attribute.getInstance(it.next())); } unsignedAttr = new DERSet(v); } // // sig must be composed from the DER encoding. // ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(signedAttr); return bOut.toByteArray(); }
From source file:it.trento.comune.j4sign.cms.ExternalSignatureSignerInfoGenerator.java
License:Open Source License
/** * Builds the SignerCertificateV2 attribute according to RFC2634(Enhanced * Security Services (ESS)) + RFC5035(ESS Update: AddingCertID Algorithm * Agility).<br>//from w ww . j a v a 2s . co m * This signed attribute is mandatory for CAdES-BES (ETSI TS 101 733) * compliancy. * * @param sigProvider * the provider to use for digest calculation. * @return the SignerCertificateV2 attribute calculated from to the current * certificate and digest algorithm. * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws CertificateEncodingException * @throws IOException */ private Attribute buildSigningCertificateV2Attribute(String sigProvider) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, IOException { X509Certificate cert = this.getCertificate(); MessageDigest dig = MessageDigest.getInstance(this.getDigestAlgOID(), sigProvider); byte[] certHash = dig.digest(cert.getEncoded()); // ricavo issuerandserialnumber (ID) del certificato // byte[] encodedCert = this.cert.getEncoded(); // ASN1InputStream ais = new ASN1InputStream(encodedCert); // DERObject derObj = ais.readObject(); // ASN1Sequence asn1Seq = (ASN1Sequence) derObj; // ais.close(); // X509CertificateStructure x509CStructure = new // X509CertificateStructure( // asn1Seq); // X509Name x509Name = x509CStructure.getIssuer(); // DERInteger serialNum = x509CStructure.getSerialNumber(); // GeneralName generalName = new GeneralName(x509Name); // GeneralNames generalNames = new GeneralNames(generalName); // ROB: more directly JcaX509CertificateHolder holder = new JcaX509CertificateHolder(cert); X500Name x500name = holder.getIssuer(); GeneralName generalName = new GeneralName(x500name); GeneralNames generalNames = new GeneralNames(generalName); DERInteger serialNum = new DERInteger(holder.getSerialNumber()); IssuerSerial issuerserial = new IssuerSerial(generalNames, serialNum); // --- ESSCertIDv2 essCert = new ESSCertIDv2(new AlgorithmIdentifier(getDigestAlgOID()), certHash, issuerserial); // ESSCertIDv2 essCert = new ESSCertIDv2(new AlgorithmIdentifier( // getDigestAlgOID()), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new ESSCertIDv2[] { essCert }); return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2)); }