Астахов Константин: другие произведения.

Генератор паролей

Журнал "Самиздат": [Регистрация] [Найти] [Рейтинги] [Обсуждения] [Новинки] [Обзоры] [Помощь]
Оценка: 6.63*5  Ваша оценка:
  • Аннотация:
    Эти генераторы паролей могут быть интересными...

  Как известно, популярны пароли серии 1234, QWERTY, password, 1, admin etc... Их кому не лень ломают.
  Как бороться? Пишите сложные пароли в блокнот, носимый/хранимый в труднодоступных похищению местах, напр., дома, и не храните их в компе.
  А вот как их генерировать? Меня вдохновила статейка вот отсюда.
  
  Вот Вам текстик на Перле моего переложения:
  
  #!/usr/bin/perl -w
  # Perl version of mkpw_md5_alpha
  # Call this by /usr/bin/perl mkpw_md5_alpha.pl --length=integer<40 --count=integer
  
  
   use Getopt::Long;
   use Digest::MD5 qw(md5 md5_hex);
  
   my ($theDate, $adate, $bdate, $cdate, $xdate, $pdate, $sx, $pass);
  
   my $length = 8; # Default password length
   my $cnt = 1; # Default number of MD5 cycles
  
   GetOptions ("length=i" => \$length, # Password length
   "count=i" => \$cnt); # Number of hash feedback-cycles
  
   open(DATE, "date +%Y%m%d |"); $theDate = ; close(DATE);
   $adate = int($theDate); # Generate Year-Month-Day variable signature
  
   open(DATE, "date +%H%M%S |"); $theDate = ; close(DATE);
   $bdate = int($theDate); # Generate Hour-Min-Sec variable signature
  
   open(DATE, "date +%N |"); $theDate = ; close(DATE);
   $cdate = int($theDate); # Generate Nanoseconds variable signature
  
   $xdate = $adate ^ $bdate ^ $cdate; $pdate = pack("a", $xdate); # Combinate signatures by xor
  
   open(RNG, "head /dev/urandom |"); $sx=; close(RNG);
   $sx = $sx.$pdate; # Get random generator concatenated with signatures combination
  
   while ($cnt > 1) { # Process MD5 feedback cycles
  
   $cnt = $cnt - 1;
   $sx = md5($sx);
  
   }
  
   $sx = md5_hex($sx); # Last MD5 cycle
  
   # Get substring from base64 encoded random
   open(PWD, "echo $sx | uuencode -m -| sed -n 2p | cut -c3-43 |"); $sx=; close(PWD);
  
   $pass = substr($sx, 1, $length); # Limit password length and print it
   printf("%s\n", $pass);
  
  
  
  А вот вариации для bash, более простые (в аргументах - только длина):
  
  #!/bin/bash
  # Password generators
  
  # Simple alphabetic password making function
  function mkpw() { head /dev/urandom | uuencode -m - | sed -n 2p | cut -c1-${1:-8}; }
  
  function mkpw_md5() { # Hex password making function via MD5 hashing
  
   # random + Year + Month + Day + Hour + Minute + Second + Nanoseconds
   local s=$(head /dev/urandom)$(date +%Y%m%d%H%M%S%N)
   echo $s | md5sum | cut -c1-${1:-8};
  }
  
  function mkpw_md5_alpha() { # Alphabetic password making function via MD5 hashing
  
   # random + Year + Month + Day + Hour + Minute + Second + Nanoseconds
   local s=$(head /dev/urandom)$(date +%Y%m%d%H%M%S%N)
   echo $s | md5sum | uuencode -m -| sed -n 2p | cut -c3-43 | cut -c1-${1:-8};
  }
  
  function mkpw_sha1() { # Hex password making function via SHA1 hashing
  
   # random + Year + Month + Day + Hour + Minute + Second + Nanoseconds
   local s=$(head /dev/urandom)$(date +%Y%m%d%H%M%S%N)
   echo $s | sha1sum | cut -c1-${1:-8};
  }
  
  function mkpw_sha1_alpha() { # Alphabetic password making function via SHA1 hashing
  
   # random + Year + Month + Day + Hour + Minute + Second + Nanoseconds
   local s=$(head /dev/urandom)$(date +%Y%m%d%H%M%S%N)
   echo $s | sha1sum | uuencode -m -| sed -n 2p | cut -c3-43 | cut -c1-${1:-8};
  }
  
  А вот более стойкий вариант скрипта mkpw_hash_alpha. Убрана избыточность из сигнатуры даты/времени, hex-вывод MD5 заменен на бинарный, чтобы снизить избыточность в строке формата Base64. Остается всего 16 символов на 1 хэш, зато часто интересных... Подробности на страничке проекта.
  
  #!/usr/bin/perl -w
  # Perl version of password generator mkpw-hash-alpha
  # Call this by /usr/bin/perl mkpw-hash-alpha.pl [--hash=MD5/SHA1/SHA256/SHA512] [--length=integer<17] [--cycles=integer=1...3]
  # Designed under GPLv3 by Konstantin V.Astakhov at 2010-08-28
  # kv-astakhov@mail.ru
  
   use Getopt::Long;
   use Digest::MD5 qw(md5);
   use Digest::SHA qw(sha1 sha256 sha512);
   use POSIX qw(strftime);
   use MIME::Base64;
   use Switch;
  
   my $length = 6; # Default password length
   my $fbcycles = 1; # Default number of MD5 cycles
   my $help = ""; # Help flag
   my $htype = ""; # Hash type
  
   GetOptions ("hash=s" => \$htype, # Hash type
   "length=i" => \$length, # Password length
   "cycles=i" => \$fbcycles, # Number of hash feedback-cycles
   'help|?' => \$help); # Help output flag
  
   if ($help) { # Help output
  
   printf("\n%s\n%s\n\n", "Usage: perl mkpw-hash-alpha.pl [--hash=MD5/SHA1/SHA256/SHA512] [--length=integer] [--cycles=integer]",
  
   "Recommended arguments: length < 17, cycles = 1...5");
  
   }
   else { # Program operating with length/cycles arguments
  
   my $hcycles = 1 + int($length / 16); # Number of hash regeneration cycles
   my $pass = "";
   # Initial empty password
  
   while ($hcycles > 0) { # Process hash regeneration cycles
  
   my $sx = sysrandom().hdate(); # Get random generator concatenated with timestamp combination
  
   $hcycles = $hcycles - 1;
  
   while ($fbcycles > 1) { # Process hash feedback cycles
  
   $fbcycles = $fbcycles - 1;
  
   switch ($htype){ # Select hash of necessary type
  
   case("MD5") { $sx = md5($sx); }
   case("SHA1") { $sx = sha1($sx); }
   case("SHA256") { $sx = sha256($sx); }
   case("SHA512") { $sx = sha512($sx); }
  
   else { $sx = md5($sx); }
   }
  
   };
  
   switch ($htype){ # Select hash of necessary type
  
   case("MD5") { $sx = md5($sx); }
   case("SHA1") { $sx = sha1($sx); }
   case("SHA256") { $sx = sha256($sx); }
   case("SHA512") { $sx = sha512($sx); }
  
   else { $sx = md5($sx); }
   }
  
   $sx = substr(encode_base64($sx), 0, 16); # Cut control symbols in tail
  
   $pass =
  $pass.$sx; # Add MD5 hash to password
  
   };
  
   printf("%s\n", substr($pass, 0, $length)); # Limit password length and print password
  
   }
  
   sub sysrandom # Random generator based at /dev/urandom
   {
   open(RNG, "head /dev/urandom |"); my $x=; close(RNG);
  
   return $x;
   }
  
   sub hdate # Hash-like date timestamp
   {
   # YY-MM-DD date
   my $hyear = int(strftime "%y", localtime);
   my $hmonth = int(strftime "%m", localtime);
   my $hday = int(strftime "%d", localtime);
   my $ddate = 365 * $hyear + 30 * $hmonth + $hday; # Pseudo-day normalized date signature (not Gregorian-style)
  
   # HH:MM:SS date
   my $hhour = int(strftime "%H", localtime);
   my $hmin = int(strftime "%M", localtime);
   my $hsec = int(strftime "%S", localtime);
   my $tdate = 3600 * $hhour + 60 * $hmin + $hsec; # Second normalized time signature
  
   open(DATE, "date +%N |"); my $theDate = ; close(DATE);
   my $nsdate = int($theDate); # Nanosecond normalized time
  
   my $xdate = $ddate ^ $tdate ^ $nsdate; # Combinate signatures by xor
   my $pdate = pack("a", $xdate); # Pack signature to a string
  
   return $pdate;
   }
Оценка: 6.63*5  Ваша оценка:

Связаться с программистом сайта.

Новые книги авторов СИ, вышедшие из печати:
И.Арсенов "Сен.Следующий шаг" Е.Руденко "Незримого начала тень" В.Горъ "Проклятие короля" Е.Ковалевская "Клирик" В.Пекальчук "Долина смертных теней" С.Бадей "Верить предсказанному?" Я.Тройнич "Леди-жрица" И.Дравин "Чужак.Мэтр" А.Афанасьев "Подлецы и герои" К.Измайлова, А.Орлова "Пятый постулат" П.Миротворцев "Искусство Мертвых" В.Рощин "Команда ликвидаторов" Д.Север "Бордо,Рокфор и Шаризо" Ю.Погуляй "Братство Чародеев" Н.Щерба "Часодеи.Часовое сердце" О.Батлер "Моя маленькая Британия" А.Спесивцев "Атаман из будущего.Огнем и мечом" А.Михалев "Московская магия.Первая волна" В.Поляков "Мистик" К.Запорожан "Темный Город" Н.Бульба "И осталась только надежда" Р.Витич "Код Альфа" Н.Кузьмина "Попала!" Ш.Врочек "Рим.Кн.1.Последний легат" Д.Манасыпов "Район.Возвращение" С.Малицкий "Пагуба" А.Колентьев "Радиоактивный ветер" А.Нейтак "Контрмеры" Ю.Фирсанова "Час Д" Ю.Иванович "Нирвана" В.Кононюк "Шанс?Параллельный переход"

Как попасть в этoт список

Сайт - "Художники"
Доска об'явлений "Книги"