Generate Random text using Salesforce Apex

Generate Random text using Salesforce Apex

Check the following sample apex code which generates random 10 characters using EncodingUtil.base64Encode(), Crypto.generateAesKey(), replaceAll() and substring() methods.

Sample Apex Code:

String tempKey = EncodingUtil.base64Encode(
    Crypto.generateAesKey(256)
);
tempKey = tempKey.replaceAll( '[+/=]', '');
System.debug(
    tempKey.substring(0, 10)
);

Crypto.generateAesKey() – It is used to generate an Advanced Encryption Standard (AES) key.
EncodingUtil.base64Encode() – It is used to convert the AES key Blob value to an unencoded String representation.
replaceAll() – Replaces +, / and = characters.
substring() – It is used to get the 10 characters.

Leave a Reply