List of usage examples for org.bouncycastle.asn1 ASN1Set getObjects
public Enumeration getObjects()
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java
License:Open Source License
/** * A validao se basea apenas em assinaturas com um assinante apenas. * Valida apenas com o contedo do tipo DATA: OID ContentType * 1.2.840.113549.1.9.3 = OID Data 1.2.840.113549.1.7.1 * * @param content//from ww w . ja va 2 s . co m * @param signed * @return * @params content Necessrio informar apenas se o pacote PKCS7 NO for do * tipo ATTACHED. Caso seja do tipo attached, este parmetro ser * substituido pelo contedo do pacote PKCS7. * @params signed Valor em bytes do pacote PKCS7, como por exemplo o * contedo de um arquivo ".p7s". No a assinatura pura como no caso do * PKCS1. TODO: Implementar validao de co-assinaturas */ @Override public boolean check(byte[] content, byte[] signed) { CMSSignedData signedData = null; PublicKey publicKey = null; try { if (content == null) { signedData = new CMSSignedData(signed); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), signed); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a PKCS7 package", exception); } SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); /* * Retirando o Certificado Digital e a chave Pblica da assinatura */ try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException ex) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", ex); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } AttributeTable signedAttributes = signerInformation.getSignedAttributes(); if (signedAttributes == null) { throw new SignerException("Package PKCS7 without signed attributes"); } // Validar a poltica org.bouncycastle.asn1.cms.Attribute signaturePolicyIdentifierAttribute = signedAttributes .get(new DERObjectIdentifier((new SignaturePolicyIdentifier()).getOID())); if (signaturePolicyIdentifierAttribute != null) { ASN1Set valueAttribute = signaturePolicyIdentifierAttribute.getAttrValues(); for (Enumeration<DERSequence> iterator = valueAttribute.getObjects(); iterator.hasMoreElements();) { DERSequence sequence = iterator.nextElement(); DERObjectIdentifier policyIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0); String policyOID = policyIdentifier.getId(); SignaturePolicy policy = SignaturePolicyFactory.getInstance().factory(policyOID); if (policy != null) { policy.validate(content, signed); } else { LOGGER.log(Level.WARNING, "N\u00e3o existe validador para a pol\u00edtica {0}", policyOID); } } } else { throw new SignerException("ICP-Brasil invalid format. There is not policy signature."); } return true; }
From source file:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java
License:Open Source License
@Override public boolean verify() { try {/*from ww w . 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:com.guardtime.asn1.CertToken.java
License:Apache License
/** * Class constructor.//from www. ja va2 s . c o m * * @param obj ASN.1 representation of certification token. */ CertToken(ASN1Encodable obj) throws Asn1FormatException { try { certToken = Asn1CertToken.getInstance(obj); version = certToken.getVersion().getValue().intValue(); if (version != VERSION) { throw new Asn1FormatException("invalid cert token version: " + version); } history = certToken.getHistory().getOctets(); publishedData = new PublishedData(certToken.getPublishedData()); ASN1Set pubRefs = certToken.getPubReference(); if (pubRefs != null) { pubReferences = new ArrayList(); Enumeration e = pubRefs.getObjects(); while (e.hasMoreElements()) { Object nextElement = e.nextElement(); if (!(nextElement instanceof DERNull)) { pubReferences.add(((ASN1OctetString) nextElement).getOctets()); } } } Extensions exts = certToken.getExtensions(); if (exts != null) { // check for critical extensions Asn1Util.checkExtensions(exts); extensions = exts.getEncoded(ASN1Encoding.DER); } } catch (Asn1FormatException e) { throw e; } catch (Exception e) { throw new Asn1FormatException("cert token has invalid format", e); } }
From source file:com.guardtime.asn1.SignatureInfo.java
License:Apache License
/** * Class constructor.//from w w w. ja v a 2 s . co m * * @param obj ASN.1 representation of time signature. * * @throws Asn1FormatException if provided ASN.1 object has invalid format. */ SignatureInfo(ASN1Encodable obj) throws Asn1FormatException { try { signatureInfo = Asn1SignatureInfo.getInstance(obj); // Check that signature algorithm and value are present // (NullPointerException will be thrown otherwise) signatureAlgorithm = signatureInfo.getSignatureAlgorithm().getAlgorithm().getId(); signatureValue = signatureInfo.getSignatureValue().getOctets(); ASN1Set pkiRefs = signatureInfo.getPkiReferences(); if (pkiRefs != null) { pkiReferences = new ArrayList(); Enumeration e = pkiRefs.getObjects(); while (e.hasMoreElements()) { Object nextElement = e.nextElement(); if (!(nextElement instanceof DERNull)) { pkiReferences.add(((ASN1OctetString) nextElement).getOctets()); } } } } catch (Exception e) { throw new Asn1FormatException("signature info has invalid format", e); } }
From source file:com.guardtime.asn1.TimeSignature.java
License:Apache License
/** * Class constructor.// w w w.ja v a 2s. c o m * * @param obj ASN.1 representation of time signature. * * @throws Asn1FormatException if provided ASN.1 object has invalid format. */ TimeSignature(ASN1Encodable obj) throws Asn1FormatException { try { timeSignature = Asn1TimeSignature.getInstance(obj); // Check that location and history chains are present // (NullPointerException will be thrown otherwise) location = timeSignature.getLocation().getOctets(); history = timeSignature.getHistory().getOctets(); publishedData = new PublishedData(timeSignature.getPublishedData()); Asn1SignatureInfo pkSig = timeSignature.getPkSignature(); if (pkSig != null) { pkSignature = new SignatureInfo(pkSig); } ASN1Set pubRefs = timeSignature.getPubReferences(); if (pubRefs != null) { pubReferences = new ArrayList(); Enumeration e = pubRefs.getObjects(); while (e.hasMoreElements()) { Object nextElement = e.nextElement(); if (!(nextElement instanceof DERNull)) { pubReferences.add(((ASN1OctetString) nextElement).getOctets()); } } } } catch (Asn1FormatException e) { throw e; } catch (Exception e) { throw new Asn1FormatException("time signature has invalid format", e); } }
From source file:es.gob.afirma.applet.CMSInformation.java
License:Open Source License
/** * Obtiene la información de diferentes tipos de formatos. * @param doj Etiqueta ASN.1 de la que se obtienen los datos. * @param envelopeType Tipo de formato: * <li>0: EnvelopedData</li> * <li>1: AuthenticatedData</li> * <li>2: AuthEnvelopedData</li> * <li>3: SignedAndEnvelopedData</li> * <li>4: SignedData</li>/*from www . j a v a 2s. com*/ * <li>5: Encrypted</li> * @param tipoDetalle Tipo de datos (literal) * @param signBinaryType Tipo de firmado binario (CADES o CMS) * @return Representación de los datos. */ private static String extractData(final ASN1TaggedObject doj, final int envelopeType, final String tipoDetalle, final int signBinaryType) { String detalle = ""; //$NON-NLS-1$ detalle = detalle + tipoDetalle + CR; ASN1Set rins = null; EncryptedContentInfo encryptedContentInfo = null; ASN1Set unprotectedAttrs = null; ASN1Integer version = null; AlgorithmIdentifier aid = null; ContentInfo ci = null; ASN1Set authAttrs = null; ASN1Set ds = null; ASN1Set signerInfosSd = null; switch (envelopeType) { case TYPE_ENVELOPED_DATA: final EnvelopedData enveloped = EnvelopedData.getInstance(doj.getObject()); version = enveloped.getVersion(); rins = enveloped.getRecipientInfos(); encryptedContentInfo = enveloped.getEncryptedContentInfo(); unprotectedAttrs = enveloped.getUnprotectedAttrs(); break; case TYPE_AUTHENTICATED_DATA: final AuthenticatedData authenticated = AuthenticatedData.getInstance(doj.getObject()); version = authenticated.getVersion(); rins = authenticated.getRecipientInfos(); aid = authenticated.getMacAlgorithm(); ci = authenticated.getEncapsulatedContentInfo(); authAttrs = authenticated.getAuthAttrs(); unprotectedAttrs = authenticated.getUnauthAttrs(); break; case TYPE_AUTHENTICATED_ENVELOPED_DATA: final AuthEnvelopedData authEnveloped = AuthEnvelopedData.getInstance(doj.getObject()); version = authEnveloped.getVersion(); rins = authEnveloped.getRecipientInfos(); encryptedContentInfo = authEnveloped.getAuthEncryptedContentInfo(); authAttrs = authEnveloped.getAuthAttrs(); unprotectedAttrs = authEnveloped.getUnauthAttrs(); break; case TYPE_SIGNED_ENVELOPED_DATA: final SignedAndEnvelopedData signedEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject()); version = signedEnv.getVersion(); rins = signedEnv.getRecipientInfos(); encryptedContentInfo = signedEnv.getEncryptedContentInfo(); signerInfosSd = signedEnv.getSignerInfos(); break; case TYPE_SIGNED_DATA: final SignedData signed = SignedData.getInstance(doj.getObject()); version = signed.getVersion(); ds = signed.getDigestAlgorithms(); ci = signed.getEncapContentInfo(); signerInfosSd = signed.getSignerInfos(); break; case TYPE_ENCRYPTED_DATA: final ASN1Sequence encrypted = (ASN1Sequence) doj.getObject(); version = ASN1Integer.getInstance(encrypted.getObjectAt(0)); encryptedContentInfo = EncryptedContentInfo.getInstance(encrypted.getObjectAt(1)); if (encrypted.size() == 3) { unprotectedAttrs = (ASN1Set) encrypted.getObjectAt(2); } break; default: throw new IllegalArgumentException("Tipo de sobre no soportado: " + envelopeType); //$NON-NLS-1$ } //obtenemos la version detalle = detalle + AppletMessages.getString("CMSInformation.1") + SP + version + CR; //$NON-NLS-1$ //recipientInfo if (rins != null) { if (envelopeType != TYPE_SIGNED_DATA && envelopeType != TYPE_ENCRYPTED_DATA && rins.size() > 0) { detalle = detalle + AppletMessages.getString("CMSInformation.13") + CR; //$NON-NLS-1$ } for (int i = 0; i < rins.size(); i++) { final KeyTransRecipientInfo kti = KeyTransRecipientInfo .getInstance(RecipientInfo.getInstance(rins.getObjectAt(i)).getInfo()); detalle = detalle + AppletMessages.getString("CMSInformation.14") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$ final AlgorithmIdentifier diAlg = kti.getKeyEncryptionAlgorithm(); //issuer y serial final IssuerAndSerialNumber iss = (IssuerAndSerialNumber) SignerIdentifier .getInstance(kti.getRecipientIdentifier().getId()).getId(); detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$ + iss.getName().toString() + CR; detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$ + CR; // el algoritmo de cifrado de los datos AOCipherAlgorithm algorithm = null; final AOCipherAlgorithm[] algos = AOCipherAlgorithm.values(); // obtenemos el algoritmo usado para cifrar la pass for (final AOCipherAlgorithm algo : algos) { if (algo.getOid().equals(diAlg.getAlgorithm().toString())) { algorithm = algo; } } if (algorithm != null) { detalle = detalle + TB + AppletMessages.getString("CMSInformation.17") + SP //$NON-NLS-1$ + algorithm.getName() + CR; } else { detalle = detalle + TB + AppletMessages.getString("CMSInformation.18") + SP //$NON-NLS-1$ + diAlg.getAlgorithm() + CR; } } } if (envelopeType == TYPE_ENVELOPED_DATA || envelopeType == TYPE_ENCRYPTED_DATA) { //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); } else if (envelopeType == TYPE_AUTHENTICATED_DATA && aid != null && ci != null) { // mac algorithm detalle = detalle + AppletMessages.getString("CMSInformation.20") + SP + aid.getAlgorithm() + CR; //$NON-NLS-1$ //digestAlgorithm final ASN1Sequence seq = (ASN1Sequence) doj.getObject(); final ASN1TaggedObject da = (ASN1TaggedObject) seq.getObjectAt(4); final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObject()); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$ detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs); } else if (envelopeType == TYPE_AUTHENTICATED_ENVELOPED_DATA) { detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs); } else if (envelopeType == TYPE_SIGNED_ENVELOPED_DATA) { //algoritmo de firma final ASN1Sequence seq = (ASN1Sequence) doj.getObject(); final ASN1Set da = (ASN1Set) seq.getObjectAt(2); final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObjectAt(0)); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); } else if (envelopeType == TYPE_SIGNED_DATA && ci != null && ds != null) { //algoritmo de firma final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(ds.getObjectAt(0)); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$ } //obtenemos lo atributos opcionales if (envelopeType != TYPE_SIGNED_ENVELOPED_DATA) { if (unprotectedAttrs == null) { detalle = detalle + AppletMessages.getString("CMSInformation.28") + CR; //$NON-NLS-1$ } else { final String atributos = getUnSignedAttributes(unprotectedAttrs.getObjects()); detalle = detalle + AppletMessages.getString("CMSInformation.29") + CR; //$NON-NLS-1$ detalle = detalle + atributos; } } else if ((envelopeType == TYPE_SIGNED_ENVELOPED_DATA || envelopeType == TYPE_SIGNED_DATA) && signerInfosSd != null) { //obtenemos el(los) firmate(s) if (signerInfosSd.size() > 0) { detalle = detalle + AppletMessages.getString("CMSInformation.30") + CR; //$NON-NLS-1$ } for (int i = 0; i < signerInfosSd.size(); i++) { final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i)); detalle = detalle + AppletMessages.getString("CMSInformation.31") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$ // version detalle = detalle + TB + AppletMessages.getString("CMSInformation.1") + SP + si.getVersion() + CR; //$NON-NLS-1$ //signerIdentifier final SignerIdentifier sident = si.getSID(); final IssuerAndSerialNumber iss = IssuerAndSerialNumber.getInstance(sident.getId()); detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$ + iss.getName().toString() + CR; detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$ + CR; //digestAlgorithm final AlgorithmIdentifier algId = si.getDigestAlgorithm(); detalle = detalle + TB + AppletMessages.getString("CMSInformation.35") + SP + algId.getAlgorithm() //$NON-NLS-1$ + CR; //obtenemos lo atributos obligatorios final ASN1Set sa = si.getAuthenticatedAttributes(); String satributes = ""; //$NON-NLS-1$ if (sa != null) { satributes = getsignedAttributes(sa, signBinaryType); } detalle = detalle + TB + AppletMessages.getString("CMSInformation.36") + CR; //$NON-NLS-1$ detalle = detalle + satributes; } } return detalle; }
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 w w.ja va2 s. co m 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.cms.CoSignerEnveloped.java
License:Open Source License
/** Constructor de la clase. Se crea una cofirma a partir de los datos del * firmante, el archivo que se firma y del archivo que contiene las firmas. * @param parameters parámetros necesarios que contienen tanto la firma del * archivo a firmar como los datos del firmante. * @param signerCertificateChain Cadena de certificados del firmante. * @param sign Archivo que contiene las firmas. * @param dataType Identifica el tipo del contenido a firmar. * @param keyEntry Clave privada del firmante. * @param atrib Atributos firmados opcion ales. * @param uatrib Atributos no autenticados firmados opcionales. * @param messageDigest Huella digital a aplicar en la firma. * @return El archivo de firmas con la nueva firma. * @throws java.io.IOException Si ocurre algún problema leyendo o escribiendo los * datos/* w ww . j av a 2s .c o m*/ * @throws java.security.NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella * digital * @throws java.security.cert.CertificateException Si se produce alguna excepción con los certificados de * firma. */ byte[] coSigner(final P7ContentSignerParameters parameters, final X509Certificate[] signerCertificateChain, final byte[] sign, final String dataType, final PrivateKeyEntry keyEntry, final Map<String, byte[]> atrib, final Map<String, byte[]> uatrib, final byte[] messageDigest) throws IOException, NoSuchAlgorithmException, CertificateException { final ASN1InputStream is = new ASN1InputStream(sign); // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID signedAndEnvelopedData e.nextElement(); // Contenido de signedAndEnvelopedData final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject();// contenido // del // signedAndEnvelopedData final SignedAndEnvelopedData sd = new SignedAndEnvelopedData(contentSignedData); // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } if (signerCertificateChain.length != 0) { final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>(); for (final X509Certificate element : signerCertificateChain) { ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded()))); } certificates = SigUtils.fillRestCerts(ce, vCertsSig); } // buscamos que timo de algoritmo es y lo codificamos con su OID final String signatureAlgorithm = parameters.getSignatureAlgorithm(); final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm); final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); // Identificador del firmante ISSUER AND SERIAL-NUMBER final TBSCertificateStructure tbs = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate())); final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()), tbs.getSerialNumber().getValue()); final SignerIdentifier identifier = new SignerIdentifier(encSid); // // ATRIBUTOS // atributos firmados ASN1Set signedAttr = null; if (messageDigest == null) { signedAttr = generateSignerInfo(digestAlgorithm, parameters.getContent(), dataType, atrib); } else { signedAttr = generateSignerInfoFromHash(signerCertificateChain[0], messageDigest, dataType, atrib); } // atributos no firmados. final ASN1Set unSignedAttr = generateUnsignerInfo(uatrib); // // FIN ATRIBUTOS // digEncryptionAlgorithm final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$ // 5. SIGNERINFO // raiz de la secuencia de SignerInfo // Obtenemos los signerInfos del signedAndEnvelopedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // introducimos los SignerInfos Existentes final ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // introducimos el nuevo SignerInfo del firmante actual. for (int i = 0; i < signerInfosSd.size(); i++) { final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i)); signerInfos.add(si); } final ASN1OctetString sign2; try { sign2 = firma(signatureAlgorithm, keyEntry); } catch (final Exception ex) { throw new IOException("Error al generar la firma: " + ex, ex); //$NON-NLS-1$ } // Creamos los signerInfos del signedAndEnvelopedData signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, unSignedAttr)); // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(), sd.getEncryptedContentInfo(), certificates, null, new DERSet(signerInfos)// unsignedAttr )).getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cms.CoSignerEnveloped.java
License:Open Source License
/** Constructor de la clase. Se crea una cofirma a partir de los datos del * firmante y el archivo que se firma./*from ww w .j a v a2 s . c o m*/ * @param signatureAlgorithm * Algoritmo para la firma * @param signerCertificateChain * Cadena de certificados para la construccion de los parametros * de firma. * @param sign * Archivo que contiene las firmas. * @param dataType * Identifica el tipo del contenido a firmar. * @param keyEntry * Clave privada del firmante. * @param atrib * Atributos firmados adicionales. * @param uatrib * Atributos no firmados adicionales. * @param messageDigest * Hash a aplicar en la firma. * @return El archivo de firmas con la nueva firma. * @throws java.io.IOException * Si ocurre algún problema leyendo o escribiendo los * datos * @throws java.security.NoSuchAlgorithmException * Si no se soporta alguno de los algoritmos de firma o huella * digital * @throws java.security.cert.CertificateException * Si se produce alguna excepción con los certificados de * firma. */ byte[] coSigner(final String signatureAlgorithm, final X509Certificate[] signerCertificateChain, final byte[] sign, final String dataType, final PrivateKeyEntry keyEntry, final Map<String, byte[]> atrib, final Map<String, byte[]> uatrib, final byte[] messageDigest) throws IOException, NoSuchAlgorithmException, CertificateException { final ASN1InputStream is = new ASN1InputStream(sign); // LEEMOS EL FICHERO QUE NOS INTRODUCEN ASN1Sequence dsq = null; dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID signedAndEnvelopedData e.nextElement(); // Contenido de signedAndEnvelopedData final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject();// contenido // del // signedAndEnvelopedData final SignedAndEnvelopedData sd = new SignedAndEnvelopedData(contentSignedData); byte[] md = messageDigest != null ? messageDigest.clone() : null; // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } if (signerCertificateChain.length != 0) { final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>(); for (final X509Certificate element : signerCertificateChain) { ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded()))); } certificates = SigUtils.fillRestCerts(ce, vCertsSig); } // buscamos que tipo de algoritmo es y lo codificamos con su OID final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm); final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); // Identificador del firmante ISSUER AND SERIAL-NUMBER final TBSCertificateStructure tbs = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate())); final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()), tbs.getSerialNumber().getValue()); final SignerIdentifier identifier = new SignerIdentifier(encSid); // // ATRIBUTOS // atributos firmados ASN1Set signedAttr = null; // atributos no firmados. final ASN1Set unSignedAttr = generateUnsignerInfo(uatrib); // // FIN ATRIBUTOS // digEncryptionAlgorithm final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$ // 5. SIGNERINFO // raiz de la secuencia de SignerInfo // Obtenemos los signerInfos del signedAndEnvelopedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // introducimos los SignerInfos Existentes final ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // introducimos el nuevo SignerInfo del firmante actual. // Secuencia: // 1.- Si cofirmamos sin datos en el mismo algoritmo de hash que la firma // original sacamos el messagedigest de la firma previa. // 2.- Si no es el mismo algoritmo, miramos si nos ha llegado un messagedigest // como parametro del metodo, que quiere decir que se ha calculado externamente // (en el fondo sera que no se ha sobreescrito el parametro, con lo que // si llego != null, seguira siendo != null) // 3.- Si no es ninguno de los dos casos, no podemos firmar for (int i = 0; i < signerInfosSd.size(); i++) { final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i)); final AlgorithmIdentifier algHash = si.getDigestAlgorithm(); // Solo si coninciden los algos puedo sacar el hash de dentro if (algHash.getAlgorithm().toString().equals(AOAlgorithmID.getOID(digestAlgorithm))) { final ASN1Set signedAttrib = si.getAuthenticatedAttributes(); for (int s = 0; s < signedAttrib.size(); s++) { final ASN1Sequence elemento = (ASN1Sequence) signedAttrib.getObjectAt(s); final ASN1ObjectIdentifier oids = (ASN1ObjectIdentifier) elemento.getObjectAt(0); if (CMSAttributes.messageDigest.getId().toString().equals(oids.toString())) { final DERSet derSetHash = (DERSet) elemento.getObjectAt(1); final DEROctetString derHash = (DEROctetString) derSetHash.getObjectAt(0); md = derHash.getOctets(); } } } signerInfos.add(si); } // En este caso no puedo usar un hash de fuera, ya que no me han // pasado datos ni huellas digitales, solo un fichero de firma if (md == null) { throw new IllegalStateException("No se puede crear la firma ya que no se ha encontrado un hash valido"); //$NON-NLS-1$ } signedAttr = generateSignerInfoFromHash(signerCertificateChain[0], messageDigest, dataType, atrib); final ASN1OctetString sign2; try { sign2 = firma(signatureAlgorithm, keyEntry); } catch (final Exception ex) { throw new IOException("Error al generar la firma: " + ex, ex); //$NON-NLS-1$ } // Creamos los signerInfos del signedAndEnvelopedData signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, unSignedAttr// null //unsignedAttr )); // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(), sd.getEncryptedContentInfo(), certificates, null, new DERSet(signerInfos)// unsignedAttr )).getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cms.CounterSignerEnveloped.java
License:Open Source License
/** Constructor de la clase. Se crea una contrafirma a partir de los datos * del firmante, el archivo que se firma y del archivo que contiene las * firmas.<br>/*from www .java 2s .c o m*/ * @param parameters parámetros necesarios que contienen tanto la firma del * archivo a firmar como los datos del firmante. * @param signerCertificateChain Cadena de certificados del firmante. * @param data Archivo que contiene las firmas. * @param targetType Lo que se quiere firmar. Puede ser el árbol completo, * las hojas, un nodo determinado o unos determinados firmantes. * @param targets Nodos objetivos a firmar. * @param keyEntry Clave privada a usar para firmar. * @param dataType Identifica el tipo del contenido a firmar. * @param atri Atributo firmado que agregar a la firma. * @param uatri Atributo no firmado que agregar a la firma. * @return El archivo de firmas con la nueva firma. * @throws java.io.IOException Si ocurre algún problema leyendo o escribiendo los * datos * @throws java.security.NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella * digital. * @throws java.security.cert.CertificateException Si se produce alguna excepción con los certificados de * firma. * @throws SignatureException Cuando ocurren problemas en la firma PKCS#1. * @throws InvalidKeyException Cuando hay problemas de adecuación de la clave. */ byte[] counterSignerEnveloped(final P7ContentSignerParameters parameters, final X509Certificate[] signerCertificateChain, final byte[] data, final CounterSignTarget targetType, final int[] targets, final PrivateKeyEntry keyEntry, final String dataType, final Map<String, byte[]> atri, final Map<String, byte[]> uatri) throws IOException, NoSuchAlgorithmException, CertificateException, InvalidKeyException, SignatureException { // Inicializamos el Oid this.atrib2 = atri; this.uatrib2 = uatri; final ASN1InputStream is = new ASN1InputStream(data); // LEEMOS EL FICHERO QUE NOS INTRODUCEN final Enumeration<?> e = ((ASN1Sequence) is.readObject()).getObjects(); is.close(); // Elementos que contienen los elementos OID signedAndEnvelopedData e.nextElement(); // Contenido de signedAndEnvelopedData final ASN1Sequence contentSignedData = (ASN1Sequence) ((ASN1TaggedObject) e.nextElement()).getObject(); final SignedAndEnvelopedData sd = new SignedAndEnvelopedData(contentSignedData); // Obtenemos los signerInfos del signedAndEnvelopedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } if (signerCertificateChain.length != 0) { vCertsSig.add( Certificate.getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getEncoded()))); certificates = new BERSet(vCertsSig); } // CRLS no usado final ASN1Set certrevlist = null; // 5. SIGNERINFO // raiz de la secuencia de SignerInfo ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // FIRMA EN ARBOL if (targetType.equals(CounterSignTarget.TREE)) { signerInfos = counterTree(signerInfosSd, parameters, signerCertificateChain[0], keyEntry); } // FIRMA DE LAS HOJAS else if (targetType.equals(CounterSignTarget.LEAFS)) { signerInfos = counterLeaf(signerInfosSd, parameters, signerCertificateChain[0], keyEntry); } // FIRMA DE NODOS else if (targetType.equals(CounterSignTarget.NODES)) { // Firma de Nodos SignedAndEnvelopedData sigDat; SignedAndEnvelopedData aux = sd; int nodo = 0; for (int i = targets.length - 1; i >= 0; i--) { nodo = targets[i]; signerInfos = counterNode(aux, parameters, signerCertificateChain[0], keyEntry, nodo); sigDat = new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(), sd.getEncryptedContentInfo(), certificates, certrevlist, new DERSet(signerInfos)); // Esto se realiza asi por problemas con los casting. final ASN1InputStream asnIs = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER)); final ASN1Sequence contentSignedData2 = (ASN1Sequence) is.readObject(); // contenido del signedAndEnvelopedData asnIs.close(); aux = new SignedAndEnvelopedData(contentSignedData2); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, aux).getEncoded(ASN1Encoding.DER); } else if (targetType.equals(CounterSignTarget.SIGNERS)) { // Firma de Nodos SignedAndEnvelopedData sigDat; SignedAndEnvelopedData aux = sd; int nodo = 0; for (int i = targets.length - 1; i >= 0; i--) { nodo = targets[i]; signerInfos = counterNode(aux, parameters, signerCertificateChain[0], keyEntry, nodo); sigDat = new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(), sd.getEncryptedContentInfo(), certificates, certrevlist, new DERSet(signerInfos)); // Esto se realiza así por problemas con los casting. final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER)); final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del signedAndEnvelopedData sd2.close(); aux = new SignedAndEnvelopedData(contentSignedData2); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, aux).getEncoded(ASN1Encoding.DER); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(), sd.getEncryptedContentInfo(), certificates, certrevlist, new DERSet(signerInfos))) .getEncoded(ASN1Encoding.DER); }