将字符串转换用MD5加密

原文链接: http://www.cnblogs.com/e241138/archive/2012/07/22/2603901.html

在Java中可以用MessageDigest这个类进行操作。

下面通过代码来进行解释:

    public static String EncoderByMd5(String str) throws Exception {
        MessageDigest md5=MessageDigest.getInstance("md5");//返回实现指定摘要算法的 MessageDigest 对象。
        md5.update(str.getBytes());//先将字符串转换成byte数组,再用byte 数组更新摘要
        byte[] nStr = md5.digest();//哈希计算,即加密
        return bytes2Hex(nStr);//加密的结果是byte数组,将byte数组转换成字符串
    }

下面是bytes2Hex(...)的具体代码:

private static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;

        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

 另:在JavaScript中貌似没有类似的方法,所以只能自己实现了。网上有很多已发布的,这里就不引用了。

这是JavaScript加密字符串的页面:http://e24113.sinaapp.com/md5.html

转载于:https://www.cnblogs.com/e241138/archive/2012/07/22/2603901.html

猜你喜欢

转载自blog.csdn.net/weixin_30481087/article/details/94797551