MD5编码

作者: 花花是男神 | 来源:发表于2018-06-06 11:03 被阅读0次

    进行MD5编码,编码后的字符串肯定是唯一的,并且只会包含0-F这样的字符,符合文件的命名规则。

    那么我们就写一个方法用来将字符串进行MD5编码,代码如下所示:

    public 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 String bytesToHexString(byte[] bytes) {  
      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();  
      }
    

    相关文章

      网友评论

          本文标题:MD5编码

          本文链接:https://www.haomeiwen.com/subject/izfbsftx.html