ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Net-FCP/FCP/Util.pm
Revision: 1.1
Committed: Fri May 14 16:12:26 2004 UTC (22 years, 4 months ago) by root
Branch: MAIN
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 Net::FCP::Util - utility functions.
4
5 =head1 SYNOPSIS
6
7 use Net::FCP::Util;
8
9
10 =head1 DESCRIPTION
11
12 =over 4
13
14 =cut
15
16 package Net::FCP::Util;
17
18 use Carp ();
19 use Digest::SHA1;
20 use MIME::Base64 ();
21
22 no warnings;
23
24 =item log2 $num[, $minlog]
25
26 Calculate the (integer) log2 of a number, rounded up. If C<$minlog> is
27 given it will be the minimum value returned.
28
29 =cut
30
31 sub log2($;$) { # n, minlog
32 $_[0] && length sprintf "%$_[1]b", $_[0] - 1;
33 }
34 # the above line is much faster than the equivalent
35 # below, which illustrates a fine point of perl...
36 # my ($n, $b) = @_;
37 # $b++ while 1 << $b < $n;
38 # $b;
39
40 =item encode_mpi $num
41
42 Encode the given number as a multiple-precision number (2 byte bitlength + bytes)
43
44 =cut
45
46 sub encode_mpi($) {
47 my $num = pack "N", $_[0];
48 my $len = log2 $_[0], 1;
49 $num =~ s/^\x00+//;
50 pack "n a*", $len, $num;
51 }
52
53 =item decode_base64 $string
54
55 Decode freenet's perverted version of base64.
56
57 =cut
58
59 sub decode_base64($) {
60 my $s = shift;
61
62 $s =~ y%~\-%+/%;
63 MIME::Base64::decode_base64 "$s======";
64 }
65
66 =item encode_base64 $data
67
68 Encode into freenet's perverted version of base64.
69
70 =cut
71
72 sub encode_base64($) {
73 my $s = MIME::Base64::encode_base64 shift, "";
74 $s =~ s/=+$//;
75 $s =~ y%+/%~\-%;
76 $s;
77 }
78
79 =item generate_chk_hash $metadata, $data
80
81 Generate and return they hash portion (the part after the comma, the
82 crypto key) that would be used in the CHK (as binary). This can be used to
83 verify contents of a CHK, since this key is a hash over the data.
84
85 (This function assumes a 128 bit key, which seems standard in freenet).
86
87 =cut
88
89 sub generate_chk_hash($$) {
90 my $d = new Digest::SHA1;
91
92 $d->add ($_[0]);
93 $d->add ($_[1]);
94 $d = $d->digest;
95
96 my $k = new Digest::SHA1;
97 $k->add ("\x00" x 1); # only one iteration
98 $k->add ($d);
99
100 substr $k->digest, 0, 16; # extract leading 128 bit
101 }
102
103 =item extract_chk_hash $uri
104
105 Extract the hash portion (the part after the comma, the crypto key) of a
106 CHK (in binary). Useful to compare against the output of generate_chk_key.
107
108 =cut
109
110 sub extract_chk_hash($) {
111 $_[0] =~ /CHK\@[a-zA-Z0-9~\-]{31},([a-zA-Z0-9~\-]{22})/
112 or Carp::croak "unable to parse CHK key from '$_[0]'";
113
114 decode_base64 $1;
115 }
116
117 =back
118
119 =head1 SEE ALSO
120
121 L<Net::FCP>.
122
123 =head1 BUGS
124
125 Not heavily tested.
126
127 =head1 AUTHOR
128
129 Marc Lehmann <pcg@goof.com>
130 http://www.goof.com/pcg/marc/
131
132 =cut
133
134 1;
135