File Coverage

blib/lib/HTTP/Session/ID/Urandom.pm
Criterion Covered Total %
statement 30 31 96.7
branch 1 2 50.0
condition 1 3 33.3
subroutine 9 9 100.0
pod 0 1 0.0
total 41 46 89.1


line stmt bran cond sub pod time code
1             package HTTP::Session::ID::Urandom;
2 19     19   235140 use strict;
  19         35  
  19         758  
3 19     19   141 use warnings;
  19         32  
  19         1246  
4 19     19   5193 use utf8;
  19         3556  
  19         118  
5 19     19   845 use 5.008_001;
  19         58  
6 19     19   110 use Carp ();
  19         28  
  19         254  
7 19     19   8206 use MIME::Base64 ();
  19         14225  
  19         562  
8 19     19   8929 use POSIX ();
  19         132299  
  19         581  
9 19     19   8173 use Crypt::URandom ();
  19         71907  
  19         3922  
10              
11             sub generate_id {
12 52     52 0 6944 my ($class, $sid_length) = @_;
13 52 50 33     418 if ( !defined($sid_length) || $sid_length !~ /\A[1-9][0-9]*\z/ ) {
14 0         0 Carp::croak "sid_length must be a positive integer";
15             }
16             # bytes of CSPRNG input needed to yield at least $sid_length base64url chars
17 52         266 my $src_len = POSIX::ceil($sid_length * 3.0 / 4.0);
18             # Generate session id from a cryptographically secure source.
19 52         176 my $buf = Crypt::URandom::urandom($src_len);
20 52         1764 my $result = MIME::Base64::encode_base64($buf, '');
21 52         164 $result =~ tr|+/=|\-_|d; # make it url safe
22 52         852 return substr($result, 0, $sid_length);
23             }
24              
25             1;