2004. szeptember 20., hétfő

Generate random password string


Problem/Question/Abstract:

How can I generate the random password in own program?

Answer:

Solve 1:

In last holidays I wrote a small dialog for random password generation. It's a simple but results is very useful:))

Try it:

function TfrmPWGenerate.btnGenerateClick(Sender: TObject): string;

{max length of generated password}
const
  intMAX_PW_LEN = 10;
var
  i: Byte;
  s: string;
begin
  {if you want to use the 'A..Z' characters}
  if cbAZ.Checked then
    s := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  else
    s := '';

  {if you want to use the 'a..z' characters}
  if cbAZSmall.Checked then
    s := s + 'abcdefghijklmnopqrstuvwxyz';

  {if you want to use the '0..9' characters}
  if cb09.Checked then
    s := s + '0123456789';
  if s = '' then
    exit;

  Result := '';
  for i := 0 to intMAX_PW_LEN - 1 do
    Result := Result + s[Random(Length(s) - 1) + 1];
end;

initialization
  Randomize;

The sample results:

IBbfA1mVK2
tmuXIuQJV5
oNEY1cF6xB
flIUhfdIui
mxaK71dJaq
B0YTqxdaLh
...

I think that it's no bad:)) Of course, you can add the some additional crypt methods and check of unique.


Solve 2:

function GenPassWord(): string;
var
  nCounter: integer;
  cString: string;
  cNumber: integer;
begin
  Randomize;
  cString := '';
  // nCounter = password length
  for nCounter := 0 to 8 do
  begin
    repeat
      cNumber := Random(122);
      // for capitol chrs extend the range
    until (nNumber >= 97) and (nNumber <= 122);
    cString := cString + Chr(nNumber);
  end;
  Result := cString;
end;

Nincsenek megjegyzések:

Megjegyzés küldése