Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl -w
- use strict;
- use POSIX;
- # Generates a random passphrase from dictionary words.
- # Free to use without license or restrictions.
- sub usage
- {
- warn "Arguments: [--entropy n]\n";
- exit 1;
- }
- my $entropy = 80; # bits of entropy in generated password
- if (2 == @ARGV)
- {
- usage if ("--entropy" ne $ARGV[0] && $ARGV[1] !~ /^[0-9]+$/);
- my $e = $ARGV[1] * 1;
- if ($e < $entropy)
- {
- warn "Entropy must be a minimum of $entropy.\n";
- exit 1;
- }
- $entropy = $e;
- }
- elsif (0 != @ARGV)
- {
- usage;
- }
- my $MIN = 4;
- my $MAX = 8;
- my $MIN_DICT = 30000;
- my $wordsfile;
- open $wordsfile, '<', "/usr/share/dict/words" or
- open $wordsfile, '<', "/usr/dict/words" or
- die "Could not open words file.";
- my %words_hash = ();
- while (<$wordsfile>)
- {
- $_ =~ s/'.*//g;
- $_ =~ s/[^a-zA-Z]//g;
- $_ = lc $_;
- $words_hash{$_} = 1 if (length ($_) >= $MIN and length ($_) <= $MAX);
- }
- my @words = keys %words_hash;
- close $wordsfile or warn $!;
- die "Not enough words in dictionary." if (@words < $MIN_DICT);
- my $entropy_per_word = log (@words) / log (2);
- my $pw = "";
- my $pw_entropy = 0;
- open my $random_source, '<', "/dev/urandom"
- or die "Could not open /dev/urandom";
- binmode $random_source or die $!;
- my $random_buffer = "";
- my $random_bytes = ceil ($entropy_per_word / 8);
- die "Tried to read no random bytes." if ($random_bytes < 1);
- while ($pw_entropy < $entropy)
- {
- die "Could not read random bytes"
- if ($random_bytes !=
- read ($random_source, $random_buffer, $random_bytes));
- my @bytes = unpack 'C ' x $random_bytes, $random_buffer;
- my $n = 0;
- foreach (@bytes)
- {
- $n *= 256;
- $n += $_ * 1;
- }
- next if ($n >= @words); # don't use %, it will bias the randomness
- $pw .= ' ' if ("" ne $pw);
- foreach (split //, $words[$n])
- {
- $_ = uc if (rand > 0.8);
- $pw .= $_;
- }
- $pw_entropy += $entropy_per_word;
- }
- print $pw;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement