1# -----------------------------------------------------------------------------
2# $Id: Crypt.pm 11365 2008-05-10 14:58:28Z topia $
3# -----------------------------------------------------------------------------
4# 与えられた、またはランダムに決定されたsaltを用いて文字列をcryptする機能、
5# そして文字列をcryptして得られた文字列を、予めcryptされた文字列と
6# 比較する機能を持つ。
7# -----------------------------------------------------------------------------
8package Crypt;
9use strict;
10use warnings;
11
12#use SelfLoader;
13#1;
14#__DATA__
15
16sub encrypt {
17    # saltは省略可能。省略されるとランダムに作られる。
18    my ($str,$salt) = @_;
19    $salt = gen_salt() unless defined $salt;
20
21    return crypt($str,$salt);
22}
23
24sub check {
25    # encryptedのsaltでrawをcrypt()してみて、一致したかどうかを真偽値で返す。
26    my ($raw,$encrypted) = @_;
27
28    return crypt($raw,$encrypted) eq $encrypted;
29}
30
31sub gen_salt {
32    my $salt = '';
33
34    srand;
35    for (0 .. 1) {
36	my $n = int(rand(63));
37	if ($n < 12) {
38	    $salt .= chr($n + 46); # ./0-9
39	}
40	elsif ($n < 38) {
41	    $salt .= chr($n + 65 - 12); # A-Z
42	}
43	elsif ($n < 64) {
44	    $salt .= chr($n + 97 - 38); # a-z
45	}
46    }
47    $salt;
48}
49
501
51