專案用到給使用者密碼加密,下載了apache的commons-codec jar包,貼出對幾種加密演算法實現的demo。記之。

commons-codec-1.10下載連結:

http://commons.apache.org/proper/commons-codec/download_codec.cgi

package demo;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.language.Metaphone;
import org.apache.commons.codec.language.RefinedSoundex;
import org.apache.commons.codec.language.Soundex;

public class CodecDemo {
	public static void main(String[] args) throws DecoderException {

		String strPsw = "123456"; // 原密碼
		String ecPsw = ""; // 加密密碼
		String dcPsw = ""; // 解密密碼

		// md5:訊息摘要演算法第五(Message Digest Algorithm)
		System.out.println("MD5:");

		ecPsw = DigestUtils.md5Hex(strPsw);

		System.out.println("Original:" + strPsw);
		System.out.println("MD5:" + ecPsw + "\n");

		// SHA1:安全雜湊演算法(Secure Hash Algorithm)
		System.out.println("SHA1:");

		ecPsw = DigestUtils.sha1Hex(strPsw);

		System.out.println("Original:" + strPsw);
		System.out.println("SHA1:" + ecPsw + "\n");

		// BASE64演算法:網路上最常見的用於傳輸8Bit位元組程式碼的編碼方式之一
		System.out.println("Base64:");

		byte[] ec = null;
		byte[] dc = null;
		// 加密
		ec = Base64.encodeBase64(strPsw.getBytes(), true);
		ecPsw = new String(ec).replaceAll("\r|\n", ""); // str.replaceAll("\r|\n",
														// "") 去掉str末尾換行
		// 解密:(base64Psw=new String(ec)為要解密的字串)
		dc = Base64.decodeBase64(ecPsw.getBytes());
		dcPsw = new String(dc).replaceAll("\r|\n", "");

		System.out.println("Original:" + strPsw);
		System.out.println("Base64:" + ecPsw);
		System.out.println("deBase64:" + dcPsw + "\n");

		// Hex編解碼
		System.out.println("Hex:");

		char[] cc = null;
		cc = Hex.encodeHex(strPsw.getBytes(), true);
		ecPsw = new String(cc).replace("\r|\n", "");

		dc = Hex.decodeHex(ecPsw.toCharArray());
		dcPsw = new String(dc).replaceAll("\r|\n", "");

		System.out.println("Original:" + strPsw);
		System.out.println("Hex:" + ecPsw);
		System.out.println("deHex:" + dcPsw + "\n");

		// Metaphone及 Soundex編碼
		// Metaphone 建立出相同的key給發音相似的單字, 比 Soundex 還要準確, 但是 Metaphone 沒有固定長度,
		// Soundex 則是固定第一個英文字加上3個數字. 這通常是用在類似音比對, 也可以用在 MP3 的軟體開發.
		System.out.println("Metaphone or Soundex:");

		Metaphone metaphone = new Metaphone();
		RefinedSoundex refinedSoundex = new RefinedSoundex();
		Soundex soundex = new Soundex();
		for (int i = 0; i < 2; i++) {
			String str = (i == 0) ? "resume" : "resin";
			String mString = null;
			String rString = null;
			String sString = null;
			try {
				mString = metaphone.encode(str);
				rString = refinedSoundex.encode(str);
				sString = soundex.encode(str);
			} catch (Exception ex) {
				;
			}
			System.out.println("Original:" + str);
			System.out.println("Metaphone:" + mString);
			System.out.println("RefinedSoundex:" + rString);
			System.out.println("Soundex:" + sString + "\n");
		}
	}

}

參考文章:

http://www.oschina.net/question/12_4981?fromerr=ZTPdDmBt