How to generate a random alpha-numeric string

前端 未结 30 3006
忘掉有多难
忘掉有多难 2020-11-21 05:38

I\'ve been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifie

30条回答
  •  深忆病人
    2020-11-21 05:59

    I found this solution that generates a random hex encoded string. The provided unit test seems to hold up to my primary use case. Although, it is slightly more complex than some of the other answers provided.

    /**
     * Generate a random hex encoded string token of the specified length
     *  
     * @param length
     * @return random hex string
     */
    public static synchronized String generateUniqueToken(Integer length){ 
        byte random[] = new byte[length];
        Random randomGenerator = new Random();
        StringBuffer buffer = new StringBuffer();
    
        randomGenerator.nextBytes(random);
    
        for (int j = 0; j < random.length; j++) {
            byte b1 = (byte) ((random[j] & 0xf0) >> 4);
            byte b2 = (byte) (random[j] & 0x0f);
            if (b1 < 10)
                buffer.append((char) ('0' + b1));
            else
                buffer.append((char) ('A' + (b1 - 10)));
            if (b2 < 10)
                buffer.append((char) ('0' + b2));
            else
                buffer.append((char) ('A' + (b2 - 10)));
        }
        return (buffer.toString());
    }
    
    @Test
    public void testGenerateUniqueToken(){
        Set set = new HashSet();
        String token = null;
        int size = 16;
    
        /* Seems like we should be able to generate 500K tokens 
         * without a duplicate 
         */
        for (int i=0; i<500000; i++){
            token = Utility.generateUniqueToken(size);
    
            if (token.length() != size * 2){
                fail("Incorrect length");
            } else if (set.contains(token)) {
                fail("Duplicate token generated");
            } else{
                set.add(token);
            }
        }
    }
    

提交回复
热议问题