1.新建Md5.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package
com.loger.md5;
import
java.io.UnsupportedEncodingException;
import
java.security.MessageDigest;
import
java.security.NoSuchAlgorithmException;
import
sun.misc.BASE64Encoder;
public
class
Md5 {
/**利用MD5進行加密*/
public
String EncoderByMd5(String str)
throws
NoSuchAlgorithmException, UnsupportedEncodingException{
//確定計算方法
MessageDigest md5=MessageDigest.getInstance(
"MD5"
);
BASE64Encoder base64en =
new
BASE64Encoder();
//加密后的字符串
String newstr=base64en.encode(md5.digest(str.getBytes(
"utf-8"
)));
return
newstr;
}
/**判斷用戶密碼是否正確
*newpasswd 用戶輸入的密碼
*oldpasswd 正確密碼*/
public
boolean
checkpassword(String newpasswd,String oldpasswd)
throws
NoSuchAlgorithmException, UnsupportedEncodingException{
if
(EncoderByMd5(newpasswd).equals(oldpasswd))
return
true
;
else
return
false
;
}
}
|
2.新建測試類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package
com.loger.md5;
import
java.io.UnsupportedEncodingException;
import
java.security.NoSuchAlgorithmException;
public
class
MyTest {
public
static
void
main(String[] args)
throws
NoSuchAlgorithmException, UnsupportedEncodingException {
Md5 md5 =
new
Md5();
String str =
"apple"
;
try
{
String newString = md5.EncoderByMd5(str);
System.out.println(newString);
}
catch
(NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(md5.EncoderByMd5(
"apple"
).equals(
"HzhwvidPbEmz4xoMZyiVfw=="
));
}
}
|
運行結果: