New build path variable
[freeradius.git] / scripts / cryptpasswd.in
1 #!@PERL@
2 #
3 # cryptpasswd   Generate or check md5 and DES hashed passwords.
4 #
5 #    This program is free software; you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License as published by
7 #    the Free Software Foundation; either version 2 of the License, or
8 #    (at your option) any later version.
9 #
10 #    This program is distributed in the hope that it will be useful,
11 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #    GNU General Public License for more details.
14 #
15 #    You should have received a copy of the GNU General Public License
16 #    along with this program; if not, write to the Free Software
17 #    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18 #
19 #    Copyright (C) 2001 The FreeRADIUS Project   http://www.freeradius.org
20 #
21 #    Written by Miquel van Smoorenburg <miquels@cistron-office.nl>
22 #
23 #    $Id$
24 #
25
26 use Getopt::Long;
27
28 sub check_des {
29         return (crypt("fnord", "aa") =~ m/^aa/);
30 }
31
32 sub check_md5 {
33         return (crypt("fnord", "\$1\$aa") =~ m/^\$1\$/);
34 }
35
36 sub usage {
37         $name = $0;
38         $name =~ s,.*/,,;
39
40         die "Usage: $name [--des|--md5|--check] plaintext_password [crypted_password]\n";
41 }
42
43 @saltc = ( '.', '/', '0'..'9', 'A'..'Z', 'a'..'z' );
44
45 #
46 #       MAIN
47 #
48 sub main {
49
50         Getopt::Long::Configure("no_ignore_case", "bundling");
51         my @options = ( "des|d+", "md5|m+", "check|c+" );
52         usage() unless (eval { Getopt::Long::GetOptions(@options) } );
53
54         if ($opt_check) {
55                 usage unless ($#ARGV == 1);
56                 if (crypt($ARGV[0], $ARGV[1]) ne $ARGV[1]) {
57                         print "Password BAD\n";
58                         return 0;
59                 } else {
60                         print "Password OK\n";
61                         return 1;
62                 }
63         }
64
65         $opt_des = 1 unless ($opt_des || $opt_md5);
66         usage() unless ($#ARGV == 0);
67
68         die "DES password hashing not available\n"
69                 if ($opt_des && !check_des());
70         die "MD5 password hashing not available\n"
71                 if ($opt_md5 && !check_md5());
72
73         $salt = ($opt_md5 ? '$1$' : '');
74         for ($i = 0; $i < ($opt_md5 ? 8 : 2); $i++) {
75                 $salt .= $saltc[rand 64];
76         }
77         $salt .= '$' if ($opt_md5);
78         print crypt($ARGV[0], $salt), "\n";
79
80         1;
81 }
82
83 exit !main();