List of usage examples for org.bouncycastle.asn1.cms ContentInfo ContentInfo
public ContentInfo(ASN1ObjectIdentifier contentType, ASN1Encodable content)
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") static protected SignedData includeCrls(byte[] assinatura, Collection crls) throws IOException, Exception, SecurityException, CRLException, NoSuchProviderException, NoSuchAlgorithmException { org.bouncycastle.asn1.pkcs.SignedData pkcs7 = pkcs7SignedData(assinatura); ContentInfo content = new ContentInfo(CMSObjectIdentifiers.data, null); SignedData signedCms = new SignedData(pkcs7.getDigestAlgorithms(), content, pkcs7.getCertificates(), pkcs7.getCRLs(), pkcs7.getSignerInfos()); ASN1EncodableVector vec = new ASN1EncodableVector(); for (X509CRLObject crl : (Collection<X509CRLObject>) crls) vec.add(ASN1Primitive.fromByteArray(crl.getEncoded())); DERSet set = new DERSet(vec); // for (X509CRLObject crl : (Collection<X509CRLObject>) crls) // set.addObject(ASN1Object.fromByteArray(crl.getEncoded())); SignedData signedCmsWithCrls = new SignedData(signedCms.getDigestAlgorithms(), signedCms.getEncapContentInfo(), signedCms.getCertificates(), set, signedCms.getSignerInfos()); signedCmsWithCrls.getCertificates(); signedCmsWithCrls.getCRLs();/*from ww w. j a v a2 s . c om*/ return signedCmsWithCrls; }
From source file:cljpdf.text.pdf.PdfPublicKeySecurityHandler.java
License:Mozilla Public License
private DERObject createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException { String s = "1.2.840.113549.3.2"; AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s); AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters(); ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( algorithmparameters.getEncoded("ASN.1")); ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream); DERObject derobject = asn1inputstream.readObject(); KeyGenerator keygenerator = KeyGenerator.getInstance(s); keygenerator.init(128);//from w w w. j av a2s . c o m SecretKey secretkey = keygenerator.generateKey(); Cipher cipher = Cipher.getInstance(s); cipher.init(1, secretkey, algorithmparameters); byte[] abyte1 = cipher.doFinal(in); DEROctetString deroctetstring = new DEROctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null); ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env); return contentinfo.getDERObject(); }
From source file:com.itextpdf.kernel.crypto.securityhandler.PubKeySecurityHandler.java
License:Open Source License
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException { EncryptionUtils.DERForRecipientParams parameters = EncryptionUtils.calculateDERForRecipientParams(in); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, parameters.abyte0); DEROctetString deroctetstring = new DEROctetString(parameters.abyte1); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, parameters.algorithmIdentifier, deroctetstring); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (ASN1Set) null); ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env); return contentinfo.toASN1Primitive(); }
From source file:com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.java
License:Open Source License
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException { String s = "1.2.840.113549.3.2"; AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s); AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters(); ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( algorithmparameters.getEncoded("ASN.1")); ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream); ASN1Primitive derobject = asn1inputstream.readObject(); KeyGenerator keygenerator = KeyGenerator.getInstance(s); keygenerator.init(128);//w ww .j av a 2 s .c o m SecretKey secretkey = keygenerator.generateKey(); Cipher cipher = Cipher.getInstance(s); cipher.init(1, secretkey, algorithmparameters); byte[] abyte1 = cipher.doFinal(in); DEROctetString deroctetstring = new DEROctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); ASN1Set set = null; EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set); ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env); return contentinfo.toASN1Primitive(); }
From source file:dorkbox.util.crypto.CryptoX509.java
License:Apache License
/** * Creates a NEW signature block that contains the pkcs7 (minus content, which is the .SF file) * signature of the .SF file./*www. j a v a 2 s. co m*/ * * It contains the hash of the data, and the verification signature. */ public static byte[] createSignature(byte[] signatureSourceData, X509CertificateHolder x509CertificateHolder, AsymmetricKeyParameter privateKey) { try { CMSTypedData content = new CMSProcessableByteArray(signatureSourceData); ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(content.getContentType().getId()); ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); ASN1EncodableVector signerInfos = new ASN1EncodableVector(); AlgorithmIdentifier sigAlgId = x509CertificateHolder.getSignatureAlgorithm(); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); // use the bouncy-castle lightweight API to generate a hash of the signature source data (usually the signature file bytes) BcContentSignerBuilder contentSignerBuilder; AlgorithmIdentifier digEncryptionAlgorithm; if (privateKey instanceof ECPrivateKeyParameters) { contentSignerBuilder = new BcECDSAContentSignerBuilder(sigAlgId, digAlgId); digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1 // DSA hashID } else if (privateKey instanceof DSAPrivateKeyParameters) { contentSignerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId); digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1 // DSA hashID } else if (privateKey instanceof RSAPrivateCrtKeyParameters) { contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); digEncryptionAlgorithm = new AlgorithmIdentifier(RSAUtil.rsaOids[0], null); // 1.2.840.113549.1.1.1 // RSA hashID } else { throw new RuntimeException("Invalid signature type. Only ECDSA, DSA, RSA supported."); } ContentSigner hashSigner = contentSignerBuilder.build(privateKey); OutputStream outputStream = hashSigner.getOutputStream(); outputStream.write(signatureSourceData, 0, signatureSourceData.length); outputStream.flush(); byte[] sigBytes = hashSigner.getSignature(); SignerIdentifier sigId = new SignerIdentifier( new IssuerAndSerialNumber(x509CertificateHolder.toASN1Structure())); SignerInfo inf = new SignerInfo(sigId, digAlgId, null, digEncryptionAlgorithm, new DEROctetString(sigBytes), (ASN1Set) null); digestAlgs.add(inf.getDigestAlgorithm()); signerInfos.add(inf); ASN1EncodableVector certs = new ASN1EncodableVector(); certs.add(x509CertificateHolder.toASN1Structure()); ContentInfo encInfo = new ContentInfo(contentTypeOID, null); SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, new BERSet(certs), null, new DERSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd); CMSSignedData cmsSignedData2 = new CMSSignedData(content, contentInfo); return cmsSignedData2.getEncoded(); } catch (Throwable t) { logger.error("Error signing data.", t); throw new RuntimeException("Error trying to sign data. " + t.getMessage()); } }
From source file:es.gob.afirma.envelopers.cades.CAdESData.java
License:Open Source License
/** Méodo que genera una firma digital usando el sitema conocido como * Data y que consiste en el contenido del fichero codificado como un * conjunto de bytes./* w w w. j a v a 2s . c o m*/ * @param parameters * Parámetros necesarios para obtener los datos de * SignedData. * @return El contenido del fichero en formato Data. * @throws IOException */ static byte[] genData(final P7ContentSignerParameters parameters) throws IOException { // construimos el Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.data, new DEROctetString(parameters.getContent())) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cades.CAdESDigestedData.java
License:Open Source License
/** Método que genera la firma de tipo digestedData. * @param parameters//from w w w . ja va 2 s. c om * Parámetros necesarios para la generación de este * tipo. * @param dataType * Identifica el tipo del contenido a firmar. * @return Mensaje firmado en tipo Digested Data. * @throws java.security.NoSuchAlgorithmException * Si no se soporta alguno de los algoritmos de firma o huella * digital * @throws java.io.IOException * Si ocurre algún problema leyendo o escribiendo los * datos */ static byte[] genDigestedData(final P7ContentSignerParameters parameters, final String dataType) throws NoSuchAlgorithmException, IOException { if (parameters == null) { throw new IllegalArgumentException("Los parametros no pueden ser nulos"); //$NON-NLS-1$ } // Obtenemos el algoritmo para "digestear" final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(parameters.getSignatureAlgorithm()); final AlgorithmIdentifier digAlgId; try { digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); } catch (final Exception e) { throw new IOException(new StringBuilder().append("Error de codificacion: ").append(e).toString(), e); //$NON-NLS-1$ } // indicamos el tipo de contenido final ContentInfo encInfo = new ContentInfo(new ASN1ObjectIdentifier(dataType), null); // digest final DEROctetString digest = new DEROctetString( MessageDigest.getInstance(digestAlgorithm).digest(parameters.getContent())); // construimos el digestedData. return new ContentInfo(PKCSObjectIdentifiers.digestedData, new DigestedData(digAlgId, encInfo, digest)) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cades.CAdESEncryptedData.java
License:Open Source License
/** Método principal que genera la firma de tipo EncryptedData. * @param data//ww w . ja v a 2s .c o m * Datos a cifrar. * @param digAlg * ALgoritmo para realizar el Digest. * @param config * Configuración del algoritmo para firmar. * @param pass * Cadena que se usar paa cifrar los datos. * @param dataType * Identifica el tipo del contenido a firmar. * @return la firma de tipo EncryptedData. * @throws java.security.NoSuchAlgorithmException * Si no se soporta alguno de los algoritmos de firma o huella * digital * @throws IOException */ static byte[] genEncryptedData(final byte[] data, final String digAlg, final AOCipherConfig config, final String pass, final String dataType) throws NoSuchAlgorithmException, AOException, IOException { // Asignamos la clave de cifrado final SecretKey cipherKey = CAdESUtils.assignKey(config, pass); // Datos previos útiles final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(digAlg); // generamos el contenedor de cifrado final EncryptedContentInfo encInfo; try { // 3. ENCRIPTEDCONTENTINFO encInfo = CAdESUtils.getEncryptedContentInfo(data, config, cipherKey); } catch (final Exception ex) { throw new AOException("Error durante el proceso de cifrado", ex); //$NON-NLS-1$ } // 4. ATRIBUTOS // obtenemos la lista de certificados final ASN1Set unprotectedAttrs = SigUtils.getAttributeSet( new AttributeTable(CAdESUtils.initContexExpecific(digestAlgorithm, data, dataType, null))); // construimos el Enveloped Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.encryptedData, new EncryptedData(encInfo, unprotectedAttrs)) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cades.CAdESEnvelopedData.java
License:Open Source License
/** Método que genera la firma de tipo EnvelopedData. * @param parameters//from w w w .ja va2 s. c o m * Parámetros necesarios para la generación de este * tipo. * @param config * Configuración del algoritmo para firmar * @param certDest * Certificado del destino al cual va dirigido la firma. * @param dataType * Identifica el tipo del contenido a firmar. * @return la firma de tipo EnvelopedData. * @throws java.io.IOException * Si ocurre algún problema leyendo o escribiendo los * datos * @throws java.security.cert.CertificateEncodingException * Si se produce alguna excepción con los certificados de * firma. * @throws java.security.NoSuchAlgorithmException * Si no se soporta alguno de los algoritmos de firma o huella * digital */ byte[] genEnvelopedData(final P7ContentSignerParameters parameters, final X509Certificate[] signerCertificateChain, final AOCipherConfig config, final X509Certificate[] certDest, final String dataType) throws IOException, CertificateEncodingException, NoSuchAlgorithmException { this.cipherKey = CAdESUtils.initEnvelopedData(config, certDest); // Datos previos útiles final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(parameters.getSignatureAlgorithm()); // 1. ORIGINATORINFO // obtenemos la lista de certificados final ASN1Set certificates = CAdESUtils.fetchCertificatesList(signerCertificateChain); final ASN1Set certrevlist = null; OriginatorInfo origInfo = null; if (signerCertificateChain.length != 0) { origInfo = new OriginatorInfo(certificates, certrevlist); } // 2. RECIPIENTINFOS final Info infos = CAdESUtils.getEnvelopeInfo(parameters.getContent(), config, certDest, this.cipherKey); // 3. ATRIBUTOS final ASN1Set unprotectedAttrs = SigUtils.getAttributeSet(new AttributeTable( CAdESUtils.initContexExpecific(digestAlgorithm, parameters.getContent(), dataType, null))); // construimos el Enveloped Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo, new DERSet(infos.getRecipientInfos()), infos.getEncInfo(), unprotectedAttrs)) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cades.CAdESEnvelopedData.java
License:Open Source License
/** Método que genera la firma de tipo EnvelopedData. * @param data//from ww w . j a v a2s . com * Datos binarios a firmar * @param digestAlg * Algoritmo de hash * @param config * Configuración del algoritmo para firmar * @param certDest * Certificado del destino al cual va dirigido la firma. * @param dataType * Identifica el tipo del contenido a firmar. * @return la firma de tipo EnvelopedData. * @throws java.io.IOException * Si hay problemas en la lectura de datos * @throws java.security.cert.CertificateEncodingException * Cuando el certificado proporcionado no está codificado * adecuadamente * @throws java.security.NoSuchAlgorithmException * Si no se soporta alguno de los algoritmos indicados */ byte[] genEnvelopedData(final byte[] data, final String digestAlg, final AOCipherConfig config, final X509Certificate[] certDest, final String dataType) throws IOException, CertificateEncodingException, NoSuchAlgorithmException { this.cipherKey = CAdESUtils.initEnvelopedData(config, certDest); // Datos previos útiles final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(digestAlg); // 1. ORIGINATORINFO final OriginatorInfo origInfo = null; // 2. RECIPIENTINFOS final Info infos = CAdESUtils.getEnvelopeInfo(data, config, certDest, this.cipherKey); // 3. ATRIBUTOS final ASN1Set unprotectedAttrs = SigUtils.getAttributeSet( new AttributeTable(CAdESUtils.initContexExpecific(digestAlgorithm, data, dataType, null))); // construimos el Enveloped Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo, new DERSet(infos.getRecipientInfos()), infos.getEncInfo(), unprotectedAttrs)) .getEncoded(ASN1Encoding.DER); }