Some times we required to generate some unique random id for externalId purpose or sometime we need random string. salesforce OOTB provides some util class to generate it using Crypto and EncodingUtils classes. here is how we can generate unique random id with 32, 48 and 64 length of ids.
Generate unique random Id in apex
following code returns 32 characters length of id. we can also generate 48 and 64 char length string changing AES key to 128,192 and 256.
Blog b = Crypto.GenerateAESKey(128);
String randomId = EncodingUtil.ConvertTohex(b);
system.debug(randomId); //output: 192bad2864edddb416595e1231a57bde
we can also do substring to make it any length of string you want.
Blob b = Crypto.GenerateAESKey(128);
String randomId = EncodingUtil.ConvertTohex(b);
string 10charId = randomId.SubString(0,10);
system.debug(10charId); //output: 47b33e0808
Source:
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_restful_crypto.htm
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_restful_encodingUtil.htm