Java mail signature encryption

Source: Internet
Author: User
Tags mailmessage

1. download the latest bc package, bcmail-jdk15on-149.jar, bcprov-jdk15on149.jar, bcpkix-jdk15on-149.jar, and import the project.

2. Compile the SignedMail class. Create a SignedMail class.

Package com. suresec. simplemail; import java. math. bigInteger; import java. security. keyPair; import java. security. keyPairGenerator; import java. security. keyStore; import java. security. noSuchAlgorithmException; import java. security. noSuchProviderException; import java. security. privateKey; import java. security. publicKey; import java. security. secureRandom; import java. security. security; import java. security. cert. C ErtStore; import java. security. cert. certificate; import java. security. cert. collectionCertStoreParameters; import java. security. cert. x509Certificate; import java. util. arrays; import java. util. date; import java. util. enumeration; import java. util. vector; import javax. mail. internet. mimeBodyPart; import javax. mail. internet. mimeMultipart; import javax. security. auth. x500.X500Principal; import javax. security. auth. x5 00. x500PrivateCredential; import org. bouncycastle. asn1.ASN1EncodableVector; import org. bouncycastle. asn1.ASN1Set; import org. bouncycastle. asn1.DERObjectIdentifier; import org. bouncycastle. asn1.DEROctetString; import org. bouncycastle. asn1.DERSet; import org. bouncycastle. asn1.cms. attributeTable; import org. bouncycastle. asn1.pkcs. attribute; import org. bouncycastle. asn1.pkcs. PKCSObjectIdentifiers; import org. B Ouncycastle. asn1.smime. SMIMECapabilitiesAttribute; import org. bouncycastle. asn1.smime. SMIMECapability; import org. bouncycastle. asn1.smime. SMIMECapabilityVector; import org. bouncycastle. asn1.smime. SMIMEEncryptionKeyPreferenceAttribute; import org. bouncycastle. asn1.x509. basicConstraints; import org. bouncycastle. asn1.x509. generalName; import org. bouncycastle. asn1.x509. generalNames; import org. bouncycastle. a Sn1.x509. x509Extension; import org. bouncycastle. asn1.x509. x509Extensions; import org. bouncycastle. jce. PKCS10CertificationRequest; import org. bouncycastle. jce. provider. bouncyCastleProvider; import org. bouncycastle. mail. smime. SMIMEEnvelopedGenerator; import org. bouncycastle. mail. smime. SMIMEException; import org. bouncycastle. mail. smime. SMIMESignedGenerator; import org. bouncycastle. mail. smime. SMIMEUtil; impor T org. bouncycastle. x509.X509V1CertificateGenerator; import org. bouncycastle. x509.X509V3CertificateGenerator; import org. bouncycastle. x509.extension. authorityKeyIdentifierStructure; import org. bouncycastle. x509.extension. subjectKeyIdentifierStructure; public class SignedMail {public static String ROOT_ALIAS = "root"; public static String INTERMEDIATE_ALIAS = "intermediate"; public static String END_ENTIT Y_ALIAS = "end"; private static final int VALIDITY_PERIOD = 365*24*60*60*1000; // one yearpublic static char [] KEY_PASSWD = "suresec ". toCharArray (); public static KeyStore credentials; public static PrivateKey; public static Certificate [] chain; public static X509Certificate cert; public static CertStore certsAndCRLs; public boolean init () throws Exception {Security. addProvider (new BouncyCastl EProvider (); credentials = createCredentials (); key = (PrivateKey) credentials. getKey (END_ENTITY_ALIAS, KEY_PASSWD); chain = credentials. getCertificateChain (END_ENTITY_ALIAS); certsAndCRLs = CertStore. getInstance ("Collection", new CollectionCertStoreParameters (Arrays. asList (chain), "BC"); cert = (X509Certificate) chain [0]; return true;}/*** Create a KeyStore containing the private credential with * cert Ificate chain and a trust anchor. */public static KeyStore createCredentials () throws Exception {KeyStore store = KeyStore. getInstance ("JKS"); store. load (null, null); X500PrivateCredential rootCredential = createRootCredential (); X500PrivateCredential interCredential = createIntermediateCredential (rootCredential. getPrivateKey (), rootCredential. getCertificate (); X500PrivateCredential endCredential = crea TeEndEntityCredential (interCredential. getPrivateKey (), interCredential. getCertificate (); store. setCertificateEntry (rootCredential. getAlias (), rootCredential. getCertificate (); store. setKeyEntry (endCredential. getAlias (), endCredential. getPrivateKey (), KEY_PASSWD, new Certificate [] {endCredential. getCertificate (), interCredential. getCertificate (), rootCredential. getCertificate ()}); return store ;}/*** Generate a X500PrivateCredential for the end entity. */public static encrypt createEndEntityCredential (PrivateKey caKey, X509Certificate caCert) throws Exception {KeyPair endPair = generateRSAKeyPair (); X509Certificate endCert = encrypt (endPair. getPublic (), caKey, caCert); return new X500PrivateCredential (endCert, endPair. getPrivate (), END_ENTITY_ALIAS);}/*** Generate a samp Le V3 certificate to use as an end entity certificate */public static X509Certificate partition (PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception {X509V3CertificateGenerator certGen = new partition (); certGen. setSerialNumber (BigInteger. valueOf (1); certGen. setIssuerDN (caCert. getSubjectX500Principal (); certGen. setNotBefore (new Date (System. curren TTimeMillis (); certGen. setNotAfter (new Date (System. currentTimeMillis () + VALIDITY_PERIOD); certGen. setSubjectDN (new X500Principal ("CN = Test End Certificate"); certGen. setPublicKey (entityKey); certGen. setSignatureAlgorithm ("SHA1WithRSAEncryption"); certGen. addExtension (X509Extensions. authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure (caCert); certGen. addExtension (X509Extensions. subjec TKeyIdentifier, false, new SubjectKeyIdentifierStructure (entityKey); certGen. addExtension (X509Extensions. basicConstraints, true, new BasicConstraints (false); // certGen. addExtension (X509Extensions. keyUsage, true, new KeyUsage (KeyUsage. digitalSignature | KeyUsage. keyEncipherment); return certGen. generateX509Certificate (caKey, "BC");}/*** Generate a X500PrivateCredential for the intermediate entity. * /Public static cipher (PrivateKey caKey, X509Certificate caCert) throws Exception {KeyPair interPair = generateRSAKeyPair (); X509Certificate interCert = cipher (interPair, caKey, caCert, interPair. getPrivate (), INTERMEDIATE_ALIAS);}/*** Generate a sample V3 certificate to use as an intermediate CA c Ertificate */public static X509Certificate encrypt (KeyPair pair, PrivateKey caKey, X509Certificate caCert) throws Exception {PKCS10CertificationRequest request = generateRequest (pair); // validate the certification requestif (! Request. verify ("BC") {System. out. println ("request failed to verify! "); System. exit (1);} // create the certificate using the information in the requestX509V3CertificateGenerator certGen = new X509V3CertificateGenerator (); certGen. setSerialNumber (BigInteger. valueOf (System. currentTimeMillis (); certGen. setIssuerDN (caCert. getSubjectX500Principal (); certGen. setNotBefore (new Date (System. currentTimeMillis (); certGen. setNotAfter (new Date (System. currentTimeMillis () + VALIDIT Y_PERIOD); certGen. setSubjectDN (new X500Principal (request. getcertifrequrequestinfo (). getSubject (). getEncoded (); certGen. setPublicKey (request. getPublicKey ("BC"); certGen. setSignatureAlgorithm ("SHA1WithRSAEncryption"); certGen. addExtension (X509Extensions. authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure (caCert); certGen. addExtension (X509Extensions. subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure (request. getPublicKey ("BC"); certGen. addExtension (X509Extensions. basicConstraints, true, new BasicConstraints (true); // certGen. addExtension (X509Extensions. keyUsage, true, new KeyUsage (KeyUsage. keyCertSign | KeyUsage. cRLSign); // certGen. addExtension (X509Extensions. extendedKeyUsage, true, new ExtendedKeyUsage (KeyPurposeId. id_kp_serverAuth); // extract the extension req Uest attributeASN1Set attributes = request. getCertificationRequestInfo (). getAttributes (); for (int I = 0; I! = Attributes. size (); I ++) {Attribute attr = Attribute. getInstance (attributes. getObjectAt (I); // process extension requestif (attr. getAttrType (). equals (PKCSObjectIdentifiers. pkcs_9_at_extensionRequest) {X509Extensions = X509Extensions. getInstance (attr. getAttrValues (). getObjectAt (0); Enumeration e = extensions. oids (); while (e. hasMoreElements () {DERObjectIdentifier oid = (DERObjectIdentifier) e. nextElement (); X509Extension ext = extensions. getExtension (oid); certGen. addExtension (oid, ext. isCritical (), ext. getValue (). getOctets () ;}} X509Certificate issuedCert = certGen. generateX509Certificate (caKey, "BC"); return issuedCert;} public static PKCS10CertificationRequest generateRequest (KeyPair pair) throws Exception {// create a SubjectAlternativeName extension valueGeneralNames subjectAltNames = new GeneralNames (new GeneralName (GeneralName. rfc822Name, "test@test.test"); // create the extensions object and add it as an attributeVector oids = new Vector (); Vector values = new Vector (); oids. add (X509Extensions. subjectAlternativeName); values. add (new X509Extension (false, new DEROctetString (subjectAltNames); X509Extensions extensions = new X509Extensions (oids, values); Attribute attribute Attribute = new Attribute (PKCSObjectIdentifiers. pkcs_9_at_extensionRequest, new DERSet (extensions); return new PKCS10CertificationRequest ("SHA1withRSA", new X500Principal ("CN = Test Certificate"), pair. getPublic (), new DERSet (attribute), pair. getPrivate ();}/*** Generate a X500PrivateCredential for the root entity. */public static response createRootCredential () throws Exception {KeyPair rootPair = generateRSAKeyPair (); X509Certificate rootCert = generateRootCert (rootPair); return new response (rootCert, rootPair. getPrivate (), ROOT_ALIAS);}/*** Create a random 1024 bit RSA key pair */public static KeyPair generateRSAKeyPair () throws Exception {KeyPairGenerator kpGen = KeyPairGenerator. getInstance ("RSA", "BC"); kpGen. initialize (1024, new SecureRandom (); return kpGen. generateKeyPair ();}/*** Generate a sample V1 certificate to use as a CA root certificate */public static X509Certificate generateRootCert (KeyPair pair) throws Exception {X509V1CertificateGenerator certGen = new X509V1CertificateGenerator (); certGen. setSerialNumber (BigInteger. valueOf (1); certGen. setIssuerDN (new X500Principal ("CN = Test CA Certificate"); certGen. setNotBefore (new Date (System. currentTimeMillis (); certGen. setNotAfter (new Date (System. currentTimeMillis () + VALIDITY_PERIOD); certGen. setSubjectDN (new X500Principal ("CN = Test CA Certificate"); certGen. setPublicKey (pair. getPublic (); certGen. setSignatureAlgorithm ("SHA1WithRSAEncryption"); return certGen. generateX509Certificate (pair. getPrivate (), "BC");} public MimeMultipart createMultipartWithSignature (PrivateKey key, X509Certificate cert, CertStore certsAndCRLs, MimeBodyPart dataPart) throws Exception {// create some smime capabilities in case someone wants to define signedAttrs = new ASN1EncodableVector (); SMIMECapabilityVector caps = new SMIMECapabilityVector (); caps. addCapability (SMIMECapability. aES256_CBC); caps. addCapability (SMIMECapability. dES_EDE3_CBC); caps. addCapability (SMIMECapability. rC2_CBC, 128); signedAttrs. add (new SMIMECapabilitiesAttribute (caps); signedAttrs. add (new SMIMEEncryptionKeyPreferenceAttribute (SMIMEUtil. createIssuerAndSerialNumberFor (cert); // set up the generatorSMIMESignedGenerator gen = new SMIMESignedGenerator (); gen. addSigner (key, cert, SMIMESignedGenerator. DIGEST_SHA256, new AttributeTable (signedAttrs), null); gen. addCertificatesAndCRLs (certsAndCRLs); // create the signed messagereturn gen. generate (dataPart, "BC");} public MimeMultipart signMail (MimeBodyPart dataPart) {try {return createMultipartWithSignature (this. key, this. cert, this. certsAndCRLs, dataPart);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} return null;}/*** email encryption * @ param dataPart * @ return */public MimeBodyPart encryptMail (MimeBodyPart dataPart) {SMIMEEnvelopedGenerator gen = new sender (); mimeBodyPart envPart; try {envPart = gen. generate (dataPart, SMIMEEnvelopedGenerator. DES_EDE3_CBC, "BC"); return envPart;} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (NoSuchProviderException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (SMIMEException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return null;} // public static MimeMessage createMimeMessage (// Object content, // String contentType, // MimeMessage message) // throws MessagingException // {// message. setContent (content, contentType); // message. saveChanges (); // return message ;//}}

3. Make a slight modification to the SimpleMailSender class and add the previous blog post.

MimeBodyPart dataPart = new MimeBodyPart (); dataPart. setText ("Hello world! "); // MimeMultipart multiPart = signMail. signMail (dataPart); // mailMessage = signMail. createMimeMessage (multiPart, multiPart. getContentType (), mailMessage); // mailMessage. setText (mailContent); // send the email MimeBodyPart envPart = signMail. encryptMail (dataPart); mailMessage. setContent (envPart. getContent (), envPart. getContentType (); Transport. send (mailMessage );

4. Run the program to view the digital signature file. As shown in:

650) this. width = 650; "title =" 2.png" src = "http://www.bkjia.com/uploads/allimg/131228/155J043A-0.png"/>

This article is from the "openldap" blog and will not be reposted!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.