function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SalesRedSalesRed 

Random Password Generator. Always Alphanumeric?

Hi,   I came across the following functuon for generating a random password.  I require that the password is alphanumeric.

 

I note the function does seem to return alphanumeric characters.  Does this seem correct or is it just a coincidence in the passwords I've generated so far?   I need to confirm if alphanumeric will always be returned. If so, what is the logic (explanation) for it?

 

public String generator(Integer len){
Blob blobKey = crypto.generateAesKey(128);
String key = EncodingUtil.convertToHex(blobKey);
return key.substring(0,len);
}

 

Thanks in advance for any help!

Best Answer chosen by Admin (Salesforce Developers) 
JitendraJitendra

Hi,

Your code is perfect. Please try to execute it in developer console:

Integer len = 10;
Blob blobKey = crypto.generateAesKey(128);
String key = EncodingUtil.convertToHex(blobKey);
String pwd = key.substring(0,len);
System.debug('************ '+pwd);

 variable len is the desired length of the string generated.

All Answers

JitendraJitendra

Hi,

Your code is perfect. Please try to execute it in developer console:

Integer len = 10;
Blob blobKey = crypto.generateAesKey(128);
String key = EncodingUtil.convertToHex(blobKey);
String pwd = key.substring(0,len);
System.debug('************ '+pwd);

 variable len is the desired length of the string generated.

This was selected as the best answer
SalesRedSalesRed

Hi jitendra,

 

Thanks for your help.   Regarding my question.  I do note it returns alphanumeric (always an alphabetic character & a number) in my testing so far.  Regarding variable len, I am aware it is the length of the required password.  Do you know if it is correct that it will always (100% of the time) return a combination of alphabet characters and numbers (or is it just a coincidence in my testing so far)?

 

Thanks again,

 

Fergus.

JitendraJitendra

Hi Fergus,

 

It was just coincidence in your case. It is possible that it may return only number. You can add extra condition that aftre random string generation check that it contains atleast one string otherwise again generate it.

SalesRedSalesRed

Thanks Jitendra for your help & suggestions.

nidhi aryanidhi arya
Hi ,


I have a requirement to generate unique random number when a new record gets created in the system.

i have written below line of code to generate a random string

Integer max=6;
String password=EncodingUtil.convertToHex(crypto.generateAesKey(128)).substring(1,max);
recordToUpdate.put('Seller_Code__c','S'+password);

this code is working fine.But I am not sure whether this code will generate a unique random number everytime.Can anyone help me on this?

In case if this does not generate a unique number how can i handle it.