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

  • shariq

    Member
    September 22, 2018 at 9:49 pm

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

  • Parul

    Member
    September 23, 2018 at 5:05 am

    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

Popular Salesforce Videos