javaprimary-keysecure-random

Java SecureRandom generate URL like Medium.com (Random 12 characters)


Instead of using the Long type do the Primary key, I found seems Medium.com using 12 characters. Can anyone let me know the algorithm or similar way to create it.

For example: medium.com/**/nosuchmethoderror-in-log4j-issue-3a80f0c412c

Hash (current timestamp + blabla +...) => like: 3a80f0c412c

I heard using Java SecureRandom quite good but I haven't really understood it. Someone can show me the code? Tks


Solution

  • If you just need 12 random characters, you could generate a UUID and then take a substring:

    UUID uuid = UUID.randomUUID();
    System.out.println(uuid.toString().replaceAll("-", "").substring(0, 12));
    

    Demo