File Coverage

blib/lib/Crypt/SaltedHash.pm
Criterion Covered Total %
statement 87 92 94.5
branch 18 24 75.0
condition 13 15 86.6
subroutine 19 21 90.4
pod 8 8 100.0
total 145 160 90.6


line stmt bran cond sub pod time code
1             package Crypt::SaltedHash;
2            
3 3     3   512509 use v5.6.0;
  3         14  
4 3     3   18 use strict;
  3         11  
  3         107  
5            
6 3     3   1606 use Crypt::SysRandom ();
  3         10948  
  3         116  
7 3     3   1923 use Digest ();
  3         2369  
  3         115  
8 3     3   1478 use MIME::Base64 ();
  3         2534  
  3         95  
9 3     3   1605 use POSIX ();
  3         29255  
  3         5098  
10            
11             our $VERSION = '0.10';
12            
13             =encoding latin1
14            
15             =head1 NAME
16            
17             Crypt::SaltedHash - Perl interface to functions that assist in working
18             with salted hashes.
19            
20             =head1 SYNOPSIS
21            
22             use Crypt::SaltedHash;
23            
24             my $csh = Crypt::SaltedHash->new(algorithm => 'SHA-1');
25             $csh->add('secret');
26            
27             my $salted = $csh->generate;
28             my $valid = Crypt::SaltedHash->validate($salted, 'secret');
29            
30            
31             =head1 STATUS
32            
33             This module is deprecated.
34            
35             This module has not had significant updates since 2006.
36             There are newer modules that support more secure algorithms and hashing options,
37             and are extensible, such as L.
38            
39             =head1 DESCRIPTION
40            
41             The C module provides an object oriented interface to
42             create salted (or seeded) hashes of clear text data. The original
43             formalization of this concept comes from RFC-3112 and is extended by the use
44             of different digital algorithms.
45            
46             =head1 ABSTRACT
47            
48             =head2 Setting the data
49            
50             The process starts with 2 elements of data:
51            
52             =over
53            
54             =item *
55            
56             a clear text string (this could represent a password for instance).
57            
58             =item *
59            
60             the salt, a random seed of data. This is the value used to augment a hash in order to
61             ensure that 2 hashes of identical data yield different output.
62            
63             =back
64            
65             For the purposes of this abstract we will analyze the steps within code that perform the necessary actions
66             to achieve the endresult hashes. Cryptographers call this hash a digest. We will not however go into an explanation
67             of a one-way encryption scheme. Readers of this abstract are encouraged to get information on that subject by
68             their own.
69            
70             Theoretically, an implementation of a one-way function as an algorithm takes input, and provides output, that are both
71             in binary form; realistically though digests are typically encoded and stored in a database or in a flat text or XML file.
72             Take slappasswd5 for instance, it performs the exact functionality described above. We will use it as a black box compiled
73             piece of code for our analysis.
74            
75             In pseudocode we generate a salted hash as follows:
76            
77             Get the source string and salt as separate binary objects
78             Concatenate the 2 binary values
79             Hash the concatenation into SaltedPasswordHash
80             Base64Encode(concat(SaltedPasswordHash, Salt))
81            
82             We take a clear text string and hash this into a binary object representing the hashed value of the clear text string plus the random salt.
83             Then we have the Salt value, which are typically 4 bytes of purely random binary data represented as hexadecimal notation (Base16 as 8 bytes).
84            
85             Using SHA-1 as the hashing algorithm, SaltedPasswordHash is of length 20 (bytes) in raw binary form
86             (40 bytes if we look at it in hex). Salt is then 4 bytes in raw binary form. The SHA-1 algorithm generates
87             a 160 bit hash string. Consider that 8 bits = 1 byte. So 160 bits = 20 bytes, which is exactly what the
88             algorithm gives us.
89            
90             The Base64 encoding of the binary result looks like:
91            
92             {SSHA}B0O0XSYdsk7g9K229ZEr73Lid7HBD9DX
93            
94             Take note here that the final output is a 32-byte string of data. The Base64 encoding process uses bit shifting, masking, and padding as per RFC-3548.
95            
96             A couple of examples of salted hashes using on the same exact clear-text string:
97            
98             slappasswd -s testing123
99             {SSHA}72uhy5xc1AWOLwmNcXALHBSzp8xt4giL
100            
101             slappasswd -s testing123
102             {SSHA}zmIAVaKMmTngrUi4UlS0dzYwVAbfBTl7
103            
104             slappasswd -s testing123
105             {SSHA}Be3F12VVvBf9Sy6MSqpOgAdEj6JCZ+0f
106            
107             slappasswd -s testing123
108             {SSHA}ncHs4XYmQKJqL+VuyNQzQjwRXfvu6noa
109            
110             4 runs of slappasswd against the same clear text string each yielded unique endresult hashes.
111             The random salt is generated silently and never made visible.
112            
113             =head2 Extracting the data
114            
115             One of the keys to note is that the salt is dealt with twice in the process. It is used once for the actual application of randomness to the
116             given clear text string, and then it is stored within the final output as purely Base64 encoded data. In order to perform an authentication
117             query for instance, we must break apart the concatenation that was created for storage of the data. We accomplish this by splitting
118             up the binary data we get after Base64 decoding the stored hash.
119            
120             In pseudocode we would perform the extraction and verification operations as such:
121            
122             Strip the hash identifier from the Digest
123             Base64Decode(Digest, 20)
124             Split Digest into 2 byte arrays, one for bytes 0 � 20(pwhash), one for bytes 21 � 32 (salt)
125             Get the target string and salt as separate binary object
126             Concatenate the 2 binary values
127             SHA hash the concatenation into targetPasswordHash
128             Compare targetPasswordHash with pwhash
129             Return corresponding Boolean value
130            
131             Our job is to split the original digest up into 2 distinct byte arrays, one of the left 20 (0 - 20 including the null terminator) bytes and
132             the other for the rest of the data. The left 0 � 20 bytes will represent the salted binary value we will use for a byte-by-byte data
133             match against the new clear text presented for verification. The string presented for verification will have to be salted as well. The rest
134             of the bytes (21 � 32) represent the random salt which when decoded will show the exact hex characters that make up the once randomly
135             generated seed.
136            
137             We are now ready to verify some data. Let's start with the 4 hashes presented earlier. We will run them through our code to extract the
138             random salt and then using that verify the clear text string hashed by slappasswd. First, let's do a verification test with an erroneous
139             password; this should fail the matching test:
140            
141             {SSHA}72uhy5xc1AWOLwmNcXALHBSzp8xt4giL Test123
142             Hash extracted (in hex): ef6ba1cb9c5cd4058e2f098d71700b1c14b3a7cc
143             Salt extracted (in hex): 6de2088b
144             Hash length is: 20 Salt length is: 4
145             Hash presented in hex: 256bc48def0ce04b0af90dfd2808c42588bf9542
146             Hashes DON'T match: Test123
147            
148             The match failure test was successful as expected. Now let's use known valid data through the same exact code:
149            
150             {SSHA}72uhy5xc1AWOLwmNcXALHBSzp8xt4giL testing123
151             Hash extracted (in hex): ef6ba1cb9c5cd4058e2f098d71700b1c14b3a7cc
152             Salt extracted (in hex): 6de2088b
153             Hash length is: 20 Salt length is: 4
154             Hash presented in hex: ef6ba1cb9c5cd4058e2f098d71700b1c14b3a7cc
155             Hashes match: testing123
156            
157             The process used for salted passwords should now be clear. We see that salting hashed data does indeed add another layer of security to the
158             clear text one-way hashing process. But we also see that salted hashes should also be protected just as if the data was in clear text form.
159             Now that we have seen salted hashes actually work you should also realize that in code it is possible to extract salt values and use them
160             for various purposes. Obviously the usage can be on either side of the colored hat line, but the data is there.
161            
162             =head1 METHODS
163            
164             =over 4
165            
166             =item B
167            
168             Returns a new Crypt::SaltedHash object.
169             Possible keys for I<%options> are:
170            
171             =over
172            
173             =item *
174            
175             I: It's also possible to use common string representations of the
176             algorithm (e.g. "sha256", "SHA-384"). If the argument is missing, SHA-1 will
177             be used by default.
178            
179             =item *
180            
181             I: You can specify your on salt. You can either specify it as a sequence
182             of characters or as a hex encoded string of the form "HEX{...}". If the argument is missing,
183             a random seed is provided for you (recommended).
184            
185             =item *
186            
187             I: By default, the module assumes a salt length of 4 bytes (or 8, if it is encoded in hex).
188             If you choose a different length, you have to tell the I function how long your seed was.
189            
190             =back
191            
192             =cut
193            
194             sub new {
195 9     9 1 200635 my ( $class, %options ) = @_;
196            
197 9   100     34 $options{algorithm} ||= 'SHA-1';
198 9   100     39 $options{salt_len} ||= 4;
199 9   66     36 $options{salt} ||= &__generate_hex_salt( $options{salt_len} * 2 );
200            
201 9         27 $options{algorithm} = uc( $options{algorithm} );
202             $options{algorithm} .= '-1'
203 9 50       28 if $options{algorithm} =~ m!SHA$!; # SHA => SHA-1, HMAC-SHA => HMAC-SHA-1
204            
205 9         50 my $digest = Digest->new( $options{algorithm} );
206             my $self = {
207             salt => $options{salt},
208             algorithm => $options{algorithm},
209             digest => $digest,
210 9         4825 scheme => &__make_scheme( $options{algorithm} ),
211             };
212            
213 9         47 return bless $self, $class;
214             }
215            
216             =item B
217            
218             Logically joins the arguments into a single string, and uses it to
219             update the current digest state. For more details see L.
220            
221             =cut
222            
223             sub add {
224 10     10 1 23 my $self = shift;
225 10         20 $self->obj->add(@_);
226 10         16 return $self;
227             }
228            
229             =item B
230            
231             Resets the digest.
232            
233             =cut
234            
235             sub clear {
236 0     0 1 0 my $self = shift;
237 0         0 $self->{digest} = Digest->new( $self->{algorithm} );
238 0         0 return $self;
239             }
240            
241             =item B
242            
243             Returns the salt in binary form.
244            
245             =cut
246            
247             sub salt_bin {
248 10     10 1 11 my $self = shift;
249            
250 10 100       68 return $self->{salt} =~ m!^HEX\{(.*)\}$!i ? pack( "H*", $1 ) : $self->{salt};
251             }
252            
253             =item B
254            
255             Returns the salt in hexadecimal form ('HEX{...}')
256            
257             =cut
258            
259             sub salt_hex {
260 0     0 1 0 my $self = shift;
261            
262             return $self->{salt} =~ m!^HEX\{(.*)\}$!i
263             ? $self->{salt}
264 0 0       0 : 'HEX{' . join( '', unpack( 'H*', $self->{salt} ) ) . '}';
265             }
266            
267             =item B
268            
269             Generates the seeded hash. Uses the I-method of L before actually performing
270             the digest calculation, so adding more cleardata after a call of I to an instance of
271             I has the same effect as adding the data before the call of I.
272            
273             =cut
274            
275             sub generate {
276 10     10 1 20 my $self = shift;
277            
278 10         14 my $clone = $self->obj->clone;
279 10         23 my $salt = $self->salt_bin;
280            
281 10         33 $clone->add($salt);
282            
283 10         48 my $gen = &MIME::Base64::encode_base64( $clone->digest . $salt, '' );
284 10         16 my $scheme = $self->{scheme};
285            
286 10         45 return "{$scheme}$gen";
287             }
288            
289             =item B
290            
291             Validates a hasheddata previously generated against cleardata. I<$salt_len> defaults to 4 if not set.
292             Returns 1 if the validation is successful, 0 otherwise.
293            
294             =cut
295            
296             sub validate {
297 4     4 1 184494 my ( undef, $hasheddata, $cleardata, $salt_len ) = @_;
298            
299             # trim white-spaces
300 4         14 $hasheddata =~ s!^\s+!!;
301 4         11 $hasheddata =~ s!\s+$!!;
302            
303 4         9 my $scheme = &__get_pass_scheme($hasheddata);
304 4 100       22 $scheme = uc( $scheme ) if $scheme;
305 4         10 my $algorithm = &__make_algorithm($scheme);
306 4   100     11 my $hash = &__get_pass_hash($hasheddata) || '';
307 4         10 my $salt = &__extract_salt( $hash, $salt_len );
308            
309 4         12 my $obj = __PACKAGE__->new(
310             algorithm => $algorithm,
311             salt => $salt,
312             salt_len => $salt_len
313             );
314 4         19 $obj->add($cleardata);
315            
316 4         12 my $gen_hasheddata = $obj->generate;
317 4         12 my $gen_hash = &__get_pass_hash($gen_hasheddata);
318            
319 4         9 return _secure_compare( $gen_hash, $hash );
320             }
321            
322             =item B
323            
324             Returns a handle to L object.
325            
326             =cut
327            
328             sub obj {
329 20     20 1 89 return shift->{digest};
330             }
331            
332             =back
333            
334             =head1 FUNCTIONS
335            
336             I
337            
338             =cut
339            
340             sub __make_scheme {
341            
342 9     9   16 my $scheme = shift;
343            
344 9         24 my @parts = split /-/, $scheme;
345 9 100       22 pop @parts if $parts[-1] eq '1'; # SHA-1 => SHA
346            
347 9         21 $scheme = join '', @parts;
348            
349 9         36 return uc("S$scheme");
350             }
351            
352             sub __make_algorithm {
353 4     4   7 my ( $algorithm ) = @_;
354            
355 4   100     12 $algorithm ||= '';
356 4         7 local $1;
357            
358 4 100       18 if ( $algorithm =~ m!^S(.*)$! ) {
359 3         5 $algorithm = $1;
360            
361             # print STDERR "algorithm: $algorithm\n";
362 3 50       15 if ( $algorithm =~ m!([a-zA-Z]+)([0-9]+)! ) {
363            
364 3         7 my $name = uc($1);
365 3         7 my $digits = $2;
366            
367             # print STDERR "name: $name\n";
368             # print STDERR "digits: $digits\n";
369            
370 3 50       6 $name = "HMAC-$2" if $name =~ m!^HMAC(.*)$!; # HMAC-SHA-1
371 3 50       10 $digits = "-$digits" unless $name =~ m!MD$!; # MD2, MD4, MD5
372            
373 3         8 $algorithm = "$name$digits";
374             }
375            
376             }
377            
378 4         8 return $algorithm;
379             }
380            
381             sub __get_pass_scheme {
382 4     4   9 local $1;
383 4 100       17 return unless $_[0] =~ m/{([^}]*)/;
384 3         8 return $1;
385             }
386            
387             sub __get_pass_hash {
388 8     8   17 local $1;
389 8 100       37 return unless $_[0] =~ m/}(.*)/;
390 7         27 return $1;
391             }
392            
393             sub __generate_hex_salt {
394            
395 4   50 4   20 my $length = shift || 8;
396            
397 4         63 my $salt = substr( unpack( "h*", Crypt::SysRandom::random_bytes( POSIX::ceil( $length / 2 ) ) ), 0, $length );
398            
399 4         20 return "HEX{$salt}";
400             }
401            
402             sub __extract_salt {
403            
404 4     4   9 my ( $hash, $salt_len ) = @_;
405            
406 4         15 my $binhash = &MIME::Base64::decode_base64($hash);
407 4   100     17 my $binsalt = substr( $binhash, length($binhash) - ( $salt_len || 4 ) );
408            
409 4         6 return $binsalt;
410             }
411            
412             sub _secure_compare {
413 4     4   8 my ($left, $right) = @_;
414 4         9 my $res = length $left != length $right;
415 4 100       8 $right = $left if $res;
416 4         93 $res |= ord(substr $left, $_, 1) ^ ord(substr $right, $_, 1) for 0 .. length($left) - 1;
417 4         36 return $res == 0;
418             }
419            
420             =head1 SEE ALSO
421            
422             L, L
423            
424             =head1 AUTHOR
425            
426             Sascha Kiefer,
427            
428             The current maintainer is Robert Rothenberg
429            
430             =head1 ACKNOWLEDGMENTS
431            
432             The author is particularly grateful to Andres Andreu for his article: Salted
433             hashes demystified - A Primer (L)
434            
435             =head1 COPYRIGHT AND LICENSE
436            
437             Copyright (C) 2005-2006, 2010, 2013, 2026 Sascha Kiefer
438            
439             This library is free software; you can redistribute it and/or modify
440             it under the same terms as Perl itself.
441            
442             =cut
443            
444             1;