List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers data
ASN1ObjectIdentifier data
To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers data.
Click Source Link
From source file:es.gob.afirma.envelopers.cms.AOCMSEnveloper.java
License:Open Source License
/** Recupera el contenido de un envoltorio CMS. * @param cmsEnvelop Envoltorio CMS./*from ww w . ja v a 2 s . co m*/ * @param addresseePke Clave privada del destinatario que desea desensobrar. * @return Contenido del envoltorio. * @throws InvalidKeyException Cuando la clave de descifrado configurada no sea válida o pertenezca a un destinatario. * @throws AOException Cuando se produce un error durante al desenvolver los datos. * @throws InvalidKeySpecException Cuando ocurren problemas relacionados con la estructura interna de las claves */ @Override public byte[] recoverData(final byte[] cmsEnvelop, final PrivateKeyEntry addresseePke) throws InvalidKeyException, AOException, IOException, InvalidKeySpecException { final org.bouncycastle.asn1.ASN1InputStream is = new org.bouncycastle.asn1.ASN1InputStream(cmsEnvelop); // Leemos los datos final org.bouncycastle.asn1.ASN1Sequence dsq = (org.bouncycastle.asn1.ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> objects = dsq.getObjects(); // Elementos que contienen los elementos OID Data final org.bouncycastle.asn1.ASN1ObjectIdentifier doi = (org.bouncycastle.asn1.ASN1ObjectIdentifier) objects .nextElement(); byte[] datos; try { if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data)) { Logger.getLogger("es.gob.afirma") //$NON-NLS-1$ .warning("La extraccion de datos de los envoltorios CMS Data no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.digestedData)) { Logger.getLogger("es.gob.afirma") //$NON-NLS-1$ .warning("La extraccion de datos de los envoltorios CMS DigestedData no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.compressedData)) { datos = AOCMSEnveloper.recoverCMSCompressedData(cmsEnvelop); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.encryptedData)) { datos = AOCMSEnveloper.recoverCMSEncryptedData(cmsEnvelop, this.cipherKey); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.envelopedData)) { datos = AOCMSEnveloper.recoverCMSEnvelopedData(cmsEnvelop, addresseePke); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authEnvelopedData)) { datos = AOCMSEnveloper.recoverCMSAuthenticatedEnvelopedData(cmsEnvelop, addresseePke); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authenticatedData)) { datos = AOCMSEnveloper.recoverCMSAuthenticatedData(cmsEnvelop, addresseePke); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.signedAndEnvelopedData)) { datos = AOCMSEnveloper.recoverCMSSignedEnvelopedData(cmsEnvelop, addresseePke); } else { throw new AOInvalidFormatException( "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$ } } catch (final AOInvalidRecipientException e) { throw new InvalidKeyException( "La clave indicada no pertenece a ninguno de los destinatarios del envoltorio", e); //$NON-NLS-1$ } catch (final CertificateEncodingException e) { throw new AOException("Error al descodificar los certificados del envoltorio", e); //$NON-NLS-1$ } catch (final NoSuchAlgorithmException e) { throw new AOException("No se reconoce el algoritmo indicado", e); //$NON-NLS-1$ } catch (final NoSuchPaddingException e) { throw new AOException("No se reconoce el tipo de relleno indicado", e); //$NON-NLS-1$ } catch (final InvalidAlgorithmParameterException e) { throw new AOException("No se reconoce la configuracion del algoritmo indicado", e); //$NON-NLS-1$ } catch (final IllegalBlockSizeException e) { throw new AOException("Tamano de bloque invalido: " + e, e); //$NON-NLS-1$ } catch (final BadPaddingException e) { throw new AOException("relleno invalido: " + e, e); //$NON-NLS-1$ } return datos; }
From source file:es.gob.afirma.envelopers.cms.AOCMSMultiEnveloper.java
License:Open Source License
/** Cofirma un sobre digital CMS. * @param data Datos contenidos en el sobre digital a cofirmar * @param sign Sobre digital/*www . ja v a2 s . com*/ * @param algorithm Algoritmo de firma * @param keyEntry Entrada de clave privada a usar para la firma * @param xParams Parámetros adicionales. Únicamente se lee <i>precalculatedHashAlgorithm</i> * @return Sobre digtal cofirmado * @throws AOException Si ocurre cualquier problema durante el proceso */ public byte[] cosign(final byte[] data, final byte[] sign, final String algorithm, final PrivateKeyEntry keyEntry, final Properties xParams) throws AOException { final String precalculatedDigest = xParams != null ? xParams.getProperty("precalculatedHashAlgorithm") //$NON-NLS-1$ : null; byte[] messageDigest = null; if (precalculatedDigest != null) { messageDigest = data; } final P7ContentSignerParameters csp = new P7ContentSignerParameters(data, algorithm); // tipos de datos a firmar. if (this.dataTypeOID == null) { this.dataTypeOID = PKCSObjectIdentifiers.data.getId(); } // Si la firma que nos introducen es SignedAndEnvelopedData try { // El parametro omitContent no tiene sentido en un signed and // envelopedData. return new CoSignerEnveloped().coSigner(csp, (X509Certificate[]) keyEntry.getCertificateChain(), sign, this.dataTypeOID, keyEntry, this.atrib, this.uatrib, messageDigest); } catch (final Exception e) { throw new AOException("Error generando la Cofirma del sobre", e); //$NON-NLS-1$ } }
From source file:es.gob.afirma.envelopers.cms.AOCMSMultiEnveloper.java
License:Open Source License
/** Cofirma un sobre digital CMS. * @param sign Sobre digital CMS ya firmado * @param algorithm Algoritmo de firma a usar * @param keyEntry ENtrada de clave privada para la firma * @return Sobre cofirmado//from w w w . java 2 s . c om * @throws AOException Si ocurre cualquier problema durante el proceso */ public byte[] cosign(final byte[] sign, final String algorithm, final PrivateKeyEntry keyEntry) throws AOException { // tipos de datos a firmar. if (this.dataTypeOID == null) { this.dataTypeOID = PKCSObjectIdentifiers.data.getId(); } // Cofirma de la firma usando unicamente el fichero de firmas. try { return new CoSignerEnveloped().coSigner(algorithm, (X509Certificate[]) keyEntry.getCertificateChain(), sign, this.dataTypeOID, keyEntry, this.atrib, this.uatrib, null); } catch (final Exception e) { throw new AOException("Error generando la Cofirma PKCS#7", e); //$NON-NLS-1$ } }
From source file:es.gob.afirma.envelopers.cms.AOCMSMultiEnveloper.java
License:Open Source License
/** Recupera el contenido de un envoltorio CMS. * @param cmsEnvelop/* www. ja va2 s . co m*/ * Envoltorio CMS. * @return Contenido del envoltorio. * @throws AOInvalidRecipientException * Cuando el usuario no es uno de los destinatarios del sobre. * @throws InvalidKeyException Cuando la clave de descifrado configurada no es válida. * @throws CertificateEncodingException * Cuando el certificado del destinatario no es válido. * @throws IOException * Cuando el envoltorio está corrupto o no puede leerse. * @throws AOInvalidFormatException * Cuando no se ha indicado un envoltorio soportado. * @throws AOException * Cuando se produce un error durante al desenvolver los datos. * @throws NoSuchAlgorithmException Si el JRE no soporta algún algoritmo necesario * @throws BadPaddingException Si hay problemas estableciendo el relleno de los datos * @throws IllegalBlockSizeException Si no cuadran los tamaños de bloque de los algoritmos usados * @throws InvalidAlgorithmParameterException Si no se soporta algún parámetro necesario * para algún algoritmo * @throws NoSuchPaddingException Si no se soporta algún método de relleno * @throws InvalidKeySpecException Cuando ocurren problemas relacionados con la estructura interna de las claves */ byte[] recoverData(final byte[] cmsEnvelop) throws InvalidKeyException, CertificateEncodingException, IOException, AOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException { final org.bouncycastle.asn1.ASN1InputStream is = new org.bouncycastle.asn1.ASN1InputStream(cmsEnvelop); // Leemos los datos final org.bouncycastle.asn1.ASN1Sequence dsq = (org.bouncycastle.asn1.ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> objects = dsq.getObjects(); // Elementos que contienen los elementos OID Data final org.bouncycastle.asn1.ASN1ObjectIdentifier doi = (org.bouncycastle.asn1.ASN1ObjectIdentifier) objects .nextElement(); byte[] datos; if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data)) { LOGGER.warning("La extraccion de datos de los envoltorios CMS Data no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.digestedData)) { LOGGER.warning("La extraccion de datos de los envoltorios CMS DigestedData no esta implementada"); //$NON-NLS-1$ datos = null; } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.compressedData)) { datos = AOCMSMultiEnveloper.recoverCMSCompressedData(cmsEnvelop); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.encryptedData)) { datos = AOCMSMultiEnveloper.recoverCMSEncryptedData(cmsEnvelop, this.cipherKey); } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.envelopedData)) { datos = AOCMSMultiEnveloper.recoverCMSEnvelopedData(cmsEnvelop, this.configuredKe); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authEnvelopedData)) { datos = AOCMSMultiEnveloper.recoverCMSAuthenticatedEnvelopedData(cmsEnvelop, this.configuredKe); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authenticatedData)) { datos = AOCMSMultiEnveloper.recoverCMSAuthenticatedData(cmsEnvelop, this.configuredKe); } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.signedAndEnvelopedData)) { datos = AOCMSMultiEnveloper.recoverCMSSignedEnvelopedData(cmsEnvelop, this.configuredKe); } else { throw new AOInvalidFormatException( "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$ } return datos; }
From source file:es.gob.afirma.envelopers.cms.CMSData.java
License:Open Source License
/** Méodo que genera una estructura CMS de tipo Data. * @param content//from www. j a va 2s . c om * Datos que se desean envolver. * @return El envoltorio de tipo data. * @throws IOException En caso de error en la lectura o tratamiento de datos */ static byte[] genData(final byte[] content) throws IOException { return new ContentInfo(PKCSObjectIdentifiers.data, new DEROctetString(content)) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cms.ValidateCMS.java
License:Open Source License
/** Método que verifica que es una firma de tipo "data" * @param data/*from www . j a v a2s.c om*/ * Datos CMS. * @return si es de este tipo. */ @SuppressWarnings("unused") static boolean isCMSData(final byte[] data) { boolean isValid = true; try { final ASN1InputStream is = new ASN1InputStream(data); final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID Data final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement(); if (!doi.equals(PKCSObjectIdentifiers.data)) { isValid = false; } else { // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); /* * Si no es un objeto de tipo Dara se pasa al manejo de la * excepcion */ new DEROctetString(doj.getObject()); } } catch (final Exception ex) { isValid = false; } return isValid; }
From source file:es.gob.afirma.signers.cades.CAdESTriPhaseSigner.java
License:Open Source License
/** Realiza una firma CAdES completa. * @param digestAlgorithmName Algoritmo de huella digital * @param content Datos a firmar (usar <code>null</code> si no se desean añadir a la firma) * @param signerCertificateChain Cadena de certificados del firmante * @param signature Firma PKCS#1 v1.5 de los atributos firmados * @param signedAttributes Atributos firmados (prefirma) * @return Firma CAdES completa//from w w w . jav a 2s .c o m * @throws AOException Cuando se produce cualquier error durante el proceso. */ public static byte[] postSign(final String digestAlgorithmName, final byte[] content, final X509Certificate[] signerCertificateChain, final byte[] signature, final byte[] signedAttributes) throws AOException { if (signerCertificateChain == null || signerCertificateChain.length == 0) { throw new IllegalArgumentException("La cadena de certificados debe contener al menos una entrada"); //$NON-NLS-1$ } final TBSCertificateStructure tbsCertificateStructure; try { tbsCertificateStructure = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate())); } catch (final Exception e) { throw new AOException("No se ha podido crear la estructura de certificados", e); //$NON-NLS-1$ } final SignerIdentifier signerIdentifier = new SignerIdentifier( new IssuerAndSerialNumber(X500Name.getInstance(tbsCertificateStructure.getIssuer()), tbsCertificateStructure.getSerialNumber().getValue())); // Algoritmo de huella digital final AlgorithmIdentifier digestAlgorithmOID; try { digestAlgorithmOID = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithmName)); } catch (final Exception e) { throw new AOException("Error obteniendo el OID en ASN.1 del algoritmo de huella digital", e); //$NON-NLS-1$ } // EncryptionAlgorithm final AlgorithmIdentifier keyAlgorithmIdentifier; try { keyAlgorithmIdentifier = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$ } catch (final Exception e) { throw new AOException("Error al codificar el algoritmo de cifrado", e); //$NON-NLS-1$ } // Firma PKCS#1 codificada final ASN1OctetString encodedPKCS1Signature = new DEROctetString(signature); // Atributos firmados final ASN1Set asn1SignedAttributes; try { asn1SignedAttributes = (ASN1Set) ASN1Primitive.fromByteArray(signedAttributes); } catch (final IOException e) { throw new AOException("Error en la inclusion de la recuperacion de los SignedAttibutes", e); //$NON-NLS-1$ } // SignerInfo final ASN1EncodableVector signerInfo = new ASN1EncodableVector(); signerInfo.add(new SignerInfo(signerIdentifier, digestAlgorithmOID, asn1SignedAttributes, keyAlgorithmIdentifier, encodedPKCS1Signature, null)); // ContentInfo final ContentInfo contentInfo; if (content != null) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final CMSProcessable msg = new CMSProcessableByteArray(content); try { msg.write(baos); } catch (final Exception e) { throw new AOException("Error en la escritura del contenido implicito en el ContentInfo", e); //$NON-NLS-1$ } contentInfo = new ContentInfo(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.data.getId()), new BEROctetString(baos.toByteArray())); } else { contentInfo = new ContentInfo(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.data.getId()), null); } // Certificados final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>(); for (final X509Certificate cert : signerCertificateChain) { try { ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(cert.getEncoded()))); } catch (final Exception e) { Logger.getLogger("es.gob.afirma").severe( //$NON-NLS-1$ "Error insertando el certificado '" + AOUtil.getCN(cert) + "' en la cadena de confianza"); //$NON-NLS-1$ //$NON-NLS-2$ } } final ASN1Set certificates = SigUtils.createBerSetFromList(ce); // Algoritmos de huella digital final ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector(); digestAlgorithms.add(digestAlgorithmOID); try { return new ContentInfo(PKCSObjectIdentifiers.signedData, new SignedData(new DERSet(digestAlgorithms), contentInfo, certificates, null, new DERSet(signerInfo))).getEncoded(ASN1Encoding.DER); } catch (final IOException e) { throw new AOException("Error creando el ContentInfo de CAdES: " + e, e); //$NON-NLS-1$ } }
From source file:es.gob.afirma.signers.cades.CAdESUtils.java
License:Open Source License
private static ASN1EncodableVector initContexExpecific(final String dataDigestAlgorithmName, final byte[] data, final byte[] dataDigest, final Date signDate, final boolean padesMode) throws NoSuchAlgorithmException { // authenticatedAttributes final ASN1EncodableVector contexExpecific = new ASN1EncodableVector(); // ContentType es obligatorio, y debe tener siempre el valor "id-data" contexExpecific.add(new Attribute(CMSAttributes.contentType, new DERSet(PKCSObjectIdentifiers.data))); // fecha de firma, no se anade en modo PAdES, pero es obligatorio en CAdES if (!padesMode) { contexExpecific.add(new Attribute(CMSAttributes.signingTime, new DERSet(new ASN1UTCTime(signDate)))); }/*from ww w.j ava 2 s .c o m*/ // MessageDigest contexExpecific.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(dataDigest != null ? dataDigest : MessageDigest.getInstance(dataDigestAlgorithmName).digest(data))))); return contexExpecific; }
From source file:es.gob.afirma.signers.cades.CAdESValidator.java
License:Open Source License
/** Verifica si los datos proporcionados se corresponden con una estructura de tipo <i>Data</i>. * @param data Datos PKCS#7/CMS/CAdES./*from ww w . ja v a2 s . co m*/ * @return <code>true</code> si los datos proporcionados se corresponden con una estructura de tipo <i>Data</i>, * <code>false</code> en caso contrario. * @throws IOException En caso de problemas leyendo el fichero */ @SuppressWarnings("unused") static boolean isCAdESData(final byte[] data) throws IOException { // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1InputStream is = new ASN1InputStream(data); final Enumeration<?> e; try { e = ((ASN1Sequence) is.readObject()).getObjects(); } catch (final ClassCastException ex) { // No es una secuencia return false; } finally { is.close(); } // Elementos que contienen los elementos OID Data final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement(); if (!doi.equals(PKCSObjectIdentifiers.data)) { return false; } // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); try { /* Los valores de retorno no se usan, solo es para verificar que la * conversion ha sido correcta. De no ser asi, se pasaria al manejo * de la excepcion. */ new DEROctetString(doj.getObject()); } catch (final Exception ex) { LOGGER.info("Los datos proporcionados no son de tipo Data: " + ex); //$NON-NLS-1$ return false; } return true; }
From source file:es.gob.afirma.signers.cms.AOCMSSigner.java
License:Open Source License
/** {@inheritDoc} */ @Override//from ww w .j av a2 s .c o m public byte[] sign(final byte[] data, final String algorithm, final PrivateKey key, final java.security.cert.Certificate[] certChain, final Properties xParams) throws AOException, IOException { new BCChecker().checkBouncyCastle(); final Properties extraParams = xParams != null ? xParams : new Properties(); final String precalculatedDigest = extraParams.getProperty("precalculatedHashAlgorithm"); //$NON-NLS-1$ byte[] messageDigest = null; if (precalculatedDigest != null) { messageDigest = data; } final P7ContentSignerParameters csp = new P7ContentSignerParameters(data, algorithm); // tipos de datos a firmar. if (this.dataType == null) { this.dataType = PKCSObjectIdentifiers.data.getId(); } final String mode = extraParams.getProperty("mode", AOSignConstants.DEFAULT_SIGN_MODE); //$NON-NLS-1$ final boolean omitContent = mode.equals(AOSignConstants.SIGN_MODE_EXPLICIT) || precalculatedDigest != null; try { return new GenSignedData().generateSignedData(csp, omitContent, Boolean.parseBoolean(extraParams.getProperty("applySystemDate", "true")), //$NON-NLS-1$ //$NON-NLS-2$ this.dataType, key, certChain, this.atrib, this.uatrib, messageDigest); } catch (final NoSuchAlgorithmException e) { throw new AOException("Error en el algoritmo de firma: " + e, e); //$NON-NLS-1$ } catch (final CertificateException e) { throw new AOException("Error en el certificado de firma: " + e, e); //$NON-NLS-1$ } }