码迷,mamicode.com
首页 > 编程语言 > 详细

Java 获取字符串Hash值

时间:2014-09-09 12:18:08      阅读:1072      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   java   for   div   

Java 生成字符串的Hash值:

   /**
     * A hashing method that changes a string (like a URL) into a hash suitable for using as a
     * disk filename.
     */
    public static String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        // http://stackoverflow.com/questions/332079
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append(‘0‘);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

 

Java 获取字符串Hash值

标签:style   blog   http   color   os   io   java   for   div   

原文地址:http://www.cnblogs.com/oxgen/p/3962085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!