使用apache的commons-codec jar包进行Base64编码/解码,md5加密
package base64;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
public class MD5Demo {
public static void main(String[] args) {
String str = "你好,很高兴认识你!";
try {
String encode = Base64.encodeBase64String(str.getBytes("utf-8"));
System.out.println(encode);
String decode = new String(Base64.decodeBase64(encode), "utf-8");
System.out.println(decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String code = Base64.encodeBase64String(DigestUtils.md5(str));
System.out.println(code);
}
}
输出结果分别为
5L2g5aW977yM5b6I6auY5YW06K6k6K+G5L2g77yB
你好,很高兴认识你!
L9aMgawEobXiPtOoDBXsrg==
JDK本身也自带Base64的类,不过并不太好找
com.sun.org.apache.xerces.internal.impl.dv.util.Base64是一个,好像还有其他的。JDK1.8则有个java.util.Base64类。
JDK本身也自带MD5摘要算法功能,java.security.MessageDigest;
public static void main(String[] args) {
String str = "你好,很高兴认识你!";
try {
byte[] data = str.getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("md5");
byte[] md5 = md.digest(data);
// md.update(data);
// byte[] md5 = md.digest();
String code = Base64.encodeBase64String(md5);
System.out.println(code);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("加密失败", e);
}
}
其中md.digest(data);等同于md.update(data);md.digest();其内部调用关系如下:
public byte[] digest(byte[] input) {
update(input);
return digest();
}
另外不能连续调用update(byte[] input),会影响算法结果,即:
{ /*错误*/
md.update(data);
md.update(data);
md.digest();
}
{ /*错误*/
md.update(data);
md.digest(data);
}
{ /*正确*/
md.update(data);
md.digest();
}
{ /*正确*/
md.update(data);
}
MessageDigest源码中有个state属性,update会更改其属性,digest后会改回默认,大概是因为这个属性的原因吧,engineUpdate()方法的源码没有找到,不清楚state是否真的对其造成影响,但是多次update后得到的md5并不一样
// The state of this digest
private static final int INITIAL = 0;
private static final int IN_PROGRESS = 1;
private int state = INITIAL;
/**
* Updates the digest using the specified byte.
*
* @param input the byte with which to update the digest.
*/
public void update(byte input) {
engineUpdate(input);
state = IN_PROGRESS;
}
/**
* Completes the hash computation by performing final operations
* such as padding. The digest is reset after this call is made.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] digest() {
/* Resetting is the responsibility of implementors. */
byte[] result = engineDigest();
state = INITIAL;
return result;
}