首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

怎么保证MD5加密结果在不同的环境上都相同

2012-12-18 
如何保证MD5加密结果在不同的环境下都相同首先我们来看一下Java是如何实现MD5的:?import java.io.Unsuppor

如何保证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");

?

热点排行