#! /usr/bin/perl # hash-md5-salt -- generate salted hashes using crypt(3). # Check if plain text matches a given salted hash. # Copyright (C) 2015 Nick Urbanik # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. use strict; use warnings; use Getopt::Long; my %LEN = ( 1 => 8, 5 => 12, 6 => 16 ); sub usage { ( my $prog = $0 ) =~ s{.*/}{}; print < \&usage, debug => \my $debug, quiet => \my $quiet, ) or usage; sub random { my ( $upper ) = @_; eval { require Math::Random::Secure; }; if ( $@ ) { warn "Math::Random::Secure not installed: using plain rand\n" unless $quiet; return rand $upper; } return Math::Random::Secure::irand $upper; } sub gensalt { my ( $len ) = @_; $len ||= 8; return join q{}, map { $LEGAL[ random( scalar @LEGAL ) ] } 1 .. $len; } my $clear = shift or usage; my $salt = shift || '$1$'; # Deal specially with the case where SALT is of the form $1$, $5$ or $6$. if ( $salt =~ m{^\$([156])\$$} ) { my $len = $LEN{$1}; $salt .= gensalt( $len ) . q{$}; } print "SALT='$salt'\n" if $debug; $salt = "\$1\$$salt\$" unless $salt =~ m{^\$[156]\$[^\$]{2,}}; print "SALT2='$salt'\n" if $debug; my $hash = crypt $clear, $salt; print "$hash\n"; my $match; if ( length $hash eq length $salt ) { $match = $hash eq $salt ? 'MATCHES' : 'NO MATCH'; print "$match\n"; }