How to Generate the Random String using Apex in Salesforce

I recently worked on customer support cases in our Salesforce org. To manage case tracking and ensure each case has a unique identifier, we have to generate a random alphanumeric reference code for each new case. Customers will use this code to reference their case in communications.

To solve this, I created an apex class to generate a random string consisting of uppercase letters and numbers.

In this Salesforce tutorial, I will explain how to generate a random string using Apex in Salesforce.

Random String in Salesforce Apex

In Salesforce Apex, a random string refers to a sequence of characters generated randomly. It is generally used for scenarios like generating temporary passwords, tokens, or unique identifiers.

Apex doesn’t have a direct method for generating random strings, but we can create one by combining various methods such as Math.random(), character arrays, and string manipulation.

Generate Random String using Crypto.getRandomInteger() in Salesforce Apex

In Salesforce Apex, the Crypto.getRandomINteger() method is used to generate a random integer that can be used to select characters from a string of possible values, like letters and numbers.

To generate random strings using Crypto.getRandomInteger() in Salesforce Apex, navigate to the developer console, then create a new Apex Class and enter the code below.

public class RandomStringGenerator {
    public static String generateRandomString(Integer len) {
        final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        String randStr = '';
        while (randStr.length() < len) {
            Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
            randStr += chars.substring(idx, idx+1);
        }
        return randStr;
    }
}

To call the class, launch the Apex anonymous window and enter the code below to generate the random string in the debug.

Integer length = 10;
String randomStr = RandomStringGenerator.generateRandomString(length);
System.debug('Generated Random String: ' + randomStr);

In the anonymous code, we set the length of the random string to 10 and called the class method RandomStringGenerator with the method generateRandomString().

After executing the anonymous code, the execution log window will display a 10-digit random string in the debug.

How to generate random string in Salesforce Apex

This way, we can generate a random string using the Crypto.getRandomInteger() method in Salesforce Apex.

Generate a Random String using the Math.random() method in Salesforce Apex

To generate a random string or code using the Math.random() method in Salesforce Apex, navigate to the Salesforce developer console and follow the steps below.

1. Create a new Apex class in the developer console and enter the code below.

public class RandomCodeGenerator {
    public static Long generateTenDigitRandomNumber() {

        Long randomTenDigitNumber = (Long)(Math.random() * 9000000000L) + 1000000000L;
        return randomTenDigitNumber;
    }
}

Now, launch the Apex anonymous window and execute the code below to call the class method.

Long randomNumber = RandomCodeGenerator.generateTenDigitRandomNumber();
System.debug('Random 10-digit number: ' + randomNumber);

Now, in the execution log window, we will see a random 10-digit number generated in the debug.

Salesforce Apex generate random 10 digit string

This way, we can generate a random string in Salesforce Apex using the Math.random() method.

Generate a Random String using Crypto.generateAesKey in Salesforce Apex

To generate a random string using the Crypto.generateAesKey() method in Salesforce Apex, create a new Apex class and follow the code structure below.

public class RandomStringGenerator {
    public static String generateRandomString() {
        Blob aesKey = Crypto.generateAesKey(128);
        String randomString = EncodingUtil.base64Encode(aesKey);

        System.debug('Generated Random String: ' + randomString);

        return randomString;
    }
}

Now, to call the above class method for generating a random string, execute the code below in the Apex anonymous window.

RandomStringGenerator.generateRandomString();

In the execution log window, you will see the output as a random string in debug.

Generate a random string in Salesforce Apex

This way, we can generate a random String using Crypto.generateAesKey() method in Salesforce Apex.

Conclusion

In this Salesforce tutorial, we have learned about the various methods to generate random strings. We successfully generated strings using methods such as Crypto.getRandomInteger(), Math.random(), and Crypto.genrateAeskey().

By following these methods, you can efficiently generate random strings in your Salesforce environment.

You may also like to read.

live webinar

Salesforce Data Cloud with Agentforce Data Library

In this live webinar, we will showcase how Salesforce AI Agents use business data and documents to provide intelligent responses using Agentforce Data Library and Salesforce Data Cloud.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.