How to set password of a user using Apex

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

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.

System.setPassword('005300000123aBc','A$tr0ngPW');
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);