List of usage examples for org.bouncycastle.asn1.cms IssuerAndSerialNumber IssuerAndSerialNumber
public IssuerAndSerialNumber(X509Name name, ASN1Integer serialNumber)
From source file:br.ufpb.dicomflow.integrationAPI.mail.AbstractMailSender.java
License:Open Source License
private Message signAndEcrypt(Message message, X509Certificate signCert, X509Certificate encryptCert, PrivateKey privateKey) throws Exception { MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailcap.addMailcap(/*from ww w . j a v a2 s . co m*/ "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mailcap.addMailcap( "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mailcap.addMailcap( "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mailcap.addMailcap( "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mailcap.addMailcap( "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mailcap); /* Create the Signer - SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X500Name(((X509Certificate) signCert).getIssuerDN().getName()), ((X509Certificate) signCert).getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder() .setSignedAttributeGenerator(new AttributeTable(attributes)) .build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey, signCert)); /* Add the list of certs to the generator */ List certList = new ArrayList(); certList.add(signCert); Store certs = new JcaCertStore(certList); signer.addCertificates(certs); /* Sign the message */ MimeMultipart mm = signer.generate((MimeMessage) message); MimeMessage signedMessage = new MimeMessage(message.getSession()); /* Set all original MIME headers in the signed message */ Enumeration headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { signedMessage.addHeaderLine((String) headers.nextElement()); } /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); /* Create the encrypter - SMIMEEnvelopedGenerator */ SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(encryptCert)); /* Encrypt the message */ MimeBodyPart encryptedPart = encrypter.generate(signedMessage, new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).build()); /* * Create a new MimeMessage that contains the encrypted and signed * content */ ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); MimeMessage encryptedMessage = new MimeMessage(message.getSession(), new ByteArrayInputStream(out.toByteArray())); /* Set all original MIME headers in the encrypted message */ headers = ((MimeMessage) message).getAllHeaderLines(); while (headers.hasMoreElements()) { String headerLine = (String) headers.nextElement(); /* * Make sure not to override any content-* headers from the * original message */ if (!Strings.toLowerCase(headerLine).startsWith("content-")) { encryptedMessage.addHeaderLine(headerLine); } } return encryptedMessage; }
From source file:cljpdf.text.pdf.PdfPublicKeySecurityHandler.java
License:Mozilla Public License
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException { ASN1InputStream asn1inputstream = new ASN1InputStream( new ByteArrayInputStream(x509certificate.getTBSCertificate())); TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure .getInstance(asn1inputstream.readObject()); AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo() .getAlgorithmId();/* w ww . ja v a 2 s . c om*/ IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue()); Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId()); cipher.init(1, x509certificate); DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0)); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring); }
From source file:com.cordys.coe.ac.emailio.outbound.EmailMessageFactory.java
License:Apache License
/** * This method creates and returns a signed version of the given mail. * * @param mbpToBeSigned The message to sign. * @param eicConfiguration The configuration to use. * @param sSession The main session to use. * @param sSenderAddress The email address of the sender. * * @return The signed message to return. * * @throws OutboundEmailException In case of any exceptions. * @throws KeyManagerException In case of any key manager related exceptions. *//* w w w . jav a 2s . co m*/ private static MimeMessage signMessage(MimeMessage mbpToBeSigned, ISMIMEConfiguration eicConfiguration, Session sSession, String sSenderAddress) throws OutboundEmailException, KeyManagerException { MimeMessage mmReturn = null; // Use the address to find the proper private key. PrivateKey pkKey = null; ICertificateInfo ciInfo = eicConfiguration.getCertificateInfo(sSenderAddress); if (ciInfo != null) { pkKey = ciInfo.getKey(); } if ((pkKey == null) && !eicConfiguration.getBypassSMIME()) { throw new OutboundEmailException( OutboundEmailExceptionMessages.OEE_COULD_NOT_FIND_A_PRIVATE_KEY_FOR_EMAIL_ADDRESS_0, sSenderAddress); } else { mmReturn = mbpToBeSigned; } // Create the signed message if possible. If no private key was found and bypassing S/MIME // is allowed the original message is returned. if (pkKey != null) { try { // Get the public key. X509Certificate xcPublic = ciInfo.getX509Certificate(); // Create the SMIME capabilities SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); // Create the signing preferences. ASN1EncodableVector attributes = new ASN1EncodableVector(); X509Name name = new X509Name(xcPublic.getIssuerDN().getName()); IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, xcPublic.getSerialNumber()); SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute( issuerAndSerialNumber); attributes.add(encryptionKeyPreferenceAttribute); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); // Create the signature generator. SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSigner(pkKey, xcPublic, "DSA".equals(pkKey.getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1 : SMIMESignedGenerator.DIGEST_MD5, new AttributeTable(attributes), null); // Create the list of certificates that will be sent along with the signature. Right // now the CA certificate will NOT be sent along with the mail. It is expected that // the receiver is capable of verifying the authenticity of the certificate itself. List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(xcPublic); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); signer.addCertificatesAndCRLs(certs); // Sign the actual message // The message that was created will ALWAYS have a multipart. In order to keep it // readable in ALL clients we will sign the content of the message, not the whole // message. MimeMultipart mm = signer.generate(mbpToBeSigned, "BC"); mmReturn = new MimeMessage(sSession); // Set the content of the signed message mmReturn.setContent(mm); mmReturn.saveChanges(); } catch (Exception e) { throw new OutboundEmailException(e, OutboundEmailExceptionMessages.OEE_ERROR_SIGNING_EMAIL_MESSAGE); } } else if (LOG.isDebugEnabled()) { LOG.debug("Bypassing S/MIME because no private key was found for " + sSenderAddress); } return mmReturn; }
From source file:com.cordys.coe.test.smime.TestSendEncryptedAndSignedMessage.java
License:Apache License
/** * This method sends the message to the receiver. * * @throws Exception DOCUMENTME//ww w . j a va2 s. c o m */ private void sendMessage() throws Exception { final InternetAddress[] RECEIVER_ADDRESS = new InternetAddress[] { new InternetAddress("outlook2007@ces70.cordys.com", "Outlook 2007 User"), new InternetAddress("outlookexpress@ces70.cordys.com", "Outlook Express User"), new InternetAddress("thunderbird@ces70.cordys.com", "Thunderbird User"), new InternetAddress("cordystestuser1@ces70.cordys.com", "Cordys Test User 1"), new InternetAddress("cordystestuser2@ces70.cordys.com", "Cordys Test User 2") }; final InternetAddress SENDER_ADDRESS = new InternetAddress("testprogram@ces70.cordys.com", "Test Program User"); String sSubject = "From test progam V1 [S&E] No r"; boolean bDoEncryption = true; // String sContent = "Single line"+System.getProperty("line.separator")+"SecondLine"; String sContent = "Single line\nSecondLine"; // Add capabilities. MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mailcap.addMailcap( "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); mailcap.addMailcap( "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); mailcap.addMailcap( "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); mailcap.addMailcap( "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); mailcap.addMailcap( "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(mailcap); /* Add BC */ Security.addProvider(new BouncyCastleProvider()); /* Get the private key to sign the message with */ ICertificateInfo certInfo = m_km.getCertificateInfo(SENDER_ADDRESS.getAddress()); if (certInfo == null) { throw new Exception("cannot find private key for email address " + SENDER_ADDRESS); } /* Create the message to sign and encrypt */ Properties props = System.getProperties(); props.put("mail.smtp.host", "srv-nl-ces70"); Session session = Session.getDefaultInstance(props, null); MimeMessage body = new MimeMessage(session); body.setContent(sContent, "text/plain"); body.saveChanges(); /* Create the SMIMESignedGenerator */ SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); X509Certificate cert = certInfo.getX509Certificate(); ASN1EncodableVector attributes = new ASN1EncodableVector(); X509Name name = new X509Name(cert.getIssuerDN().getName()); IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, cert.getSerialNumber()); SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute( issuerAndSerialNumber); attributes.add(encryptionKeyPreferenceAttribute); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSigner((PrivateKey) certInfo.getKey(), cert, "DSA".equals(certInfo.getKey().getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1 : SMIMESignedGenerator.DIGEST_MD5, new AttributeTable(attributes), null); /* Add the list of certs to the generator */ List<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); signer.addCertificatesAndCRLs(certs); /* Sign the message */ MimeMultipart mm = signer.generate(body, "BC"); MimeMessage signedMessage = new MimeMessage(session); /* Set the content of the signed message */ signedMessage.setContent(mm); signedMessage.saveChanges(); /* Create the encrypter */ if (bDoEncryption) { SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator(); for (InternetAddress ia : RECEIVER_ADDRESS) { ICertificateInfo ciTemp = m_km.getCertificateInfo(ia.getAddress()); if (ciTemp != null) { encrypter.addKeyTransRecipient(ciTemp.getX509Certificate()); } else if (LOG.isDebugEnabled()) { LOG.debug("No certificate found for " + ia.toString()); } } /* Encrypt the message */ MimeBodyPart encryptedPart = encrypter.generate(signedMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); /* * Create a new MimeMessage that contains the encrypted and signed content */ ByteArrayOutputStream out = new ByteArrayOutputStream(); encryptedPart.writeTo(out); body = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray())); } else { body = signedMessage; } body.setFrom(SENDER_ADDRESS); body.setRecipients(Message.RecipientType.TO, RECEIVER_ADDRESS); body.addRecipient(Message.RecipientType.TO, new InternetAddress("intermediate@ces70.cordys.com", "Intermediate user")); body.setSentDate(new Date()); body.addHeader("User-Agent", "CordysMailClient"); body.setSubject(sSubject); Transport.send(body); }
From source file:com.itextpdf.kernel.crypto.securityhandler.PubKeySecurityHandler.java
License:Open Source License
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException { ASN1InputStream asn1inputstream = new ASN1InputStream( new ByteArrayInputStream(x509certificate.getTBSCertificate())); TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure .getInstance(asn1inputstream.readObject()); assert tbscertificatestructure != null; AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm(); IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue()); byte[] cipheredBytes = EncryptionUtils.cipherBytes(x509certificate, abyte0, algorithmidentifier); DEROctetString deroctetstring = new DEROctetString(cipheredBytes); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring); }
From source file:com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.java
License:Open Source License
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException { ASN1InputStream asn1inputstream = new ASN1InputStream( new ByteArrayInputStream(x509certificate.getTBSCertificate())); TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure .getInstance(asn1inputstream.readObject()); AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm(); IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue()); Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId()); try {// w ww . j av a 2 s .c o m cipher.init(1, x509certificate); } catch (InvalidKeyException e) { cipher.init(1, x509certificate.getPublicKey()); } DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0)); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring); }
From source file:com.zotoh.crypto.CryptoUte.java
License:Open Source License
private static SMIMESignedGenerator makeSignerGentor(PrivateKey key, Certificate[] certs, SigningAlgo algo) throws CertStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, GeneralSecurityException, CertificateEncodingException { SMIMESignedGenerator gen = new SMIMESignedGenerator("base64"); List<Certificate> lst = asList(true, certs); ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); caps.addCapability(SMIMECapability.dES_CBC); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); X509Certificate x0 = (X509Certificate) certs[0]; X509Certificate issuer = x0;// w w w.ja v a2s .c o m X500Principal issuerDN; if (certs.length > 1) { issuer = (X509Certificate) certs[1]; } issuerDN = issuer.getSubjectX500Principal(); x0 = (X509Certificate) certs[0]; // // add an encryption key preference for encrypted responses - // normally this would be different from the signing certificate... // IssuerAndSerialNumber issAndSer = new IssuerAndSerialNumber(X500Name.getInstance(issuerDN.getEncoded()), x0.getSerialNumber()); Provider prov = Crypto.getInstance().getProvider(); signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(issAndSer)); try { JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(prov).build()); bdr.setDirectSignature(true); ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key); bdr.setSignedAttributeGenerator( new DefaultSignedAttributeTableGenerator(new AttributeTable(signedAttrs))); gen.addSignerInfoGenerator(bdr.build(cs, x0)); gen.addCertificates(new JcaCertStore(lst)); return gen; } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } }
From source file:es.gob.afirma.envelopers.cades.CAdESEPESSignedAndEnvelopedData.java
License:Open Source License
/** Método que genera la firma de tipo SignedAndEnvelopedData. * @param parameters//www. j av a2 s .co m * Parámetros necesarios para la generación de este * tipo. * @param config * Configuración del algoritmo para firmar * @param policy * Política del certificado. * @param certDest * Certificado del destino al cual va dirigido la firma. * @param dataType * Identifica el tipo del contenido a firmar. * @param keyEntry * Entrada a la clave de firma * @return Firma de tipo SignedAndEnvelopedData. * @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 encuentra un algoritmo válido. */ byte[] genCADESEPESSignedAndEnvelopedData(final P7ContentSignerParameters parameters, final X509Certificate[] signerCertificateChain, final AOCipherConfig config, final AdESPolicy policy, final X509Certificate[] certDest, final String dataType, final PrivateKeyEntry keyEntry) throws IOException, CertificateEncodingException, NoSuchAlgorithmException { final SecretKey cipherKey = CAdESUtils.initEnvelopedData(config, certDest); // 1. VERSION // la version se mete en el constructor del signedAndEnvelopedData y es // 1 // 2. DIGESTALGORITM // buscamos que timo de algoritmo es y lo codificamos con su OID final String signatureAlgorithm; final String digestAlgorithm; final ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); try { signatureAlgorithm = parameters.getSignatureAlgorithm(); digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm); final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); digestAlgs.add(digAlgId); } catch (final Exception e) { throw new IOException("Error de codificacion: " + e, e); //$NON-NLS-1$ } // LISTA DE CERTIFICADOS: obtenemos la lista de certificados ASN1Set certificates = null; certificates = CAdESUtils.fetchCertificatesList(signerCertificateChain); // 2. RECIPIENTINFOS final Info infos = CAdESUtils.getEnvelopeInfo(parameters.getContent(), config, certDest, cipherKey); // 4. SIGNERINFO // raiz de la secuencia de SignerInfo final ASN1EncodableVector signerInfos = new ASN1EncodableVector(); final TBSCertificateStructure tbs2 = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate())); final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs2.getIssuer()), tbs2.getSerialNumber().getValue()); final SignerIdentifier identifier = new SignerIdentifier(encSid); // AlgorithmIdentifier final AlgorithmIdentifier digAlgId = new AlgorithmIdentifier( new ASN1ObjectIdentifier(AOAlgorithmID.getOID(digestAlgorithm)), new DERNull()); // // ATRIBUTOS final ASN1EncodableVector contextExpecific = CAdESUtils.generateSignerInfo(signerCertificateChain[0], digestAlgorithm, parameters.getContent(), policy, null); this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); final ASN1Set signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); // digEncryptionAlgorithm final AlgorithmIdentifier encAlgId; try { encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$ } catch (final Exception e) { throw new IOException("Error de codificacion: " + e, e); //$NON-NLS-1$ } final ASN1OctetString sign2; try { sign2 = firma(signatureAlgorithm, keyEntry); } catch (final AOException ex) { throw new IOException("Error en la firma electronica: " + ex, ex); //$NON-NLS-1$ } signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, null // unsignedAttr )); final ASN1Set certrevlist = null; // construimos el Signed And Enveloped Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, new SignedAndEnvelopedData(new DERSet(infos.getRecipientInfos()), new DERSet(digestAlgs), infos.getEncInfo(), certificates, certrevlist, new DERSet(signerInfos))) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.envelopers.cades.CAdESEPESSignedAndEnvelopedData.java
License:Open Source License
/** Método que inserta remitentes en el "OriginatorInfo" de un sobre * de tipo AuthenticatedEnvelopedData.// w w w. j av a 2 s.com * @return La nueva firma AuthenticatedEnvelopedData con los remitentes que * tenía (si los tuviera) con la cadena de certificados * nueva. * @throws IOException */ byte[] addOriginatorInfo(final InputStream data, final P7ContentSignerParameters parameters, final X509Certificate[] signerCertificateChain, final PrivateKeyEntry keyEntry, final AdESPolicy policy) throws IOException { // boolean isValid = false; byte[] retorno = null; // LEEMOS EL FICHERO QUE NOS INTRODUCEN 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 DERObjectIdentifier doi = (DERObjectIdentifier) e.nextElement(); if (doi.equals(PKCSObjectIdentifiers.signedAndEnvelopedData)) { // Contenido de Data final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final SignedAndEnvelopedData signEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject()); // Obtenemos los originatorInfo final ASN1EncodableVector signerInfos = new ASN1EncodableVector(); final Enumeration<?> signers = signEnv.getSignerInfos().getObjects(); while (signers.hasMoreElements()) { signerInfos.add((ASN1Sequence) signers.nextElement()); } ASN1EncodableVector signCerts = new ASN1EncodableVector(); // Si no hay certificados, se deja como esta. if (signerCertificateChain.length != 0) { // algoritmo final String signatureAlgorithm; final String digestAlgorithm; final ASN1EncodableVector digestAlgs = new ASN1EncodableVector(); signatureAlgorithm = parameters.getSignatureAlgorithm(); digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm); AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); digestAlgs.add(digAlgId); final TBSCertificateStructure tbs2; try { tbs2 = TBSCertificateStructure.getInstance( ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate())); } catch (final CertificateEncodingException ex) { throw new IOException("Error en la codificacion del certificado del firmante", ex); //$NON-NLS-1$ } final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber( X500Name.getInstance(tbs2.getIssuer()), tbs2.getSerialNumber().getValue()); final SignerIdentifier identifier = new SignerIdentifier(encSid); // AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(AOAlgorithmID.getOID(digestAlgorithm)), new DERNull()); // // ATRIBUTOS final ASN1EncodableVector contextExpecific; try { contextExpecific = CAdESUtils.generateSignerInfo(signerCertificateChain[0], digestAlgorithm, parameters.getContent(), policy, null); } catch (final CertificateEncodingException ex) { throw new IOException("Error en la codificacion del certificado del firmante", ex); //$NON-NLS-1$ } catch (final NoSuchAlgorithmException ex) { throw new IOException("Error generacion del SignerInfo", ex); //$NON-NLS-1$ } this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); final ASN1Set signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); final ASN1Set unSignedAttr = null; // digEncryptionAlgorithm final SignerInfo nuevoSigner = CAdESUtils.signAndEnvelope(keyEntry, signatureAlgorithm, digAlgId, identifier, signedAttr, unSignedAttr, "RSA", //$NON-NLS-1$ this.signedAttr2); // introducimos el nuevo Signer signerInfos.add(nuevoSigner); // LISTA DE CERTIFICADOS: obtenemos la lista de certificados try { signCerts = CAdESUtils.loadCertificatesList(signEnv, signerCertificateChain); } catch (final CertificateEncodingException ex) { throw new IOException("Error en la codificacion de los certificados del firmante", ex); //$NON-NLS-1$ } } else { LOGGER.warning("No se ha podido obtener el certificado del nuevo firmante "); //$NON-NLS-1$ } final ASN1Set certrevlist = null; // Se crea un nuevo AuthenticatedEnvelopedData a partir de los // datos anteriores con los nuevos originantes. retorno = new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, new SignedAndEnvelopedData(signEnv.getRecipientInfos(), signEnv.getDigestAlgorithms(), signEnv.getEncryptedContentInfo(), // encInfo, new DERSet(signCerts), // certificates, certrevlist, // certrevlist, new DERSet(signerInfos))).getEncoded(ASN1Encoding.DER); } return retorno; }
From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java
License:Open Source License
/** Obtiene un <code>Info</code> que contiene los RecipientInfos y el EncryptedContentInfo. * @param data Datos a incluir en el sobre * @param config Configuración de cifrado a aplicar * @param certDest Certificados de los destinatarios * @param cipherKey Clave de cifrado//from w w w.j a v a 2 s . co m * @return <code>Info</code> que contiene los RecipientInfos y el EncryptedContentInfo * @throws IOException en caso de error de entrada / salida * @throws CertificateEncodingException en caso de errores de codificación en los certificados */ static Info getEnvelopeInfo(final byte[] data, final AOCipherConfig config, final X509Certificate[] certDest, final SecretKey cipherKey) throws IOException, CertificateEncodingException { // Reiniciamos las dos variables final Info infos = new Info(); final ASN1EncodableVector recipientInfos = new ASN1EncodableVector(); X509Certificate cert; TBSCertificateStructure tbs; IssuerAndSerialNumber isse; RecipientIdentifier rid; PublicKey pubKey; AlgorithmIdentifier keyEncAlg; SubjectPublicKeyInfo info; // Cifrado de la clave byte[] encryptedKey = null; // generamos el contenedor de cifrado RecipientInfo recipient = null; for (final X509Certificate element : certDest) { cert = element; tbs = TBSCertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate())); // Obtenemos el Isuer & serial number isse = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()), tbs.getSerialNumber().getValue()); // Creamos el recipientInfo rid = new RecipientIdentifier(isse); // Obtenemos la clave publica pubKey = cert.getPublicKey(); // obtenemos la informacion de la clave publica info = tbs.getSubjectPublicKeyInfo(); // obtenemos el algoritmo de cifrado. keyEncAlg = info.getAlgorithm(); try { // ciframos la clave encryptedKey = cipherKey(pubKey, cipherKey); } catch (final Exception e) { LOGGER.severe("Error durante el proceso cifrado de la clave: " + e); //$NON-NLS-1$ } // creamos el recipiente con los datos del destinatario. final KeyTransRecipientInfo keyTransRecipientInfo = new KeyTransRecipientInfo(rid, keyEncAlg, new DEROctetString(encryptedKey)); recipient = new RecipientInfo(keyTransRecipientInfo); // Lo añadimos al recipiente de destinatarios. recipientInfos.add(recipient); } // 3. ENCRIPTEDCONTENTINFO try { infos.setEncInfo(getEncryptedContentInfo(data, config, cipherKey)); } catch (final Exception e) { LOGGER.severe("Error durante el proceso cifrado de la clave: " + e); //$NON-NLS-1$ } infos.setRecipientInfos(recipientInfos); return infos; }