1#!./perl -w
2
3BEGIN {
4    chdir 't' if -d 't';
5    require "./test.pl";
6    set_up_inc( qw(. ../lib) );
7    use Config;
8}
9
10if ( !$Config{d_crypt} ) {
11    skip_all("crypt unimplemented");
12}
13else {
14    plan(tests => 6);
15}
16
17
18# Can't assume too much about the string returned by crypt(),
19# and about how many bytes of the encrypted (really, hashed)
20# string matter.
21#
22# HISTORICALLY the results started with the first two bytes of the salt,
23# followed by 11 bytes from the set [./0-9A-Za-z], and only the first
24# eight characters mattered, but those are probably no more safe
25# bets, given alternative encryption/hashing schemes like MD5,
26# C2 (or higher) security schemes, and non-UNIX platforms.
27#
28# On platforms implementing FIPS mode, using a weak algorithm (including
29# the default triple-DES algorithm) causes crypt(3) to return a null
30# pointer, which Perl converts into undef. We assume for now that all
31# such platforms support glibc-style selection of a different hashing
32# algorithm.
33# glibc supports MD5, but OpenBSD only supports Blowfish.
34my $alg = '';       # Use default algorithm
35if ( !defined(crypt("ab", $alg."cd")) ) {
36    $alg = '$5$';   # Try SHA-256
37}
38if ( !defined(crypt("ab", $alg."cd")) ) {
39    $alg = '$2b$12$FPWWO2RJ3CK4FINTw0Hi';  # Try Blowfish
40}
41if ( !defined(crypt("ab", $alg."cd")) ) {
42    $alg = ''; # Nothing worked.  Back to default
43}
44
45SKIP: {
46    skip ("VOS crypt ignores salt.", 1) if ($^O eq 'vos');
47    ok(substr(crypt("ab", $alg."cd"), length($alg)+2) ne 
48       substr(crypt("ab", $alg."ce"), length($alg)+2),
49       "salt makes a difference");
50}
51
52$a = "a\xFF\x{100}";
53
54eval {$b = crypt($a, $alg."cd")};
55like($@, qr/Wide character in crypt/, "wide characters ungood");
56
57chop $a; # throw away the wide character
58
59eval {$b = crypt($a, $alg."cd")};
60is($@, '',                   "downgrade to eight bit characters");
61is($b, crypt("a\xFF", $alg."cd"), "downgrade results agree");
62
63my $x = chr 256; # has to be lexical, and predeclared
64# Assignment gets optimised away here:
65$x = crypt "foo", ${\"bar"}; # ${\ } to defeat constant folding
66is $x, crypt("foo", "bar"), 'crypt writing to utf8 target';
67ok !utf8::is_utf8($x), 'crypt turns off utf8 on its target';
68