DBI/Filter/SaltHash.pm

filter: Statementstmt 96.4% 27 / 28 Branchbran 83.3% 5 / 6 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod 100% 3 / 3 totaltotal 95.4% 42 / 44 CC 5 SCAR 6.5
CC
5
Cov
94%
decode
3.1
encode
2.0
generate_salt
2.0
CRAP 1.9
« DBI/Filter/utf8.pm ↑ Summary DBI/Filter/YAML.pm »
1 package Jifty::DBI::Filter::SaltHash;
2  
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use base qw|Jifty::DBI::Filter|;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Digest::MD5 qw(md5_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 Jifty::DBI::Filter::SaltHash - salts and hashes a value before storing it
12  
13 =head1 DESCRIPTION
14  
15 This filter will generate a random 4-byte salt, and then MD5 the given
16 value with the salt appended to the value. It will store the hash and
17 the salt in the database, and return a data structure that contains
18 both on decode. The salt and hash are stored in hexadecimal in the
19 database, so that you can put them in a text field.
20  
21 This filter is intended for storing passwords in a database.
22  
23 =head2 encode
24  
25 Generate a random 4-byte salt, MD5 the value with the salt (encoded to
26 hexadecimal) appended to it, and store both in the database.
27  
28 =cut
29  
30 sub encode {
31 2 ▶ my $self = shift;
Subroutine encode: called CC=2 SCAR=6.9
Pod documented
32 2 my $value_ref = $self->value_ref;
33  
34 2 ▶ return unless defined $$value_ref;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$value_ref 1 1 2
35  
36 1 my $salt = generate_salt();
37  
38 1 $$value_ref = md5_hex($$value_ref, $salt) . $salt;
39 }
40  
41 =head2 generate_salt
42  
43 Return a random 4-byte salt value, encoded as an 8-character hex
44 string.
45  
46 =cut
47  
48 sub generate_salt {
49 1 ▶ my $salt;
Subroutine generate_salt: called CC=2 SCAR=6.9
Pod documented
50 1 $salt .= unpack('H2',chr(int rand(255))) for(1..4);
51 1 return $salt;
52 }
53  
54 =head2 decode
55  
56 Return an arrayref of (hash, salt), both as hex strings.
57  
58 To test whether a provided value is the same one originally encoded,
59 use
60  
61 $hash eq md5_hex($value . $salt);
62  
63 =cut
64  
65 sub decode {
66 2 ▶ my $self = shift;
Subroutine decode: called CC=3 SCAR=11.2
Pod documented
67 2 my $value_ref = $self->value_ref;
68  
69 2 ▶ return unless $$value_ref;
Branch: 1 branch
BranchTrueFalseTotal
unless $$value_ref 1 1 2
70  
71 # This should never happen, but just to be safe
72 1 ▶ unless(length($$value_ref) == (8 + 32)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$value_ref == 40) { } 1 0 1
73 0 $$value_ref = [undef, undef];
74 } else {
75 1 $$value_ref = [unpack("A32A8", $$value_ref)];
76 }
77  
78 1 return 1;
79 }
80  
81  
82  
83 =head1 SEE ALSO
84  
85 L<Jifty::DBI::Filter>, L<Digest::MD5>
86  
87 =cut
88  
89 1 1;
« DBI/Filter/utf8.pm ↑ Summary DBI/Filter/YAML.pm »