Wednesday, March 16, 2016

Generate strong random password in Apex

Hi Coders,

I thought this might be handy so thought of sharing this .

It will create a random password with specified length  

public String generateRandomString(Integer len){
        String randStr = '';
        final String upperChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        final String numChars = '0123456789';
        final String LowerChars = 'abcdefghijklmnopqrstuvwxyz';
        final String specialChars = '!#$%-_=+<>';
        while (randStr.length() < len) {
           Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), upperChars.length());
           randStr += upperChars.substring(idx, idx+1);
           idx = Math.mod(Math.abs(Crypto.getRandomInteger()), numChars.length());
           randStr += numChars.substring(idx, idx+1);
           idx = Math.mod(Math.abs(Crypto.getRandomInteger()), LowerChars.length());
           randStr += LowerChars.substring(idx, idx+1);
           idx = Math.mod(Math.abs(Crypto.getRandomInteger()), specialChars.length());
           randStr += specialChars.substring(idx, idx+1);
        }
        return randStr; 
    }

Happy Coding !!!!!!!!!!!!!!!

No comments:

Post a Comment

Tips on passing Salesforce AI Associate Certification

  🌟 Motivation to Pursue the Salesforce AI Associate Certification 🌟 The world of technology is in a state of perpetual evolution, and on...