0

I need to obtain unique primary which is less than 24 char length, I have tried using SecureRandom and i read its documentation says A cryptographically strong random number. is this Reliable ? all I need to have Alphanumeric with max of 24 char length.

Like,

BQkjEQwAFi0YLBsOHzkLADAiAhshFw
NQEfJR0oJzclNwEOBAE2EicjBTYwHg
JygOFhsZJSkNNTgQERg7PREcOxUCFA
Fw46JykWJhQuAxs5NCEzDAQHBikcGw
LhAOHBUbMSYgPDI2Chk4LAs3KTMgLA
FCgmATotByYnLTw0HwQUDgspOS0fBA
LSkCHCofHxc9GhcSLiEgHSEzDgwODw
LDENBg0cKzAKHxg8Hzk4Ei8MIjs6FQ
PSIhCjo6DxMHETkyNQUOFgU1MzEEBg
EwQTJx0bMCYgAQsaJzgJOwEAMy0ZHw

the below code gave me the same but i don't know how far i can relay on SecureRandom, since this is primary key for XYZ transactions and expected to have 200k plus transaction on one day. latest we will retain 180 days transactions in Oracle DB.

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;

import java.nio.ByteBuffer;
import java.security.SecureRandom;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


import static org.slf4j.LoggerFactory.getLogger;

public class RandomGenUtil {

    private static RandomGenUtil instance;
    private static final int RANDOM_ID_SEED_LENGTH = 22;
    private static final String ALL_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String SMALL_CAPS = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUMBERS = "0123456789";
    private static final String RANDOM_ID_SEED = ALL_CAPS + SMALL_CAPS + NUMBERS;

    private static SecureRandom randomGen;

    public RandomGenUtil() {
        if (RandomGenUtil.randomGen == null) {
            RandomGenUtil.randomGen = new SecureRandom();
        }
    }

    public static RandomGenUtil getInstance() {
        if (RandomGenUtil.instance == null) {
            RandomGenUtil.instance = new RandomGenUtil();
        }
        return RandomGenUtil.instance;
    }

    public static String generateRandomId() {
        int i = 0;
        StringBuilder builder = new StringBuilder();
        while (i < RANDOM_ID_SEED_LENGTH) {
            builder.append((char) randomGen.nextInt(RANDOM_ID_SEED.length()));
            i++;
        }

        ByteBuffer bb = ByteBuffer.wrap(builder.toString().getBytes());
        return Base64.encodeBase64URLSafeString(bb.array());

    }
}
jcrshankar
  • 1,165
  • 8
  • 25
  • 45

0 Answers0