⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sendencryptedmail.java

📁 用java实现的对电子邮件进行加密解密及签名的算法接口
💻 JAVA
字号:
package cn.edu.scut.smimeapi;

import java.io.*;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;

import org.bouncycastle.mail.smime.SMIMEEnvelopedGenerator;


import javax.security.auth.login.LoginException;
import cn.edu.scut.certutils.certexceptions.NoTokenPresentException;
import java.security.cert.CertificateException;
import javax.xml.parsers.*;
import org.xml.sax.*;

import cn.edu.scut.certmgr.*;
import javax.activation.CommandMap;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.activation.MailcapCommandMap;

/**
 * <p>Title: </p>
 *
 * <p>Description: a public class to create a Encrypted Mail</p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 *
 * @author lyh
 * @version 1.0
 */
public class SendEncryptedMail extends SendMail
{
static
   {
   /* Add BC */
   Security.addProvider(new BouncyCastleProvider());

     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);

   }

    public SendEncryptedMail()
  {

  }
  /**
    * Return a MimeMessage which has been Encrypted by X509Certificate,the default
    * encrypt alg is DES_EDE3_CBC.
    *
    * @param cert the X509Certificate to encrypt the message for.
    * @param msg  the MimeMessage to be encrypted .
    * @return the  MimeMessage which has been Encrypted by X509Certificate.
    * @throws Exception
     */

  public MimeMessage CreateEncrytedMail(X509Certificate cert,MimeMessage msg)
  throws Exception
 {
       SMIMEEnvelopedGenerator  gen = new SMIMEEnvelopedGenerator();
       gen.addKeyTransRecipient((X509Certificate)cert);
        //
         MimeBodyPart mp = gen.generate(msg, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC");
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         mp.writeTo(out);

         MimeMessage encryptedMessage = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));

         /* Set all original MIME headers in the encrypted message */
         Enumeration headers = msg.getAllHeaderLines();
         while (headers.hasMoreElements())
         {
           String headline=(String) headers.nextElement();
          /* Make sure not to override any content-* headers from the original message */
           if (!headline.toLowerCase().startsWith("content-"))
               encryptedMessage.addHeaderLine(headline);
         }

        return encryptedMessage;
  }
  /**
      * Return a MimeMessage which has been Encrypted by X509Certificate.
      *
      * @param cert the X509Certificate to encrypt the message for.
      * @param encalg the String which mark the alg to be used for. It supports
      * SMIMEEnvelopedGenerator.DES_EDE3_CBC,SMIMEEnvelopedGenerator.AES128_CBC,
      * SMIMEEnvelopedGenerator.AES192_CBC, SMIMEEnvelopedGenerator.AES256_CBC
      * SMIMEEnvelopedGenerator.RC2_CBC AND SO ON.
      * @param msg  the MimeMessage to be encrypted .
      * @return the  MimeMessage which has been Encrypted by X509Certificate.
      * @throws Exception
     */
  public MimeMessage CreateEncrytedMail(X509Certificate cert,String encalg,MimeMessage msg)
  throws Exception
 {
       SMIMEEnvelopedGenerator  gen = new SMIMEEnvelopedGenerator();
       gen.addKeyTransRecipient((X509Certificate)cert);
        //

         MimeBodyPart mp = gen.generate(msg, encalg, "BC");
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         mp.writeTo(out);
         MimeMessage encryptedMessage = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));

         /* Set all original MIME headers in the encrypted message */
         Enumeration headers = msg.getAllHeaderLines();
         while (headers.hasMoreElements())
         {
           String headline=(String) headers.nextElement();
          /* Make sure not to override any content-* headers from the original message */
           if (!headline.toLowerCase().startsWith("content-"))
               encryptedMessage.addHeaderLine(headline);
         }

        return encryptedMessage;
  }

/*
  public static void main(String args[])
    {

  try
      {
       SendEncryptedMail sem=new SendEncryptedMail();
       sem.setAccount("smtp.163.com","waitfor_mylove@163.com","198097");
       MimeMessage testmsg=sem.CreateMail("waitfor_mylove@163.com","waitfor_mylove@163.com","test send encypted mail by 06-03-30","hello,world!");

       //String attachmentfile="E:\\test.zip";
       //MimeMessage testmsg=sem.CreateMailWithAttchment("yhliu@saturn.tanglab.net","yhliu@saturn.tanglab.net","test send mail","hello,world!",attachmentfile);


      ProviderConfiguration pConfig = new ProviderConfiguration("Config.xml");

      //=============epass2000

       ConfigFileItem configItem = pConfig.getConfigItem(1);
       KeyStoreManager ksMgr = new KeyStoreManager(configItem, "1234".toCharArray());//密码

      //===================Local KeyStore
      // ConfigFileItem configItem = pConfig.getConfigItem(0);
      //  KeyStoreManager ksMgr = new KeyStoreManager(configItem, "tanglab".toCharArray());//密码


       KeyStoreCertificates storeCerts = ksMgr.getAllCertificates();
       String Certalias=null;
       for(int i=0;i<storeCerts.itemCount();i++)
       {
         String alias=storeCerts.getCertItem(i).getAlias();
         Certalias=alias;
       }
       Certificate cert = ksMgr.getCertificate(Certalias);
       System.out.println("Certalias:"+Certalias);

       MimeMessage testmsg3= sem.CreateEncrytedMail((X509Certificate)cert,testmsg);
       sem.Send(testmsg3);
       }


       catch (Exception ex)
       {
          System.err.println("发送邮件异常"+ex);
       }

  }
*/


}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -