Salesforce and Random Identifiers

Salesforce generates random identifiers for internal “Id” field. However if we are looking for business identifiers we are left with AutoNumber which generates the sequential numbers. If we are looking for a business identifier with some entropy to enhance the security of it, Salesforce leaves us to custom develop it.

A Blog entry talks about few options of Salesforce random number generation. To ensure the entropy Crypto class is preferred over Math.random (I assume this is analogs to Math.random and SecureRandom in Java). But crypto’s getRandomInteger class doesn’t generate consistent length random number which might be a problem.

Here is a simple Apex class which generates consistent length (10 digits) random identifiers.

public with sharing class RandomNumberGenerator {

    public static String generateRandomNumber() {
        String randomNumber = generate();
        
        if (randomNumber.length() < 10) {
            String randomNumber2 = generate();
            randomNumber = randomNumber + randomNumber2.substring(0, 10 - randomNumber.length());
        }
        
        return randomNumber;
    }
    
    public static String generateIdentifier(String prefix) {
        return prefix + '-' + generateRandomNumber();
    }
    
    private static String generate() {
        return String.valueOf(Math.abs(Crypto.getRandomInteger()));
    }
}

Sample identifiers generated using this class:

1180069336
2399158548
1189306484
1453886484
2110260656
1859434534
9810064217
3475893391
8950171981
8562056261