Mega Code Archive

 
Categories / Delphi / Strings
 

How to create a random password

Title: How to create a random password Question: You need Passwords in your application Answer: Create a Form1 with this Objects Edit1 with Edit1.Text := 13 max. Password lentgth Edit2 to display created passwords Button1 with onClick event Button1Click // this function creates a random password function RandomPwd(PWLen: integer): string; // Table of allowed password chars const XTable: string = 'ABCDEFGHIJKLMabcdefghijklm0123456789' + 'NOPQRSTUVWXYZnopqrstuvwxyz'; var N, X, Y: integer; begin N := 0; Y := Length(XTable); // first check the wanted password length // if it greater than the table-length then // ignore it because it produces a endless loop! if (PWLen Y) then begin ShowMessage('Passwort-Length too big (max. ' + IntToStr(Y) + ')'); exit; end; // now set the length of result SetLength(result, PWLen); // go to the while loop until all random chars are generated while N // generate the next random char X := Random(Y) + 1; // look if this char not exists in the result if (pos(XTable[X], result) = 0) then begin // it's a new char. Count it and put it into the result. inc(N); Result[N] := XTable[X]; end; end; end; procedure TForm1.Button1Click(Sender: TObject); begin // start the random password generating Edit2.Text := RandomPwd(StrToInt(Edit1.Text)); end; Kurt