JavaUtils

作者: 鲁克巴克诗 | 来源:发表于2017-02-20 14:41 被阅读134次

    生成随机字符串

    public static String getRandomString(int length) { //length表示生成字符串的长度  
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
        Random random = new Random();     
        StringBuffer sb = new StringBuffer();     
        for (int i = 0; i < length; i++) {     
            int number = random.nextInt(base.length());     
            sb.append(base.charAt(number));     
        }     
        return sb.toString();     
     } 
    

    Md5加密

     public static String md5(String string) {
            byte[] hash;
            try {
                //获取指定加密字符串的摘要
                hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("Huh, MD5 should be supported?", e);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("Huh, UTF-8 should be supported?", e);
            }
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) hex.append("0");
                //通过b & 0xFF运算获得int值,再通过Integer.toHexString转成16进制字符串。
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        }
    

    相关文章

      网友评论

          本文标题:JavaUtils

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