How to set password of a user using Apex

  • Only system admin can do this.
  • Password should be compliant to password policy set at profile level of User.

The first parameter of that function call is the actual id of the user object. User Ids start with 005 and are 15 or 18 characters long and second parameter is password string.

Complex password generation TIPS
final String selectionString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
Integer idNum = Math.mod(Math.abs(Crypto.getRandomInteger()), selectionString.length());
String randomPassword = selectionString.substring(idNum, idNum+1);