Random Password Generator

KevinADC -1 Tallied Votes 462 Views Share

Code snippet to generate random passwords. Avoids using confusing characters such as lower case L (l) and the number one (1), the letter 'O' and the number zero. Upper-case alpha characters could be added to the character set if mixed-case passwords are desired.

my $password = rand_pass();

sub rand_pass {
   my @chars = ('a'..'k','m','n','p'..'z','2'..'9');
   my $length = 7;
   my $password = '';
   for (0..$length) {
      $password .= $chars[int rand @chars];
   }
   return $password;
}

Dani AI

Generated

Nice call by to drop visually ambiguous characters, and worth noting ’s one-liner idea — it demonstrates intent but yields very little entropy. Two practical issues with the original snippet: Perl’s built‑in rand() is not appropriate for generating secrets, and the for (0..$length) range is inclusive (so it produces one extra character). Below are safer patterns (cross‑platform caveats and reasoning included).

A simple, unbiased Perl approach that draws from the OS CSPRNG (works on Unix-like systems):

sub secure_rand_pass {
  my ($len) = @_;
  $len ||= 12;
  my $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
  open my $ur, '<', '/dev/urandom' or die "open: $!";
  binmode $ur;
  my $pass = '';
  my $n = length $alphabet;
  my $max = int(256 / $n) * $n - 1;
  while (length $pass < $len) {
    read $ur, my $byte, 1 or die "read: $!";
    my $v = ord($byte);
    next if $v > $max;             # avoid modulo bias
    $pass .= substr($alphabet, $v % $n, 1);
  }
  close $ur;
  return $pass;
}

Python (recommended when available) — uses the standard secrets module:

import secrets, string

def secure_password(length=12, avoid_ambiguous=True):
    alphabet = string.ascii_letters + string.digits + string.punctuation
    if avoid_ambiguous:
        for ch in 'l1Io0O':
            alphabet = alphabet.replace(ch, '')
    return ''.join(secrets.choice(alphabet) for _ in range(length))

Quick guidance: entropy (bits) = length * log2(alphabet_size). Example: the original 32‑character set at length 7 ≈ 35 bits (weak); a 10,000,000 integer gives only ≈ 23 bits. Aim for longer passwords or passphrases (12–16+ characters, or Diceware-style phrases) and avoid printing/storing generated secrets in logs. On Windows or restricted environments, use a vetted CPAN module or OS API that exposes a cryptographically secure RNG.

Prakash_8111 0 Newbie Poster

Thanks guys :
I thought one idea :
my $rand=int rand(100*100000);

How it would be ?????

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.