Activity › Forums › Salesforce® Discussions › How to generate the random string or random password using Apex?
Tagged: Password, Random, Salesforce Apex, Salesforce Force.com, String
-
How to generate the random string or random password using Apex?
Posted by Himanshu on April 30, 2016 at 3:00 PMHow to generate the random string or random password using Apex?
Parul replied 7 years, 7 months ago 6 Members · 5 Replies -
5 Replies
-
You can use following Apex code to generate random string or random password –
Integer len = 10;
Blob blobKey = crypto.generateAesKey(128);
String key = EncodingUtil.convertToHex(blobKey);
String pwd = key.substring(0,len);you can follow the following link-
https://developer.salesforce.com/forums/?id=906F000000091GsIAI
Thanks
- [adinserter block='9']
-
Hi,
Integer len = 10;
Blob blobKey = crypto.generateAesKey(128);
String key = EncodingUtil.convertToHex(blobKey);
String pwd = key.substring(0,len); -
Hi,
Hope this will help you.
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;
}
Thanks. -
Hi,
public String testGenerate(Integer getLength)
{
String charString = ‘!@#$%^&*()nopqrstuvwABCDPQRSTUVWXYZ0123456789abcdefghijkEFGHIJKLMNOlmxyz’;
String randomNew = ”;
while (randomNew .length() < getLength){
Integer changeInt = Math.mod(Math.abs(Crypto.getRandomInteger()), charString.length());
randomNew += charString.substring(changeInt , changeInt +1);
}
return randomNew ;
}Hope this helps.
-
Hi,
Adding some code snippet
Here is a static method that accepts a desired string length as an argument. It takes a full string of ASCII numbers and letters and loops through the index of your desired string length, randomly choosing an index in the full character string.
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;
}Thanks
Log In to reply.