在Java中使用MessageDigest实现MD5,sha1等加密
import java.security.*;
2 ?2 |+ e: W& ` V/ ?# I; V2 D) j3 O: z" m8 e. C% e+ K& t
/*- b3 i2 I: F! V; G; J6 D
* TestEncrypt.java
+ H+ r) h6 G% a * Author: MKing
1 c* i5 A6 b0 @7 E: e: _+ { * Last Date: 2005-11-21
. ]2 l8 {$ F4 M* G * Description: A test progrm to encrypt a string using MD5 or SHA-1,etc.7 |7 m$ ]6 P0 O, v6 h$ G& Y
*/
% r) l' Q& w) c- L
7 @8 H" B/ N3 u% [: Q1 M" Dpublic class TestEncrypt {: z/ O0 M- p8 `' u
! v6 S* [+ j1 j. J: X# c) Y public TestEncrypt() {}
; n, l# }& _& V7 N5 f7 {6 f ! x4 K- O1 l. Z9 b' i
public String Encrypt(String strSrc,String encName) {
7 e! B# S4 S/ P- I //parameter strSrc is a string will be encrypted,1 r5 k+ c8 \7 G3 V) L
//parameter encName is the algorithm name will be used.
) s6 d5 b4 }4 e% i. Y6 S //encName dafault to "MD5"
9 e- ]0 b; B2 m- U MessageDigest md=null;0 Q& f# @% q, b2 l; M( Q2 L
String strDes=null;; A' S# ~1 I# ^! ~, {( u# c6 [; O: G
5 d# |! p9 Q$ i1 V# B9 Z- C% z# d5 r- c
byte[] bt=strSrc.getBytes();6 l& ]8 N" o a, Q0 y- f
try {7 y' h, \/ m1 G" @" f- j
if (encName==null||encName.equals("")) {
( y8 Z3 \$ Z$ q/ D( [ encName="MD5";
+ \, i3 U4 Y5 a$ F8 H1 \ }
" U' D% z) ]& X md=MessageDigest.getInstance(encName);
& H6 u+ _7 `* I4 m md.update(bt);
3 ~3 ~" @% Y9 |" L1 n8 Q* I) k strDes=bytes2Hex(md.digest()); //to HexString
1 q2 E( J; }% `( t, A& u- J. w }
# Z% U0 e' ]! d; ? catch (NoSuchAlgorithmException e) {/ Z3 t7 a* z( O
System.out.println("Invalid algorithm.");
8 t% Z S6 U. ?8 \8 A return null;
6 j. A1 q& G" n* H }4 n2 W* ]3 r# r+ Q9 k/ B) ~
return strDes;
) H/ A+ ~, G6 u7 P- g, ? }! k7 o4 @, y2 m$ o9 P. D) u
: r c& h& O3 w0 g+ T8 }/ t
public String bytes2Hex(byte[]bts) {8 n" A) V7 K! j* H4 B0 w6 Z7 t
String des="";/ O' F$ q3 M3 [9 {
String tmp=null;
) G! r3 F' i7 T! Y7 | for (int i=0;i<bts.length;i++) {
7 \3 M9 g; Q0 @7 q4 { tmp=(Integer.toHexString(bts & 0xFF));
' B! ^3 s- }1 C8 H, J! M if (tmp.length()==1) {
" r; T5 s& M7 Y3 n0 u des+="0";
/ w, x/ s' r2 }! Z }
) Z- Y3 C# ^ y: l$ I* | des+=tmp;4 I- n$ S6 s7 |- Q0 n
}, V& v, e- R& _: v, \3 f0 Q
return des;; U+ L3 \6 ^" k- J3 I1 ~! N) V
}1 X9 x+ _3 i$ P. m5 h; c
% Z/ _5 W1 `2 f7 }% h3 ~3 k% z ? public static void main(String[]args) { M, X, q% b# x4 Y' x
TestEncrypt te=new TestEncrypt();: ~) {2 p( }. i1 ~4 h2 C6 a# I
String strSrc="可以加密汉字.Oh,and english";. b/ X! P, v3 q$ [. d* I
System.out.println("Source String:"+strSrc);" O, S, c3 e4 {5 E' A! o0 E9 q
System.out.println("Encrypted String:");: h/ w$ l H7 b, t- u
System.out.println("Use Def:"+te.Encrypt(strSrc,null));+ c- E. b. I0 A. I
System.out.println("Use MD5:"+te.Encrypt(strSrc,"MD5"));9 ^0 k6 S1 x! y# v4 ^
System.out.println("Use SHA:"+te.Encrypt(strSrc,"SHA-1"));1 K$ L9 } L: s
System.out.println("Use SHA-256:"+te.Encrypt(strSrc,"SHA-256"));* O8 P5 V3 L% s/ l0 i. W
}$ P4 m/ \' J) A$ F2 @& J
}