Java generate random string with md5 encryption

=====Java generates random strings =====

public String generateToken() {
        String s = String.valueOf(System.currentTimeMillis() + new Random().nextInt());

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("md5");
            byte[] digest = messageDigest.digest(s.getBytes());


            return Base64.getEncoder().encodeToString(digest); // If Base64 is not used, garbled characters will appear. Because the default encoding of new String may not completely contain the above byte array
             // base64 converts every three bytes into 4 bytes, so that the high bits are filled with 00, so the maximum is 63, and the minimum is 0. There are only 64 cases in total, so there will be no garbled characters.

            /**
             * Practice before Java8
             */
//            BASE64Encoder encoder = new BASE64Encoder();
//            return encoder.encode(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }

    }

=====Java generates a simple instance of MD5====

public static void main(String[] args) {  
        String password = "123456";  
  
        try {  
            MessageDigest instance = MessageDigest.getInstance("MD5"); // Get the MD5 algorithm object   
            byte [] digest = instance.digest(password.getBytes()); // Encrypt the string and return the byte array   
  
            StringBuffer sb = new StringBuffer ();  
             for ( byte b : digest) {  
                 int i = b & 0xff; // Get the lower 8-bit effective value of the byte   
                String hexString = Integer.toHexString(i); // Convert the integer to hexadecimal  
                 // System.out.println(hexString);  
  
                if (hexString.length() < 2) {  
                    hexString = "0" + hexString; // If it is 1 bit, add 0   
                }  
  
                sb.append(hexString);  
            }  
  
            System.out.println("md5:" + sb.toString());  
            System.out.println("md5 length:" + sb.toString().length());//Md5都是32位  
  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace ();  
            // If there is no such algorithm, throw an exception and will not go here   
        }  
    }  

====java generates random md5 encrypted id===

Use java's own uuid directly

public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid.toString());
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325081980&siteId=291194637