项目用到给用户密码加密,下载了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