2008年9月24日 星期三

[備忘記]如何做密碼編碼?

方法1(使用 seam api):
import org.jboss.seam.security.digest.DigestUtils;

public String hash(String password){
 return new DigestUtils().md5Hex(password.getBytes("Big5"));
}


方法2(使用 Apache Jakarta 專案的 Commons codec):
import org.apache.commons.codec.digest.DigestUtils;

public String hash(String password){
 //1.3版的只有提供 MD5、SHA 的編碼,如果想要完整的 SHA 編碼,請下載 1.4-snapshot
 return new DigestUtils().md5Hex(password.getBytes("Big5"));
}

方法3(使用 java api + seam api):
import java.security.MessageDigest;
import org.jboss.seam.util.Hex;

public String hash(String password){
 try{
  //MessageDigest 可傳入的演算法參數有 MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512
  MessageDigest md = MessageDigest.getInstance("MD5");
  //字串轉 byte 可指定不同的 charsetName,但其中的差異要傳入的 password 非單純的英數字組合才看的出來
  md.update(password.getBytes("Big5"));
  return new String(Hex.encodeHex(md.digest()));
 }catch(Exception e){
  throw new RuntimeException(e.getMessage());
 }
}