List of usage examples for org.bouncycastle.asn1.smime SMIMECapability dES_CBC
ASN1ObjectIdentifier dES_CBC
To view the source code for org.bouncycastle.asn1.smime SMIMECapability dES_CBC.
Click Source Link
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 w w w . j a v a 2 s. com "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: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. *///from w w w . j a v 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/*from ww w . j a v a 2s. 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.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 .j av a2 s . c om*/ 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:de.mendelson.util.security.BCCryptoHelper.java
/** * Create a pkcs7-signature of the passed content and returns it * * @param chain certificate chain, chain[0] is the signers certificate * itself//w ww. ja v a 2s .c o m * @param embeddOriginalData Indicates if the original data should be * embedded in the signature * */ public byte[] sign(byte[] content, Certificate[] chain, Key key, String digest, boolean embeddOriginalData) throws Exception { X509Certificate x509Cert = this.castCertificate(chain[0]); PrivateKey privKey = this.getPrivateKey(key); CMSSignedDataGenerator signedDataGenerator = new CMSSignedDataGenerator(); //add dont know 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)); if (digest.equalsIgnoreCase(ALGORITHM_SHA1)) { signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA1withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_MD5)) { signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("MD5withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA224)) { signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA224withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA256)) { signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA256withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA384)) { signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA384withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA512)) { signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA512withRSA", privKey, x509Cert)); } else { throw new Exception("sign: Signing digest " + digest + " not supported."); } //add cert store List<Certificate> certList = Arrays.asList(chain); Store certStore = new JcaCertStore(certList); signedDataGenerator.addCertificates(certStore); if (content == null) { throw new Exception("sign: content is absent"); } CMSTypedData processable = new CMSProcessableByteArray(content); CMSSignedData signatureData = signedDataGenerator.generate(processable, embeddOriginalData); return (signatureData.getEncoded()); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * @param chain certificate chain, chain[0] is the signers certificate * itself Signs the data using S/MIME 3.1 - dont use if for S/MIME 3.2 or * higher/*from w w w . j a v a 2 s. c o m*/ */ public MimeMultipart sign(MimeBodyPart body, Certificate[] chain, Key key, String digest) throws Exception { X509Certificate x509Cert = this.castCertificate(chain[0]); PrivateKey privKey = this.getPrivateKey(key); //call this generator with a S/MIME 3.1 compatible constructor as it defaults to RFC 5751 (other micalg values) SMIMESignedGenerator signedGenerator = new SMIMESignedGenerator(SMIMESignedGenerator.RFC3851_MICALGS); //add dont know 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)); if (digest.equalsIgnoreCase(ALGORITHM_SHA1)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA1withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA224)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA224withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA256)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA256withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA384)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA384withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA512)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA512withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_MD5)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("MD5withRSA", privKey, x509Cert)); } else { throw new Exception("sign: Signing digest " + digest + " not supported."); } //add cert store List<Certificate> certList = Arrays.asList(chain); Store certStore = new JcaCertStore(certList); signedGenerator.addCertificates(certStore); MimeMultipart signedPart = signedGenerator.generate(body); return (signedPart); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * @param chain certificate chain, chain[0] is the signers certificate * itself Signs the data using S/MIME 3.1 - dont use if for S/MIME 3.2 or * higher/*w w w .ja v a 2 s . c om*/ */ public MimeMultipart sign(MimeMessage message, Certificate[] chain, Key key, String digest) throws Exception { if (message == null) { throw new Exception("sign: Message is absent"); } X509Certificate x509Cert = this.castCertificate(chain[0]); PrivateKey privKey = this.getPrivateKey(key); SMIMESignedGenerator signedGenerator = new SMIMESignedGenerator(SMIMESignedGenerator.RFC3851_MICALGS); //add dont know 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)); if (digest.equalsIgnoreCase(ALGORITHM_SHA1)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA1withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA224)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA224withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA256)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA256withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA384)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA384withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_SHA512)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("SHA512withRSA", privKey, x509Cert)); } else if (digest.equalsIgnoreCase(ALGORITHM_MD5)) { signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC") .setSignedAttributeGenerator(new AttributeTable(signedAttrs)) .build("MD5withRSA", privKey, x509Cert)); } else { throw new Exception("sign: Signing digest " + digest + " not supported."); } //add cert store List<Certificate> certList = Arrays.asList(chain); Store certStore = new JcaCertStore(certList); signedGenerator.addCertificates(certStore); MimeMultipart multipart = signedGenerator.generate(message); return (multipart); }
From source file:gov.nih.nci.cacis.nav.SendSignedMail.java
License:BSD License
private SMIMESignedGenerator createSigner(Certificate[] chain, PrivateKey privateKey) { final SMIMECapabilityVector capabilities = new SMIMECapabilityVector(); capabilities.addCapability(SMIMECapability.dES_EDE3_CBC); capabilities.addCapability(SMIMECapability.rC2_CBC, 128); capabilities.addCapability(SMIMECapability.dES_CBC); final ASN1EncodableVector attributes = new ASN1EncodableVector(); attributes.add(new SMIMEEncryptionKeyPreferenceAttribute( new IssuerAndSerialNumber(new X509Name(((X509Certificate) chain[0]).getIssuerDN().getName()), ((X509Certificate) chain[0]).getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); final SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.addSigner(privateKey, (X509Certificate) chain[0], "DSA".equals(privateKey.getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1 : SMIMESignedGenerator.DIGEST_MD5, new AttributeTable(attributes), null); return signer; }
From source file:hk.hku.cecid.edi.as2.module.test.IncomingMessageProcessorTest.java
License:Open Source License
private MimeBodyPart signMessage(MimeBodyPart bodyPart) throws Exception { X509Certificate cert = partnershipDVO.getVerifyX509Certificate(); /* Create the 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 X509Name(cert.getIssuerDN().getName()), cert.getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.setContentTransferEncoding("base64"); signer.addSigner(keyMan.getPrivateKey(), partnershipDVO.getVerifyX509Certificate(), SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(attributes), null); // Add the list of certs to the generator ArrayList certList = new ArrayList(); certList.add(cert);//from w ww. j a va2s . co m CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); signer.addCertificatesAndCRLs(certs); // Sign body part MimeMultipart mm = signer.generate(bodyPart, "BC"); InternetHeaders headers = new InternetHeaders(); boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true")).booleanValue(); headers.setHeader("Content-Type", isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " ")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mm.writeTo(baos); MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray()); return signedPart; }
From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java
License:Open Source License
/** * Signs the encapsulated MIME body part. * // www.j ava 2 s .c om * @return an S/MIME message encapsulating the signed MIME body part. * @throws SMimeException if unable to sign the body part. */ public SMimeMessage sign() throws SMimeException { try { if (privateKey == null) { throw new SMimeException("Private key not found"); } try { setDefaults(); /* Create the 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 X509Name(cert.getIssuerDN().getName()), cert.getSerialNumber()))); attributes.add(new SMIMECapabilitiesAttribute(capabilities)); SMIMESignedGenerator signer = new SMIMESignedGenerator(); signer.setContentTransferEncoding(getContentTransferEncoding()); signer.addSigner(privateKey, cert, getDigestAlgorithm(), new AttributeTable(attributes), null); /* Add the list of certs to the generator */ ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), SECURITY_PROVIDER); signer.addCertificatesAndCRLs(certs); /* Sign the body part */ MimeMultipart mm = signer.generate(bodyPart, SECURITY_PROVIDER); InternetHeaders headers = new InternetHeaders(); boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true")) .booleanValue(); headers.setHeader("Content-Type", isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " ")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mm.writeTo(baos); MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray()); return new SMimeMessage(signedPart, this); } catch (org.bouncycastle.mail.smime.SMIMEException ex) { throw new SMimeException(ex.getMessage(), ex.getUnderlyingException()); } } catch (Exception e) { throw new SMimeException("Unable to sign body part", e); } }