JavaUtils

生成随机字符串

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)