如何保证MD5加密结果在不同的环境下都相同
首先我们来看一下Java是如何实现MD5的:
?
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Digest {
??? private static MessageDigest md5=null;
??? public static String getDigest(String msg) throws UnsupportedEncodingException, NoSuchAlgorithmException {
??????? if(null == md5) {
??????????? md5=MessageDigest.getInstance("MD5");
??????? }
??????? byte[] byteArray=null;
??????? byteArray=msg.getBytes();
??????? byte[] md5Bytes=md5.digest(byteArray);
??????? StringBuffer hexValue=new StringBuffer();
??????? for(int i=0; i < md5Bytes.length; i++) {
??????????? int val=((int)md5Bytes[i]) & 0xff;
??????????? if(val < 16)
??????????????? hexValue.append("0");
??????????? hexValue.append(Integer.toHexString(val));
??????? }
??????? return hexValue.toString();
??? }
???
??? public static void main(String []args) throws UnsupportedEncodingException, NoSuchAlgorithmException{
??????? System.out.println(getDigest("test测试"));
??? }
}
?
通过上面的代码我们会发现一个问题:
byteArray=msg.getBytes();
在不同的环境下获得的结果可能是不一样的,这样也造成很多MD5结果不一样。
所以要保证在不同环境下MD5结果相同那么必须使用相同的字符编码,比如:byteArray=msg.getBytes("ISO-8859-1");
?