2009年10月9日 星期五

JavaMail實作寄件功能

package com.nelson.util;

import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;


/**
* 此類別提供寄件之功能.
* <p>
* 文件建立日期:2009/10/09
* @author Nelson Chen
*/
public class SendMail {

private String from = null;
private String to = null;
private List<String> cc = new ArrayList<String>();
private List<String> bcc = new ArrayList<String>();
private String smtphost = null;
private int port = 25;
private boolean auth = false;

/**
 * Constructor of SendMail
 */

public SendMail(){
}

 /**
 * Constructor of SendMail
 * @param from 寄件者
 * @param to 收件者
 * @param cc 附本
 * @param bcc 密件附本
 * @param smtphost smtp伺服器主機
 * @param port smtp伺服器連結埠
 * @param auth smtp伺服器是否需要驗證
 */
public SendMail(String from,String to,List<String> cc,List<String> bcc,String smtphost,int port,boolean auth){

 this.from = from;
 this.to = to;
 this.cc = cc;
 this.bcc = bcc;
 this.smtphost = smtphost;
 this.port = port;
 this.auth = auth;
}

/**
 * 此method為簡易的寄件功能
 * @param user 寄件者帳號,smtp主機伺服器驗證使用。
 * @param password 寄件者密碼,smtp主機伺服器驗證使用。
 * @param subject 寄件主旨
 * @param content 寄件內容
 * @param debug 是否偵錯
 * @param HTML 寄件內容格式為text/html
 */
public void SimpleSend(final String user,final String password,String subject,String content,boolean debug,String HTML){

 Properties props = System.getProperties();
 props.put("mail.smtp.host",smtphost);
 props.put("mail.smtp.port",port);
 props.put("mail.smtp.quitwait", "false");
 if(auth){
  props.put("mail.smtp.socketFactory.port", port);
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.socketFactory.fallback", "false");
 }

//採用認證,因為使用外部主機
 props.put("mail.smtp.auth",auth);
 Session session = null;
 if(auth){
  //建立Session,並傳入認證之帳號、密碼
  session = Session.getDefaultInstance(props,
    new javax.mail.Authenticator(){
     protected PasswordAuthentication getPasswordAuthentication(){
      return new PasswordAuthentication(user,password);
     }
    });
 }else{
  session = Session.getInstance(props);
 }

 session.setDebug(debug);
 //建立Message
 Message msg = new MimeMessage(session);
 try{
  //設定送件者
  msg.setFrom(new InternetAddress(from,from.substring(1,from.indexOf('@')),"Big5"));
  //設定郵件主旨
  msg.setSubject(new String(subject.getBytes("Big5")));
  //設定郵件寄件時間
  msg.setSentDate(new Date());
  //設定收件者
  if(to==null || to.equals("")){
  }else{
   msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to,to.substring(1,to.indexOf('@')),"Big5"));
  }

  //設定收件者附本
  int i=0;
  int iSize = cc.size();
  Iterator<String> it = cc.iterator();
  InternetAddress[] iaddress = new InternetAddress[iSize];
  String itvalue = null;
  while(it.hasNext()){
   itvalue = (String)it.next();
   iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
   i++;
  }
  msg.setRecipients(Message.RecipientType.CC,iaddress);
//設定收件者密件附本
i=0;
  iSize = bcc.size();
  it = bcc.iterator();
  iaddress = new InternetAddress[iSize];
  while(it.hasNext()){
   itvalue = (String)it.next();
   iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
   i++;
  }
  msg.setRecipients(Message.RecipientType.BCC,iaddress);

//設定寄件內容
  if(content==null || content.equals("")){
  }else{
   MimeBodyPart mbp1 = new MimeBodyPart();
   mbp1.setText(new String(content.getBytes("Big5")));
   MimeMultipart mp1 = new MimeMultipart();
   mp1.addBodyPart(mbp1);
   msg.setContent(mp1);
  }

  //設定寄件內容為HTML格式
  if(HTML==null || HTML.equals("")){
  }else{
   msg.setDataHandler(new DataHandler(new ByteArrayDataSource(HTML,"text/html")));
  }
  Transport ts = session.getTransport("smtp");
  if(auth){
   //大部份外部主機需帳號認證
   ts.connect(user,password);
  }else{
   ts.connect();
  }
msg.saveChanges();
  Transport.send(msg);
  System.out.println("寄件成功!!");
 }catch(Exception e){
  e.printStackTrace();
  System.out.println(e.getMessage());
 }
}

/**
 * 此method為寄件功能及可夾附件檔案
 * @param user 寄件者帳號,smtp主機伺服器驗證使用。
 * @param password 寄件者密碼,smtp主機伺服器驗證使用。
 * @param subject 寄件主旨
 * @param content 寄件內容
 * @param fileName 附件檔案
 * @param debug 是否偵錯
 */

public void SendFile(final String user,final String password,String subject,String content,List<String> fileName,boolean debug){
Properties props = System.getProperties();
props.put("mail.smtp.host",smtphost);
props.put("mail.smtp.port",port);
props.put("mail.smtp.quitwait", "false");
if(auth){
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
}

//採用認證,因為使用外部主機
props.put("mail.smtp.auth",auth);
Session session = null;
if(auth){
//建立Session,並傳入認證之帳號、密碼
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user,password);
}
});
}else{
session = Session.getInstance(props);
}
session.setDebug(debug);
//建立Message
MimeMessage msg = new MimeMessage(session);
try{
//設定送件者
msg.setFrom(new InternetAddress(from,from.substring(1,from.indexOf('@')),"Big5"));
//設定郵件主旨
msg.setSubject(new String(subject.getBytes("Big5")));
//設定郵件寄件時間
msg.setSentDate(new Date());
//設定收件者
if(to==null || to.equals("")){
}else{
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to,to.substring(1,to.indexOf('@')),"Big5"));
}
//設定收件者附本
int i=0;
int iSize = cc.size();
Iterator<String> it = cc.iterator();
InternetAddress[] iaddress = new InternetAddress[iSize];
String itvalue = null;
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
i++;
}
msg.setRecipients(Message.RecipientType.CC,iaddress);
//設定收件者密件附本
i=0;
iSize = bcc.size();
it = bcc.iterator();
iaddress = new InternetAddress[iSize];
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
i++;
}
msg.setRecipients(Message.RecipientType.BCC,iaddress);
//設定寄件內容
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(new String(content.getBytes("Big5")));
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);

//設定夾檔附件
if(fileName==null){
}else{
it = fileName.iterator();
String file = null;
while(it.hasNext()){
file = (String)it.next();
System.out.println("fileName:"+file);
FileDataSource fds = new FileDataSource(file);
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.setDataHandler(new DataHandler(fds));
//解決夾檔之檔名中文亂碼問題
//MimeUtility.encodeWord(fds.getName())
mbp2.setFileName(MimeUtility.encodeWord(fds.getName(),"Big5",null));
mp.addBodyPart(mbp2);
}
}
msg.setContent(mp);
Transport ts = session.getTransport("smtp");
if(auth){
//大部份外部主機需帳號認證
ts.connect(user,password);
}else{
ts.connect();
}
msg.saveChanges();
Transport.send(msg);
System.out.println("寄件成功!!");
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}

/**
* 驗證SendMail功能是否正確
*/
public static void main(String[] args){
List<String> fileName = new ArrayList<String>();
fileName.add("d:\\MyData\\壽生經.doc");
fileName.add("d:\\MyData\\壽生經疏文.doc");
String user = null;
String password = "aaaaaa";
String subject = "=====使用Java實作smtp寄件功能!!=====";
String content = "=====使用Java實作smtp寄件功能!!=====";
String HTML="<HTML><HEAD><TITLE>"+subject+"</TITLE></HEAD><BODY><A HREF=\"http://fubonshop.com/momo_a/click.aspx?rl=http%3A%2F%2Fwww%2Emomoshop%2Ecom%2Etw%2Factivity%2Fedm%2Ejsp%3Fpn%3D090928182508%26ctype%3DE%26cid%3D0928me%26oid%3D13%26sdiv%3Dedm01&project_no=2173&user_no=78081&Link_no=2798&Trace_No=4\">看不到本封電報或遺失圖檔,請按此>>></A><BR><H1>"+subject+"</H1><HR><A HREF=\"http://tw.rd.yahoo.com/referurl/hp/1024/me/news/*http://tw.news.yahoo.com/\">Yahoo新聞</A><IMG SRC=\"http://l.yimg.com/f/a/tw/sophia/694404_sw1_mail_100809_1007give_170x120_1.gif\"></BODY></HTML>";

boolean debug = true;
SendMail sm = new SendMail();
sm.from = "aaaaaa@gmail.com";
sm.to = "aaaaaa@gmail.com";
sm.cc.add("aaaaaa@yahoo.com.tw");
sm.cc.add("aaaaaa@pchome.com.tw");
sm.bcc.add("aaaaaa@kbronet.com.tw");
sm.smtphost = "smtp.gmail.com";
sm.port = 465;
sm.auth = true;

user = sm.from;
sm.SimpleSend(user, password, subject, content, debug, HTML);
content = "=====使用Java實作smtp寄件功能!!=====";
sm.SendFile(user, password, subject, content, fileName, debug);
sm = null;
}
}


使用Java實作TripleDES之加密、解密功能!

package com.nelson.util;
import java.security.Key;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
/**
* 此類別提供TripleDES之加解密功能.
*
* 文件建立日期:2009/10/08
* @author Nelson Chen
*/
public class DESedeEncryption {
private static String algorithm = "DESede";
private static Key key = null;
private static Cipher cipher = null;
private static SecretKeyFactory keyFactory = null;
private static DESedeKeySpec keySpec = null;
/**
* 此method切始化加解密之共用鑰匙,其中產生共用之鑰匙規範可以自己決定。 *
* @param chartCode 文字編碼:UTF-8,UTF-16
* @param strKeySpec 欲產生共用鑰匙之規範,其長度需大約24。
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
*/
private static void setUp(String chartCode,String strKeySpec)
throws NoSuchAlgorithmException,
UnsupportedEncodingException,
InvalidKeyException,
InvalidKeySpecException,
NoSuchPaddingException{
keyFactory = SecretKeyFactory.getInstance(algorithm);
if(strKeySpec==null || strKeySpec.equals("")){
//若沒有提供鑰匙規範,則改以下面之值取代!
strKeySpec = "Your secret Key phrase!!";
}
keySpec = new DESedeKeySpec(strKeySpec.getBytes(chartCode));
key = keyFactory.generateSecret(keySpec);
cipher = Cipher.getInstance(algorithm);
}
/**
* 此method之功能為加密
* @param input 欲加密之文字
* @param chartCode 文字編碼:UTF-8,UTF-16
* @param strKeySpec 欲產生共用鑰匙之規範,其長度需大約24。
* @return 回傳加密後之文字
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws UnsupportedEncodingException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static String encrypt(String input,String chartCode,String strKeySpec)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException,
UnsupportedEncodingException,
NoSuchPaddingException,
InvalidKeySpecException,
NoSuchAlgorithmException{
DESedeEncryption.setUp(chartCode,strKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] bAInput = input.getBytes(chartCode);
return (new BASE64Encoder()).encode(cipher.doFinal(bAInput));
}
/**
* 此method之功能解密
* @param encryptString 加密後之文字
* @param chartCode 文字編碼:UTF-8,UTF-16
* @param strKeySpec 欲產生共用鑰匙之規範,其長度需大約24。
* @return 回傳解密後之文字
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws UnsupportedEncodingException
* @throws IOException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static String decrypt(String encryptString,String chartCode,String strKeySpec)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException,
UnsupportedEncodingException,
IOException,
NoSuchPaddingException,
InvalidKeySpecException,
NoSuchAlgorithmException{
DESedeEncryption.setUp(chartCode,strKeySpec);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] bPlanText = cipher.doFinal((new BASE64Decoder()).decodeBuffer(encryptString));
return new String(bPlanText,chartCode);
}
/**
* 驗證加密、解密功能是否正確!!
*/
public static void main(String[] args){
String input = "Nelson111111";
String chartCode = "UTF-8";
String strKeySpec = null;
String strKeySpec1 = "222222222222222222222222";
try{
String strEncrption = encrypt(input,chartCode,strKeySpec);
String strDecrption = decrypt(strEncrption,chartCode,strKeySpec);
System.out.println("Input:"+input+",Encryption:"+strEncrption);
System.out.println("Input:"+input+",Decryption:"+strDecrption);
strEncrption = encrypt(input,chartCode,strKeySpec1);
strDecrption = decrypt(strEncrption,chartCode,strKeySpec1);
System.out.println("Input:"+input+",Encryption:"+strEncrption);
System.out.println("Input:"+input+",Decryption:"+strDecrption);
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}

2009年10月8日 星期四

使用Java實作單向加密(MD5,SHA-1)功能

package com.nelson.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;
/**
* 此類別提供文字加密功能其加密之演算法可為MD5,SHA-1,SHA-256,SHA-384,SHA-512等.
*
* 文件建立日期:2009/10/08
* @author Nelson Chen
*
*/
public class Encryption {
public Encryption(){
}
/**
* 此method提供加密之功能.
* @param strPlanText 欲加密的文字.
* @param strAlgorithm 欲使用加密的演算法:MD5,SHA-1,SHA-256,SHA-384,SHA-512.
* @param strEncoding 文字之編碼:UTF-8,UTF-16,
* @return 回傳一串加密後的文字.
*/
public String Encrypt(String strPlanText,String strAlgorithm,String strEncoding){
String strEncrypt = null;
MessageDigest md = null;
try{
if(strEncoding==null || strEncoding.equals("")){
strEncoding = "UTF-8";
}
if(strAlgorithm==null || strAlgorithm.equals("")){
strAlgorithm = "MD5";
}
byte[] bstr = strPlanText.getBytes(strEncoding);
md = MessageDigest.getInstance(strAlgorithm);
md.update(bstr);
strEncrypt = (new BASE64Encoder()).encode(md.digest());
}catch(UnsupportedEncodingException ue){
ue.printStackTrace();
System.out.println(ue.getMessage());
return null;
}catch(NoSuchAlgorithmException na){
na.printStackTrace();
System.out.println(na.getMessage());
return null;
}
return strEncrypt;
}
/**
* 驗證加密功能是否正確!!
*/
public static void main(String[] args){
String chartCode = "UTF-8";
String chartCode1 = "UTF-16";
String inputStr = "Nelson";
Encryption enc = new Encryption();
System.out.println("input String:"+inputStr+",Encryption(SHA-1):"+enc.Encrypt(inputStr, "SHA-1",chartCode));
System.out.println("input String:"+inputStr+",Encryption(SHA-256):"+enc.Encrypt(inputStr, "SHA-256",chartCode));
System.out.println("input String:"+inputStr+",Encryption(SHA-384):"+enc.Encrypt(inputStr, "SHA-384",chartCode));
System.out.println("input String:"+inputStr+",Encryption(MD5):"+enc.Encrypt(inputStr, "MD5",chartCode));
System.out.println("input String:"+inputStr+",Encryption(MD5):"+enc.Encrypt(inputStr, "MD5",chartCode1));
}
}