Wednesday, August 13, 2008

Programmatically creating DotNetNuke user passwords

When programmatically creating a DotNetNuke portal, the CreatePortal method API expects passwords that are already encrypted. In DotNetNuke, by default the passwords are encrypted using one way Triple DES algorithm. There is existing functionality in DotNetNuke that can be reused to encrypt plain text passwords. Listed below is some sample code that can be used.

Requirements: The code listed below uses the following classes that can be found in the assembly: DotNetNuke.dll

  • DotNetNuke.Security.PortalSecurity
  • DotNetNuke.Common.Globals
  • DotNetNuke.Entities.Users.UserController

   1: string userName = "sampleUserName";
   3: //generate a random 8 character password
   4: string password = UserController.GeneratePassword(8)
   6: //get the machine's encryption key
   7: string key = Convert.ToString(Globals.HostSettings["EncryptionKey"]);
   9: //encrypt the password with the machines encryption key
  10: PortalSecurity portalSecurity = new PortalSecurity();
  11: password = portalSecurity.Encrypt(key, password);

Line 4: We generate a random 8 character password using the static GeneratePassword in the UserController class. It is not required to use the method, you can substitute it with you own logic. Keep in mind to satisfy the password requirements configured in DotNetNuke.
Line 7: When users login, DotNetNuke encrypts the plain text password using the encryption key that is stored in the web.config. It then compares it to the encrypted version that is stored in the database, and if they match the login successed. We have to use the same encryption key or else the user will not be able to login even if he uses the right password. We use the Globals class which contains a collection of utility functions, to retrieve the encryption key.
Line 11: We use the Encrypt method of the PortalSecurity class to encrypt the password.

Subscribe to my feed in your favorite feed reader