Activity Forums Salesforce® Discussions How to generate the random string or random password using Apex?

  • Ajay Prakash

    Member
    April 30, 2016 at 3:08 pm

    @Himanshu

    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

  • madhulika shah

    Member
    September 4, 2018 at 11:00 am

    Hi,

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

  • Avnish Yadav

    Member
    September 4, 2018 at 11:02 am

    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.

  • shariq

    Member
    September 13, 2018 at 8:00 pm

    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.

  • Parul

    Member
    September 19, 2018 at 5:33 pm

    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.

Popular Salesforce Blogs