blib/lib/Crypt/ASN1.pm

filter: Statementstmt 96.4% 242 / 251 Branchbran 75.4% 160 / 212 Conditioncond 75.7% 53 / 70 MC/DCmcdc 54.7% 23 / 42 Subroutinesub 100% 27 / 27 Podpod 100% 8 / 8 totaltotal 84.1% 513 / 610 CC 133 SCAR 29.8
CC
133
Cov
85%
_normalize_node
36.8
_dump_value
28.0
_normalize_time
24.8
CRAP 19.6
« blib/lib/Crypt/PK/DSA.pm ↑ Summary blib/lib/Math/BigInt/LTM.pm »
1 package Crypt::ASN1;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 our $VERSION = '0.091';
6  
7 2 require Exporter; our @ISA = qw(Exporter); ### use Exporter 5.57 'import';
8 2 our %EXPORT_TAGS = ( all => [qw(
9 asn1_decode_der asn1_decode_pem asn1_decode_der_file asn1_decode_pem_file
10 asn1_encode_der asn1_encode_pem asn1_encode_der_file asn1_encode_pem_file
11 asn1_to_string
12 )] );
13 2 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
14 2 our @EXPORT = qw();
15  
16 2 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use CryptX;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use Crypt::Misc qw(pem_to_der der_to_pem read_rawfile write_rawfile decode_b64);
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 # --- decode (public) ---
22  
23 4 ▶sub asn1_decode_pem {
Subroutine asn1_decode_pem: called CC=2 SCAR=7.1
Pod documented
24 4 my $pem = shift;
25 4 ▶ my $der = pem_to_der($pem) or croak "FATAL: asn1_decode_pem: failed to decode PEM data";
Branch: 1 branch
BranchTrueFalseTotal
my $der = pem_to_der($pem) or croak("FATAL: asn1_decode_pem: failed to decode PEM data") 4 0 4
26 4 return asn1_decode_der($der, @_);
27 }
28  
29 2 ▶sub asn1_decode_der_file {
Subroutine asn1_decode_der_file: called CC=1 SCAR=0.0
Pod documented
30 2 my $file = shift;
31 2 return asn1_decode_der(read_rawfile($file), @_);
32 }
33  
34 2 ▶sub asn1_decode_pem_file {
Subroutine asn1_decode_pem_file: called CC=1 SCAR=0.0
Pod documented
35 2 my $file = shift;
36 2 return asn1_decode_pem(read_rawfile($file), @_);
37 }
38  
39 # --- encode (public) ---
40  
41 69 ▶sub asn1_encode_der {
Subroutine asn1_encode_der: called CC=2 SCAR=7.0
Pod documented
42 69 my ($tree) = @_;
43 69 ▶ croak "FATAL: asn1_encode_der: argument must be an arrayref" unless ref $tree eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tree eq "ARRAY" 0 69 69
44 69 my $normalized = [ map { _normalize_node($_) } @$tree ];
45 42 return _asn1_encode_der($normalized);
46 }
47  
48 2 ▶sub asn1_encode_pem {
Subroutine asn1_encode_pem: called CC=2 SCAR=7.0
Pod documented
49 2 my ($tree, $header) = @_;
50 2 ▶ $header = 'DATA' unless defined $header;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header 0 2 2
51 2 my $der = asn1_encode_der($tree);
52 2 return der_to_pem($der, $header);
53 }
54  
55 1 ▶sub asn1_encode_der_file {
Subroutine asn1_encode_der_file: called CC=1 SCAR=0.0
Pod documented
56 1 my ($tree, $file) = @_;
57 1 my $der = asn1_encode_der($tree);
58 1 write_rawfile($file, $der);
59 1 return $der;
60 }
61  
62 1 ▶sub asn1_encode_pem_file {
Subroutine asn1_encode_pem_file: called CC=1 SCAR=0.0
Pod documented
63 1 my ($tree, $header, $file) = @_;
64 1 my $pem = asn1_encode_pem($tree, $header);
65 1 write_rawfile($file, $pem);
66 1 return $pem;
67 }
68  
69 # --- dump (public) ---
70  
71 4 ▶sub asn1_to_string {
Subroutine asn1_to_string: called CC=2 SCAR=7.0
Pod documented
72 4 my ($tree) = @_;
73 4 ▶ croak "FATAL: asn1_to_string: argument must be an arrayref" unless ref $tree eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tree eq "ARRAY" 0 4 4
74 4 my $out = '';
75 4 _dump_nodes(\$out, $tree, 0);
76 4 return $out;
77 }
78  
79 2 my %_LABEL = (
80 BOOLEAN => 'BOOLEAN', INTEGER => 'INTEGER', BIT_STRING => 'BIT STRING',
81 OCTET_STRING => 'OCTET STRING', NULL => 'NULL', OID => 'OBJECT',
82 UTF8_STRING => 'UTF8STRING', PRINTABLE_STRING => 'PRINTABLESTRING',
83 TELETEX_STRING => 'TELETEXSTRING', IA5_STRING => 'IA5STRING',
84 UTCTIME => 'UTCTIME', GENERALIZEDTIME => 'GENERALIZEDTIME',
85 SEQUENCE => 'SEQUENCE', SET => 'SET',
86 );
87  
88 25 ▶sub _dump_nodes {
Subroutine _dump_nodes: called CC=2 SCAR=6.9
89 25 my ($out, $nodes, $depth) = @_;
90 25 for my $node (@$nodes) {
91 58 _dump_node($out, $node, $depth);
92 }
93 }
94  
95 58 ▶sub _dump_node {
Subroutine _dump_node: called CC=13 SCAR=27.2
96 58 my ($out, $node, $depth) = @_;
97 58 ▶ my $type = defined $node->{type} ? $node->{type} : '?';
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'type'} ? : 58 0 58
98 58 my $val = $node->{value};
99 58 ▶ my $fmt = defined $node->{format} ? $node->{format} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'format'} ? : 58 0 58
100 58 my $indent = ' ' x $depth;
101  
102 58 ▶ if ($type eq 'SEQUENCE' || $type eq 'SET') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "SEQUENCE" or $type eq "SET") 18 40 58
Condition100%3/3
$type eq "SEQUENCE" or $type eq "SET"
l!l&&r!l&&!r
16240
MC/DC100%2/2
$type eq "SEQUENCE" or $type eq "SET"
$type eq "SEQUENCE" $type eq "SET"
Truth table100%3/3
A or B
A= $type eq "SEQUENCE"B= $type eq "SET"
ABresult
1X1
011
000
103 18 ▶ my $n = ref $val eq 'ARRAY' ? scalar @$val : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'ARRAY' ? : 18 0 18
104 18 $$out .= "${indent}$_LABEL{$type} ($n elem)\n";
105 18 ▶ _dump_nodes($out, $val, $depth + 1) if $n;
Branch: 1 branch
BranchTrueFalseTotal
if $n 18 0 18
106 18 return;
107 }
108  
109 40 ▶ if ($type eq 'CUSTOM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "CUSTOM") 3 37 40
110 3 ▶ my $cls = defined $node->{class} ? $node->{class} : 'CONTEXT_SPECIFIC';
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'class'} ? : 3 0 3
111 3 ▶ my $tag = defined $node->{tag} ? $node->{tag} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'tag'} ? : 3 0 3
112 3 my $cons = $node->{constructed};
113 3 my $label = lc($cls) . " [$tag]";
114 3 ▶ if ($cons && ref $val eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cons and ref $val eq 'ARRAY') { } 3 0 3
Condition33%1/3
$cons and ref $val eq "ARRAY"
!ll&&!rl&&r
003
MC/DC0%0/2
$cons and ref $val eq "ARRAY"
$cons ref $val eq "ARRAY"
Truth table33%1/3
A and B
A= $consB= ref $val eq "ARRAY"
ABresult
0X0
100
111
115 3 my $n = scalar @$val;
116 3 $$out .= "${indent}$label cons ($n elem)\n";
117 3 _dump_nodes($out, $val, $depth + 1);
118 } else {
119 0 $$out .= "${indent}$label prim:${\ _dump_value_short($val, $fmt)}\n";
120 }
121 3 return;
122 }
123  
124 37 ▶ my $label = exists $_LABEL{$type} ? $_LABEL{$type} : $type;
Branch: 1 branch
BranchTrueFalseTotal
exists $_LABEL{$type} ? : 37 0 37
125 37 $$out .= "${indent}${label}:${\ _dump_value($type, $val, $fmt, $node)}\n";
126 }
127  
128 37 ▶sub _dump_value {
Subroutine _dump_value: called CC=25 SCAR=33.3
129 37 my ($type, $val, $fmt, $node) = @_;
130  
131 37 ▶ return '' if $type eq 'NULL';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "NULL" 4 33 37
132  
133 33 ▶ if ($type eq 'BOOLEAN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "BOOLEAN") 2 31 33
134 2 ▶ return $val ? 'TRUE' : 'FALSE';
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 1 1 2
135 }
136 31 ▶ if ($type eq 'INTEGER') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "INTEGER") 4 27 31
137 4 ▶ return _dump_value_short($val, $fmt) if $fmt eq 'bytes';
Branch: 1 branch
BranchTrueFalseTotal
if $fmt eq "bytes" 0 4 4
138 4 ▶ my $s = defined $val ? "$val" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 4 0 4
139 4 ▶ return length($s) > 64 ? substr($s, 0, 61) . '...' : $s;
Branch: 1 branch
BranchTrueFalseTotal
length $s > 64 ? : 0 4 4
140 }
141 27 ▶ if ($type eq 'OID') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "OID") 10 17 27
142 10 ▶ my $s = defined $val ? $val : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 10 0 10
143 10 ▶ $s .= " ($node->{name})" if defined $node->{name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $node->{"name"} 1 9 10
144 10 return $s;
145 }
146 17 ▶ if ($type eq 'UTF8_STRING' || $type eq 'PRINTABLE_STRING'
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "UTF8_STRING" or $type eq "PRINTABLE_STRING" or $type eq "IA5_STRING" or $type eq "TELETEX_STRING") 6 11 17
Condition100%9/9
$type eq "UTF8_STRING" or $type eq "PRINTABLE_STRING" or $type eq "IA5_STRING" or $type eq "TELETEX_STRING"
l!l&&r!l&&!r
5111
$type eq "UTF8_STRING" or $type eq "PRINTABLE_STRING" or $type eq "IA5_STRING"
l!l&&r!l&&!r
4112
$type eq "UTF8_STRING" or $type eq "PRINTABLE_STRING"
l!l&&r!l&&!r
3113
MC/DC100%4/4
$type eq "UTF8_STRING" or $type eq "PRINTABLE_STRING" or $type eq "IA5_STRING" or $type eq "TELETEX_STRING"
$type eq "UTF8_STRING" $type eq "PRINTABLE_STRING" $type eq "IA5_STRING" $type eq "TELETEX_STRING"
Truth table100%5/5
A or B or C or D
A= $type eq "UTF8_STRING"B= $type eq "PRINTABLE_STRING"C= $type eq "IA5_STRING"D= $type eq "TELETEX_STRING"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
147 || $type eq 'IA5_STRING' || $type eq 'TELETEX_STRING') {
148 6 ▶ my $s = defined $val ? $val : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 6 0 6
149 6 ▶ return length($s) > 64 ? substr($s, 0, 61) . '...' : $s;
Branch: 1 branch
BranchTrueFalseTotal
length $s > 64 ? : 0 6 6
150 }
151 11 ▶ if ($type eq 'UTCTIME' || $type eq 'GENERALIZEDTIME') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "UTCTIME" or $type eq "GENERALIZEDTIME") 4 7 11
Condition100%3/3
$type eq "UTCTIME" or $type eq "GENERALIZEDTIME"
l!l&&r!l&&!r
317
MC/DC100%2/2
$type eq "UTCTIME" or $type eq "GENERALIZEDTIME"
$type eq "UTCTIME" $type eq "GENERALIZEDTIME"
Truth table100%3/3
A or B
A= $type eq "UTCTIME"B= $type eq "GENERALIZEDTIME"
ABresult
1X1
011
000
152 4 ▶ return defined $val ? "$val" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 4 0 4
153 }
154 7 ▶ if ($type eq 'OCTET_STRING' || $type eq 'BIT_STRING') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "OCTET_STRING" or $type eq "BIT_STRING") 7 0 7
Condition66%2/3
$type eq "OCTET_STRING" or $type eq "BIT_STRING"
l!l&&r!l&&!r
430
MC/DC0%0/2
$type eq "OCTET_STRING" or $type eq "BIT_STRING"
$type eq "OCTET_STRING" $type eq "BIT_STRING"
Truth table66%2/3
A or B
A= $type eq "OCTET_STRING"B= $type eq "BIT_STRING"
ABresult
1X1
011
000
155 7 my $extra = '';
156 7 ▶ if ($type eq 'BIT_STRING' && defined $node->{bits}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "BIT_STRING" and defined $node->{"bits"}) 3 4 7
Condition66%2/3
$type eq "BIT_STRING" and defined $node->{"bits"}
!ll&&!rl&&r
403
MC/DC50%1/2
$type eq "BIT_STRING" and defined $node->{"bits"}
$type eq "BIT_STRING" defined $node->{"bits"}
Truth table66%2/3
A and B
A= $type eq "BIT_STRING"B= defined $node->{"bits"}
ABresult
0X0
100
111
157 3 $extra = " ($node->{bits} bit)";
158 }
159 7 return _dump_value_short($val, $fmt) . $extra;
160 }
161 0 ▶ return defined $val ? "$val" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 0 0 0
162 }
163  
164 7 ▶sub _dump_value_short {
Subroutine _dump_value_short: called CC=6 SCAR=19.0
165 7 my ($val, $fmt) = @_;
166 7 ▶ return '' unless defined $val && length $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and length $val 0 7 7
Condition33%1/3
defined $val and length $val
!ll&&!rl&&r
007
MC/DC0%0/2
defined $val and length $val
defined $val length $val
Truth table33%1/3
A and B
A= defined $valB= length $val
ABresult
0X0
100
111
167 7 my $hex;
168 7 ▶ if ($fmt eq 'hex') {
Branch: 2 branches
BranchTrueFalseTotal
if ($fmt eq 'hex') { } 0 7 7
elsif ($fmt eq 'base64') { } 5 2 7
169 0 $hex = lc($val);
170 } elsif ($fmt eq 'base64') {
171 5 $hex = lc unpack("H*", decode_b64($val));
172 } else {
173 2 $hex = lc unpack("H*", $val);
174 }
175 7 ▶ return length($hex) > 64 ? substr($hex, 0, 61) . '...' : $hex;
Branch: 1 branch
BranchTrueFalseTotal
length $hex > 64 ? : 2 5 7
176 }
177  
178 # --- normalization (internal) ---
179  
180 2 my %_CLASS_MAP = (UNIVERSAL => 0, APPLICATION => 1, CONTEXT_SPECIFIC => 2, PRIVATE => 3);
181 2 my $_MAX_ULONG_DEC = _max_ulong_dec();
182 2 my $_MAX_OID_SECOND_ARC_DEC = _max_oid_second_arc_dec();
183  
184 221 ▶sub _normalize_node {
Subroutine _normalize_node: called CC=36 SCAR=36.0
185 221 my ($node) = @_;
186 221 ▶ croak "FATAL: asn1_encode: node must be a hashref" unless ref $node eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $node eq "HASH" 0 221 221
187 221 ▶ my $type = defined $node->{type} ? $node->{type} : croak "FATAL: asn1_encode: node missing 'type'";
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'type'} ? : 221 0 221
188 221 ▶ my $fmt = defined $node->{format} ? $node->{format} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'format'} ? : 166 55 221
189 221 my $val = $node->{value};
190  
191 # --- constructed types ---
192 221 ▶ if ($type eq 'SEQUENCE' || $type eq 'SET') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "SEQUENCE" or $type eq "SET") 63 158 221
Condition100%3/3
$type eq "SEQUENCE" or $type eq "SET"
l!l&&r!l&&!r
558158
MC/DC100%2/2
$type eq "SEQUENCE" or $type eq "SET"
$type eq "SEQUENCE" $type eq "SET"
Truth table100%3/3
A or B
A= $type eq "SEQUENCE"B= $type eq "SET"
ABresult
1X1
011
000
193 63 ▶ croak "FATAL: asn1_encode: $type value must be arrayref" unless ref($val) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" 0 63 63
194 63 return { type => $type, value => [ map { _normalize_node($_) } @$val ] };
195 }
196 # --- INTEGER: always normalize to decimal string ---
197 158 ▶ if ($type eq 'INTEGER') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "INTEGER") 25 133 158
198 25 ▶ croak "FATAL: asn1_encode: INTEGER missing value" unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 25 25
199 25 ▶ if ($fmt eq 'hex') {
Branch: 2 branches
BranchTrueFalseTotal
if ($fmt eq 'hex') { } 5 20 25
elsif ($fmt eq 'bytes') { } 3 17 20
200 5 require Math::BigInt;
201 5 my $hex = $val;
202 5 my $neg = ($hex =~ s/^-//);
203 5 my $bi = Math::BigInt->new("0x$hex");
204 5 ▶ $bi->bneg() if $neg;
Branch: 1 branch
BranchTrueFalseTotal
if $neg 2 3 5
205 5 $val = $bi->bstr();
206 }
207 elsif ($fmt eq 'bytes') {
208 3 require Math::BigInt;
209 3 $val = Math::BigInt->new("0x" . unpack("H*", $val))->bstr();
210 }
211 else {
212 17 $val = "$val"; # stringify Perl number
213 }
214 25 return { type => 'INTEGER', value => $val };
215 }
216 # --- BOOLEAN ---
217 133 ▶ if ($type eq 'BOOLEAN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "BOOLEAN") 4 129 133
218 4 ▶ return { type => 'BOOLEAN', value => $val ? 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 2 2 4
219 }
220 # --- NULL ---
221 129 ▶ if ($type eq 'NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "NULL") 11 118 129
222 11 return { type => 'NULL' };
223 }
224 # --- OID ---
225 118 ▶ if ($type eq 'OID') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "OID") 32 86 118
226 32 ▶ croak "FATAL: asn1_encode: OID missing value" unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 32 32
227 32 return { type => 'OID', value => _normalize_oid($val) };
228 }
229 # --- OCTET_STRING: always normalize to raw bytes ---
230 86 ▶ if ($type eq 'OCTET_STRING') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "OCTET_STRING") 21 65 86
231 21 $val = _bin_to_raw($val, $fmt);
232 17 return { type => 'OCTET_STRING', value => $val };
233 }
234 # --- BIT_STRING: raw bytes + bits ---
235 65 ▶ if ($type eq 'BIT_STRING') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "BIT_STRING") 14 51 65
236 14 $val = _bin_to_raw($val, $fmt);
237 my $bits = exists $node->{bits}
238 14 ▶ ? _normalize_bit_count($node->{bits}, length($val))
Branch: 1 branch
BranchTrueFalseTotal
exists $node->{'bits'} ? : 13 1 14
239 : (length($val) * 8);
240 11 return { type => 'BIT_STRING', value => $val, bits => $bits };
241 }
242 # --- string types ---
243 51 ▶ if ($type eq 'UTF8_STRING') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "UTF8_STRING") 8 43 51
244 8 ▶ return { type => 'UTF8_STRING', value => defined $val ? $val : '' };
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 8 0 8
245 }
246 43 ▶ if ($type eq 'IA5_STRING' || $type eq 'PRINTABLE_STRING' || $type eq 'TELETEX_STRING') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "IA5_STRING" or $type eq "PRINTABLE_STRING" or $type eq "TELETEX_STRING") 5 38 43
Condition100%6/6
$type eq "IA5_STRING" or $type eq "PRINTABLE_STRING" or $type eq "TELETEX_STRING"
l!l&&r!l&&!r
4138
$type eq "IA5_STRING" or $type eq "PRINTABLE_STRING"
l!l&&r!l&&!r
2239
MC/DC100%3/3
$type eq "IA5_STRING" or $type eq "PRINTABLE_STRING" or $type eq "TELETEX_STRING"
$type eq "IA5_STRING" $type eq "PRINTABLE_STRING" $type eq "TELETEX_STRING"
Truth table100%4/4
A or B or C
A= $type eq "IA5_STRING"B= $type eq "PRINTABLE_STRING"C= $type eq "TELETEX_STRING"
ABCresult
1XX1
01X1
0011
0000
247 5 ▶ return { type => $type, value => defined $val ? $val : '' };
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 5 0 5
248 }
249 # --- time types ---
250 38 ▶ if ($type eq 'UTCTIME') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "UTCTIME") 16 22 38
251 16 return { type => 'UTCTIME', value => _normalize_time($val, $fmt, 'utc') };
252 }
253 22 ▶ if ($type eq 'GENERALIZEDTIME') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "GENERALIZEDTIME") 3 19 22
254 3 return { type => 'GENERALIZEDTIME', value => _normalize_time($val, $fmt, 'gen') };
255 }
256 # --- CUSTOM ---
257 19 ▶ if ($type eq 'CUSTOM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "CUSTOM") 19 0 19
258 19 ▶ my $class_name = defined $node->{class} ? $node->{class} : 'CONTEXT_SPECIFIC';
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'class'} ? : 19 0 19
259 croak "FATAL: asn1_encode: invalid CUSTOM class '$class_name'"
260 19 ▶ unless exists $_CLASS_MAP{$class_name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $_CLASS_MAP{$class_name} 2 17 19
261 17 my $cls = $_CLASS_MAP{$class_name};
262 17 ▶ my $constr = $node->{constructed} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$node->{'constructed'} ? : 11 6 17
263 17 ▶ my $tag = _normalize_custom_tag(defined $node->{tag} ? $node->{tag} : 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $node->{'tag'} ? : 17 0 17
264 13 my %n = (type => 'CUSTOM', class => $cls, constructed => $constr, tag => $tag);
265 13 ▶ if ($constr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($constr) { } 11 2 13
266 11 ▶ croak "FATAL: asn1_encode: CUSTOM constructed value must be arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $val eq "ARRAY" 1 10 11
267 unless ref($val) eq 'ARRAY';
268 10 $n{value} = [ map { _normalize_node($_) } @$val ];
269 }
270 else {
271 2 ▶ croak "FATAL: asn1_encode: CUSTOM primitive value must not be a reference"
Branch: 1 branch
BranchTrueFalseTotal
if ref $val 1 1 2
272 if ref($val);
273 1 $n{value} = _bin_to_raw($val, $fmt);
274 }
275 11 return \%n;
276 }
277 0 croak "FATAL: asn1_encode: unsupported type '$type'";
278 }
279  
280 # Convert binary value from hex/base64 to raw bytes
281 36 ▶sub _bin_to_raw {
Subroutine _bin_to_raw: called CC=7 SCAR=19.5
282 36 my ($val, $fmt) = @_;
283 36 ▶ $val = '' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 36 36
284 36 ▶ $fmt = '' unless defined $fmt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fmt 0 36 36
285 36 ▶ if ($fmt eq 'hex') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "hex") 8 28 36
286 8 ▶ croak "FATAL: asn1_encode: invalid hex value"
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ /\A(?:[0-9A-Fa-f]{2})*\z/ 2 6 8
287 unless $val =~ /\A(?:[0-9A-Fa-f]{2})*\z/;
288 6 return pack("H*", $val);
289 }
290 28 ▶ if ($fmt eq 'base64') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "base64") 8 20 28
291 8 ▶ croak "FATAL: asn1_encode: invalid base64 value"
Branch: 1 branch
BranchTrueFalseTotal
unless $val =~ m[\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\z] 2 6 8
292 unless $val =~ /\A(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?\z/;
293 6 return decode_b64($val);
294 }
295 20 return $val;
296 }
297  
298 32 ▶sub _normalize_oid {
Subroutine _normalize_oid: called CC=12 SCAR=25.8
299 32 my ($val) = @_;
300 32 my $oid = "$val";
301  
302 32 ▶ croak "FATAL: asn1_encode: invalid OID value '$oid'"
Branch: 1 branch
BranchTrueFalseTotal
unless $oid =~ /\A\d+(?:\.\d+)+\z/ 2 30 32
303 unless $oid =~ /\A\d+(?:\.\d+)+\z/;
304  
305 30 my @arc = split /\./, $oid;
306 30 ▶ croak "FATAL: asn1_encode: OID must have at least 2 arcs"
Branch: 1 branch
BranchTrueFalseTotal
unless @arc >= 2 0 30 30
307 unless @arc >= 2;
308 30 ▶ croak "FATAL: asn1_encode: OID first arc must be 0, 1, or 2"
Branch: 1 branch
BranchTrueFalseTotal
unless $arc[0] >= 0 and $arc[0] <= 2 0 30 30
Condition33%1/3
$arc[0] >= 0 and $arc[0] <= 2
!ll&&!rl&&r
0030
MC/DC0%0/2
$arc[0] >= 0 and $arc[0] <= 2
$arc[0] >= 0 $arc[0] <= 2
Truth table33%1/3
A and B
A= $arc[0] >= 0B= $arc[0] <= 2
ABresult
0X0
100
111
309 unless $arc[0] >= 0 && $arc[0] <= 2;
310 30 ▶ croak "FATAL: asn1_encode: OID second arc must be between 0 and 39 when first arc is 0 or 1"
Branch: 1 branch
BranchTrueFalseTotal
if $arc[0] < 2 and $arc[1] > 39 0 30 30
Condition66%2/3
$arc[0] < 2 and $arc[1] > 39
!ll&&!rl&&r
18120
MC/DC0%0/2
$arc[0] < 2 and $arc[1] > 39
$arc[0] < 2 $arc[1] > 39
Truth table66%2/3
A and B
A= $arc[0] < 2B= $arc[1] > 39
ABresult
0X0
100
111
311 if $arc[0] < 2 && $arc[1] > 39;
312 30 ▶ croak "FATAL: asn1_encode: OID has too many arcs (maximum 64)"
Branch: 1 branch
BranchTrueFalseTotal
if @arc > 64 0 30 30
313 if @arc > 64;
314  
315 30 for my $i (1 .. $#arc) {
316 112 ▶ my $limit = ($i == 1 && $arc[0] == 2) ? $_MAX_OID_SECOND_ARC_DEC : $_MAX_ULONG_DEC;
Branch: 1 branch
BranchTrueFalseTotal
$i == 1 && $arc[0] == 2 ? : 18 94 112
Condition100%3/3
$i == 1 and $arc[0] == 2
!ll&&!rl&&r
821218
MC/DC100%2/2
$i == 1 and $arc[0] == 2
$i == 1 $arc[0] == 2
Truth table100%3/3
A and B
A= $i == 1B= $arc[0] == 2
ABresult
0X0
100
111
317 112 ▶ croak "FATAL: asn1_encode: OID arc '$arc[$i]' is too large for this encoder"
Branch: 1 branch
BranchTrueFalseTotal
unless _decimal_fits_limit($arc[$i], $limit) 2 110 112
318 unless _decimal_fits_limit($arc[$i], $limit);
319 }
320  
321 28 return $oid;
322 }
323  
324 13 ▶sub _normalize_bit_count {
Subroutine _normalize_bit_count: called CC=4 SCAR=13.9
325 13 my ($bits, $byte_len) = @_;
326 13 my $max_bits = $byte_len * 8;
327  
328 13 ▶ croak "FATAL: asn1_encode: BIT_STRING bits missing"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bits 0 13 13
329 unless defined $bits;
330  
331 13 my $raw = "$bits";
332 13 ▶ croak "FATAL: asn1_encode: BIT_STRING bits must be a non-negative integer"
Branch: 1 branch
BranchTrueFalseTotal
unless $raw =~ /\A\d+\z/ 2 11 13
333 unless $raw =~ /\A\d+\z/;
334  
335 11 $bits = int($raw);
336 11 ▶ croak "FATAL: asn1_encode: BIT_STRING bits exceeds available data ($bits > $max_bits)"
Branch: 1 branch
BranchTrueFalseTotal
if $bits > $max_bits 1 10 11
337 if $bits > $max_bits;
338  
339 10 return $bits;
340 }
341  
342 17 ▶sub _normalize_custom_tag {
Subroutine _normalize_custom_tag: called CC=3 SCAR=11.0
343 17 my ($tag) = @_;
344 17 my $raw = "$tag";
345  
346 17 ▶ croak "FATAL: asn1_encode: CUSTOM tag must be a non-negative integer"
Branch: 1 branch
BranchTrueFalseTotal
unless $raw =~ /\A\d+\z/ 3 14 17
347 unless $raw =~ /\A\d+\z/;
348 14 ▶ croak "FATAL: asn1_encode: CUSTOM tag '$raw' is too large for this encoder"
Branch: 1 branch
BranchTrueFalseTotal
unless _decimal_fits_limit($raw, $_MAX_ULONG_DEC) 1 13 14
349 unless _decimal_fits_limit($raw, $_MAX_ULONG_DEC);
350  
351 13 return int($raw);
352 }
353  
354 126 ▶sub _decimal_fits_limit {
Subroutine _decimal_fits_limit: called CC=3 SCAR=11.0
355 126 my ($value, $limit) = @_;
356 126 $value = "$value";
357 126 $value =~ s/\A0+(?=\d)//;
358 126 ▶ return 1 if length($value) < length($limit);
Branch: 1 branch
BranchTrueFalseTotal
if length $value < length $limit 123 3 126
359 3 ▶ return 0 if length($value) > length($limit);
Branch: 1 branch
BranchTrueFalseTotal
if length $value > length $limit 1 2 3
360 2 return $value le $limit;
361 }
362  
363 2 ▶sub _max_ulong_dec {
Subroutine _max_ulong_dec: called CC=4 SCAR=17.1
364 2 ▶ my $bytes = $Config::Config{longsize} || 0;
Condition50%1/2
$Config::Config{'longsize'} || 0
l!l
20
MC/DC0%0/1
$Config::Config{'longsize'} || 0
$Config::Config{'longsize'}
Truth table50%1/2
A
A= $Config::Config{'longsize'}
Aresult
11
00
365 2 ▶ return '4294967295' if $bytes == 4;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes == 4 0 2 2
366 2 ▶ return '18446744073709551615' if $bytes == 8;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes == 8 2 0 2
367  
368 0 require Math::BigInt;
369 0 return Math::BigInt->new(2)->bpow($bytes * 8)->bsub(1)->bstr();
370 }
371  
372 2 ▶sub _max_oid_second_arc_dec {
Subroutine _max_oid_second_arc_dec: called CC=4 SCAR=17.1
373 2 ▶ my $bytes = $Config::Config{longsize} || 0;
Condition50%1/2
$Config::Config{'longsize'} || 0
l!l
20
MC/DC0%0/1
$Config::Config{'longsize'} || 0
$Config::Config{'longsize'}
Truth table50%1/2
A
A= $Config::Config{'longsize'}
Aresult
11
00
374 2 ▶ return '4294967215' if $bytes == 4;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes == 4 0 2 2
375 2 ▶ return '18446744073709551535' if $bytes == 8;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes == 8 2 0 2
376  
377 0 require Math::BigInt;
378 0 return Math::BigInt->new(_max_ulong_dec())->bsub(80)->bstr();
379 }
380  
381 # Normalize timestamp to ASN.1 wire format
382 19 ▶sub _normalize_time {
Subroutine _normalize_time: called CC=22 SCAR=32.1
383 19 my ($val, $fmt, $kind) = @_;
384 19 ▶ croak "FATAL: asn1_encode: time value missing" unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 19 19
385 19 ▶ my $type = $kind eq 'utc' ? 'UTCTIME' : 'GENERALIZEDTIME';
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'utc' ? : 16 3 19
386  
387 # epoch (all digits, possibly negative)
388 19 ▶ if ($fmt eq 'epoch' || ($fmt eq '' && $val =~ /^-?\d+$/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "epoch" or $fmt eq "" and $val =~ /^-?\d+$/) 5 14 19
Condition66%4/6
$fmt eq "epoch" or $fmt eq "" and $val =~ /^-?\d+$/
l!l&&r!l&&!r
5014
$fmt eq "" and $val =~ /^-?\d+$/
!ll&&!rl&&r
4100
MC/DC33%1/3
$fmt eq "epoch" or $fmt eq "" and $val =~ /^-?\d+$/
$fmt eq "epoch" $fmt eq "" $val =~ /^-?\d+$/
Truth table75%3/4
A or B and C
A= $fmt eq "epoch"B= $fmt eq ""C= $val =~ /^-?\d+$/
ABCresult
1XX1
0111
00X0
0100
389 5 my @t = gmtime($val);
390 5 my $year = $t[5] + 1900;
391 5 ▶ if ($kind eq 'utc') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "utc") 5 0 5
392 5 ▶ croak "FATAL: asn1_encode: UTCTIME year out of range: $year (expected 1950..2049)"
Branch: 1 branch
BranchTrueFalseTotal
if $year < 1950 or $year > 2049 1 4 5
Condition66%2/3
$year < 1950 or $year > 2049
l!l&&r!l&&!r
014
MC/DC50%1/2
$year < 1950 or $year > 2049
$year < 1950 $year > 2049
Truth table66%2/3
A or B
A= $year < 1950B= $year > 2049
ABresult
1X1
011
000
393 if $year < 1950 || $year > 2049;
394 }
395 4 ▶ return ($kind eq 'utc')
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'utc' ? : 4 0 4
396 ? sprintf("%02d%02d%02d%02d%02d%02dZ", $t[5] % 100, $t[4]+1, $t[3], $t[2], $t[1], $t[0])
397 : sprintf("%04d%02d%02d%02d%02d%02dZ", $t[5]+1900, $t[4]+1, $t[3], $t[2], $t[1], $t[0]);
398 }
399  
400 # RFC 3339 (e.g. "2024-01-15T10:30:00Z" or "2024-01-15T10:30:00.5+05:30")
401 14 ▶ if ($fmt eq 'rfc3339' || $val =~ /^\d{4}-/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "rfc3339" or $val =~ /^\d{4}-/) 10 4 14
Condition100%3/3
$fmt eq "rfc3339" or $val =~ /^\d{4}-/
l!l&&r!l&&!r
464
MC/DC100%2/2
$fmt eq "rfc3339" or $val =~ /^\d{4}-/
$fmt eq "rfc3339" $val =~ /^\d{4}-/
Truth table100%3/3
A or B
A= $fmt eq "rfc3339"B= $val =~ /^\d{4}-/
ABresult
1X1
011
000
402 10 ▶ $val =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/
Branch: 1 branch
BranchTrueFalseTotal
$val =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/ or croak("FATAL: asn1_encode: invalid RFC 3339 time for ${type}: $val") 10 0 10
403 or croak "FATAL: asn1_encode: invalid RFC 3339 time for $type: $val";
404 10 my ($YYYY,$MM,$DD,$hh,$mm,$ss,$fs,$tz,$sign,$oh,$om) = ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11);
405 10 my $r;
406 10 ▶ if ($kind eq 'utc') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq 'utc') { } 9 1 10
407 9 ▶ croak "FATAL: asn1_encode: UTCTIME does not allow fractional seconds: $val"
Branch: 1 branch
BranchTrueFalseTotal
if defined $fs and length $fs 1 8 9
Condition66%2/3
defined $fs and length $fs
!ll&&!rl&&r
801
MC/DC50%1/2
defined $fs and length $fs
defined $fs length $fs
Truth table66%2/3
A and B
A= defined $fsB= length $fs
ABresult
0X0
100
111
408 if defined $fs && length $fs;
409 8 ▶ croak "FATAL: asn1_encode: UTCTIME year out of range: $YYYY (expected 1950..2049)"
Branch: 1 branch
BranchTrueFalseTotal
if $YYYY < 1950 or $YYYY > 2049 2 6 8
Condition100%3/3
$YYYY < 1950 or $YYYY > 2049
l!l&&r!l&&!r
116
MC/DC100%2/2
$YYYY < 1950 or $YYYY > 2049
$YYYY < 1950 $YYYY > 2049
Truth table100%3/3
A or B
A= $YYYY < 1950B= $YYYY > 2049
ABresult
1X1
011
000
410 if $YYYY < 1950 || $YYYY > 2049;
411 6 ▶ my $YY = ($YYYY >= 2000) ? $YYYY - 2000 : $YYYY - 1900;
Branch: 1 branch
BranchTrueFalseTotal
$YYYY >= 2000 ? : 6 0 6
412 6 $r = sprintf "%02d%02d%02d%02d%02d%02d", $YY, $MM, $DD, $hh, $mm, $ss;
413 }
414 else {
415 1 $r = sprintf "%04d%02d%02d%02d%02d%02d", $YYYY, $MM, $DD, $hh, $mm, $ss;
416 1 ▶ $r .= ".$fs" if defined $fs && $fs > 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $fs and $fs > 0 1 0 1
Condition33%1/3
defined $fs and $fs > 0
!ll&&!rl&&r
001
MC/DC0%0/2
defined $fs and $fs > 0
defined $fs $fs > 0
Truth table33%1/3
A and B
A= defined $fsB= $fs > 0
ABresult
0X0
100
111
417 }
418 7 ▶ $r .= ($tz eq 'Z') ? 'Z' : sprintf("%s%02d%02d", $sign, $oh, $om);
Branch: 1 branch
BranchTrueFalseTotal
$tz eq 'Z' ? : 7 0 7
419 7 return $r;
420 }
421  
422 4 croak "FATAL: asn1_encode: invalid $type value '$val' (expected RFC 3339 string or epoch)";
423 }
424  
425 2 1;
426  
427 =pod
428  
429 =head1 NAME
430  
431 Crypt::ASN1 - DER ASN.1 parser and encoder based on libtomcrypt
432  
433 =head1 SYNOPSIS
434  
435 use Crypt::ASN1 qw(asn1_decode_der asn1_encode_der asn1_to_string);
436  
437 # --- decode ---
438 my $tree = asn1_decode_der($der_bytes);
439 my $tree = asn1_decode_der($der_bytes, { int => 'hex', bin => 'hex' });
440  
441 # --- inspect ---
442 print asn1_to_string($tree);
443  
444 # --- encode a decoded tree ---
445 my $der2 = asn1_encode_der($tree);
446  
447 # --- build from scratch ---
448 my $der = asn1_encode_der([{
449 type => 'SEQUENCE',
450 value => [
451 { type => 'INTEGER', value => '42' },
452 { type => 'BOOLEAN', value => 1 },
453 { type => 'OID', value => '1.2.840.113549.1.1.11' },
454 { type => 'UTF8_STRING', value => 'hello' },
455 { type => 'OCTET_STRING', value => "\x00\x01\x02" },
456 { type => 'BIT_STRING', value => "\x03\x02\x01", bits => 20 },
457 { type => 'NULL' },
458 { type => 'UTCTIME', value => '2025-06-15T12:00:00Z' },
459 { type => 'CUSTOM', class => 'CONTEXT_SPECIFIC',
460 constructed => 1, tag => 0,
461 value => [{ type => 'INTEGER', value => '2' }] },
462 ],
463 }]);
464  
465 =head1 DESCRIPTION
466  
467 I<Since: CryptX-0.089>
468  
469 Parses DER-encoded ASN.1 data into a Perl data structure without requiring
470 any schema, and encodes Perl data structures back to DER.
471 Uses libtomcrypt's C<der_decode_sequence_flexi> for decoding.
472  
473 Both the decoder output and the encoder input use the same B<node hash>
474 structure described below. When given a tree produced by the decoder, the
475 encoder does its best to produce the same ASN.1 that was originally parsed,
476 regardless of what decode options were used.
477  
478 =head1 EXPORT
479  
480 Nothing is exported by default.
481  
482 You can export selected functions:
483  
484 use Crypt::ASN1 qw(asn1_decode_der asn1_encode_der);
485  
486 Or all of them at once:
487  
488 use Crypt::ASN1 ':all';
489  
490 =head1 NODE HASH STRUCTURE
491  
492 Both the decoder and encoder operate on the same data structure: an B<arrayref
493 of node hashrefs>. Each hashref represents one ASN.1 TLV (Tag-Length-Value)
494 element.
495  
496 =head2 Common keys
497  
498 Every node has three keys:
499  
500 =over
501  
502 =item C<type> (string, required)
503  
504 The ASN.1 type name. Built-in values include:
505  
506 BOOLEAN INTEGER NULL OID
507 OCTET_STRING BIT_STRING UTF8_STRING
508 PRINTABLE_STRING IA5_STRING TELETEX_STRING
509 UTCTIME GENERALIZEDTIME
510 SEQUENCE SET CUSTOM
511  
512 The list above is not exhaustive for decoded input. If the decoder encounters
513 an ASN.1 tag that does not map to one of the built-in type names above, it is
514 returned as C<CUSTOM> with the appropriate C<class>, C<constructed>, and
515 C<tag> fields. This includes unsupported universal tags such as
516 C<ENUMERATED>, which decode as C<CUSTOM> with C<< class => "UNIVERSAL" >>.
517  
518 =item C<value> (varies, required for most types)
519  
520 The decoded value. Its Perl type depends on C<type> and sometimes on the
521 C<format> key -- see L</Per-type details> below.
522  
523 =item C<format> (string, decoder sets it, encoder reads it)
524  
525 Tells the encoder how the C<value> is represented so it can convert it back
526 to DER. Set automatically by the decoder; when building nodes from scratch
527 you may omit it -- the encoder then assumes the default representation for
528 each type.
529  
530 =back
531  
532 =head2 Per-type details
533  
534 Each subsection below documents one C<type>. For types where the C<value>
535 representation depends on the decode option used, a B<format table> lists
536 every C<format>/C<value> combination. B<The encoder accepts every
537 combination shown> -- it reads C<format> and converts C<value> back to DER
538 automatically.
539  
540 =head3 BOOLEAN
541  
542 B<Keys>: C<type>, C<format>, C<value>.
543  
544 C<value> is C<1> (true) or C<0> (false). C<format> is always C<"bool">.
545  
546 { type => "BOOLEAN", format => "bool", value => 1 }
547  
548 =head3 INTEGER
549  
550 B<Keys>: C<type>, C<format>, C<value>.
551  
552 C<value> is an arbitrary-precision signed integer. C<format> describes the
553 representation:
554  
555 format value decode option example
556 -------- --------------------------- ---------------- ---------------
557 decimal decimal string (default) "255"
558 hex lowercase hex string int => 'hex' "ff"
559 bytes big-endian binary string int => 'bytes' "\xff"
560  
561 All three forms are accepted by the encoder. When C<format> is absent the
562 encoder treats C<value> as a decimal string (a Perl integer is fine too).
563  
564 Negative integers: C<decimal> and C<hex> carry a leading C<-> (e.g. C<"-5">).
565 C<bytes> stores the unsigned magnitude only and is intended for naturally
566 unsigned values such as RSA moduli. When decoding with C<< int => 'bytes' >>,
567 negative ASN.1 INTEGER values are rejected.
568  
569 =head3 NULL
570  
571 B<Keys>: C<type>, C<format>, C<value>.
572  
573 C<value> is always C<undef>. C<format> is always C<"null">. The encoder
574 ignores C<value>.
575  
576 { type => "NULL", format => "null", value => undef }
577  
578 =head3 OID
579  
580 B<Keys>: C<type>, C<format>, C<value>, and optionally C<name>.
581  
582 C<value> is a dotted-decimal OID string (at least two arcs). C<format> is
583 always C<"oid">.
584  
585 { type => "OID", format => "oid", value => "1.2.840.113549.1.1.11" }
586  
587 As a convenience, the encoder accepts textual arcs with leading zeros and
588 lets DER encoding canonicalize them. For example, C<"2.000.1"> encodes and
589 decodes back as C<"2.0.1">.
590  
591 B<Optional key>: C<name> -- present only when the C<oidmap> decode option
592 is supplied and the OID is found in the map. Ignored by the encoder.
593  
594 { ..., name => "sha256WithRSAEncryption" } # when oidmap matches
595  
596 =head3 OCTET_STRING
597  
598 B<Keys>: C<type>, C<format>, C<value>.
599  
600 C<value> is binary data. C<format> describes the representation:
601  
602 format value decode option example
603 -------- --------------------------- ----------------- --------
604 bytes raw binary string (default) "\x04\x01"
605 hex lowercase hex string bin => 'hex' "0401"
606 base64 Base64-encoded string bin => 'base64' "BAE="
607  
608 All three forms are accepted by the encoder. When C<format> is absent the
609 encoder treats C<value> as raw bytes.
610  
611 =head3 BIT_STRING
612  
613 B<Keys>: C<type>, C<format>, C<value>, C<bits>.
614  
615 C<value> is the packed bit data (MSB-first). C<format> follows the same
616 rules as C<OCTET_STRING> (C<"bytes">, C<"hex">, or C<"base64">). All three
617 forms are accepted by the encoder.
618  
619 C<bits> is the exact number of significant bits. The quantity
620 C<< 8 * byte_length(value) - bits >> gives the number of unused trailing
621 bits in the last byte.
622  
623 When C<format> is absent the encoder treats C<value> as raw bytes. When
624 C<bits> is absent it defaults to C<< 8 * length(value) >> (no unused bits).
625  
626 # default format (raw bytes, 25 significant bits)
627 { type => "BIT_STRING", format => "bytes",
628 value => "\x03\x02\x01\x00", bits => 25 }
629  
630 # hex format
631 { type => "BIT_STRING", format => "hex",
632 value => "03020100", bits => 25 }
633  
634 =head3 UTF8_STRING
635  
636 B<Keys>: C<type>, C<format>, C<value>.
637  
638 C<value> is a Perl Unicode string (C<utf8> flag on). C<format> is always
639 C<"utf8">.
640  
641 { type => "UTF8_STRING", format => "utf8", value => "caf\x{e9}" }
642  
643 =head3 PRINTABLE_STRING, IA5_STRING, TELETEX_STRING
644  
645 B<Keys>: C<type>, C<format>, C<value>.
646  
647 C<value> is a byte string. C<format> is always C<"string"> for all three.
648  
649 { type => "PRINTABLE_STRING", format => "string", value => "abc" }
650 { type => "IA5_STRING", format => "string", value => "ia5" }
651 { type => "TELETEX_STRING", format => "string", value => "tele" }
652  
653 =head3 UTCTIME
654  
655 B<Keys>: C<type>, C<format>, C<value>.
656  
657 C<value> is a timestamp. C<format> describes the representation:
658  
659 format value decode option example
660 -------- ----------------------------- --------------- -----------------------
661 rfc3339 RFC 3339 string (default) "2024-01-15T10:30:00Z"
662 epoch Unix timestamp (integer) dt => 'epoch' 1705314600
663  
664 Both forms are accepted by the encoder. When C<format> is absent, the
665 encoder auto-detects: an all-digit value is treated as epoch, a value
666 matching C<YYYY-> is treated as RFC 3339.
667  
668 For C<UTCTIME>, encoder input must fall within the UTCTime year window
669 C<1950..2049>; values outside that range are rejected. Fractional seconds
670 are also rejected for C<UTCTIME>.
671  
672 Time validation in the encoder is currently B<syntactic>, not full calendar
673 validation. The encoder checks the accepted input shape and ASN.1-specific
674 constraints above, but it does not verify that every RFC 3339-looking date
675 and time is semantically valid.
676  
677 The decoder expands the 2-digit UTCTime year using the RFC 5280 window
678 (YY E<gt>= 50 E<rarr> 19YY, else 20YY). Timezone offsets are preserved
679 (e.g. C<"2024-01-15T10:30:00+05:30">).
680  
681 =head3 GENERALIZEDTIME
682  
683 B<Keys>: C<type>, C<format>, C<value>.
684  
685 Same C<format> rules as C<UTCTIME>; both forms are accepted by the encoder.
686 Fractional seconds are preserved (e.g. C<"2024-01-15T10:30:00.125Z">).
687 Validation is likewise syntactic only; semantically invalid calendar values
688 that match the accepted timestamp syntax are not currently rejected.
689  
690 =head3 SEQUENCE
691  
692 B<Keys>: C<type>, C<format>, C<value>.
693  
694 C<value> is an arrayref of child node hashrefs (in order). C<format> is
695 always C<"array">.
696  
697 { type => "SEQUENCE", format => "array", value => [ ...children... ] }
698  
699 =head3 SET
700  
701 B<Keys>: C<type>, C<format>, C<value>.
702  
703 Same structure as C<SEQUENCE>. C<format> is always C<"array">. Both
704 ASN.1 SET and SET OF are represented as C<type =E<gt> "SET"> (they share
705 the same DER tag C<0x31>).
706  
707 =head3 CUSTOM
708  
709 Represents any tag that does not map to one of the built-in type names above.
710 This is commonly used for context-specific implicit/explicit tags (C<[0]>,
711 C<[1]>, ...) found in X.509 certificates and other ASN.1 schemas, but it can
712 also be emitted by the decoder for unsupported universal tags.
713  
714 B<Keys>: C<type>, C<format>, C<value>, C<class>, C<constructed>, C<tag>.
715  
716 =over
717  
718 =item C<class> (string) -- C<"CONTEXT_SPECIFIC">, C<"APPLICATION">, C<"UNIVERSAL">, or C<"PRIVATE">
719  
720 =item C<constructed> (integer) -- C<1> if constructed, C<0> if primitive
721  
722 =item C<tag> (integer) -- the tag number (e.g. C<0> for C<[0]>)
723  
724 Must be a non-negative integer within the range supported by the current
725 encoder build.
726  
727 =back
728  
729 B<Constructed> (C<< constructed => 1 >>): C<value> is an arrayref of child
730 nodes. C<format> is C<"array">.
731  
732 { type => "CUSTOM", format => "array",
733 class => "CONTEXT_SPECIFIC", constructed => 1, tag => 0,
734 value => [ { type => "INTEGER", ... } ] }
735  
736 B<Primitive> (C<< constructed => 0 >>): C<value> is raw data. C<format>
737 follows the same rules as C<OCTET_STRING> (C<"bytes">, C<"hex">, or
738 C<"base64"> depending on the C<bin> decode option). All three forms are
739 accepted by the encoder. Primitive C<CUSTOM> values must not be references.
740  
741 # default format
742 { type => "CUSTOM", format => "bytes",
743 class => "CONTEXT_SPECIFIC", constructed => 0, tag => 1,
744 value => "\xAA\xBB" }
745  
746 # hex format (bin => 'hex')
747 { type => "CUSTOM", format => "hex",
748 class => "CONTEXT_SPECIFIC", constructed => 0, tag => 1,
749 value => "aabb" }
750  
751 =head2 Re-encoding Decoded Trees
752  
753 The encoder reads C<format> and converts C<value> back to DER before
754 encoding. When given a tree returned by C<asn1_decode_der>, it does its best
755 to produce the same ASN.1 that was originally parsed, regardless of the
756 decode options used:
757  
758 my $tree = asn1_decode_der($der, { int=>'hex', bin=>'base64', dt=>'epoch' });
759 my $der2 = asn1_encode_der($tree);
760  
761 =head2 Building nodes from scratch
762  
763 When constructing nodes by hand you need C<type> and C<value> (plus the
764 extra keys noted above for C<CUSTOM> and C<BIT_STRING>). You may omit
765 C<format>; the encoder assumes:
766  
767 Type default value interpretation
768 ---------------- ------------------------------------------
769 INTEGER decimal string or Perl integer
770 OCTET_STRING raw bytes
771 BIT_STRING raw packed bytes, bits = length(value) * 8
772 UTCTIME RFC 3339 string (or all-digit epoch)
773 GENERALIZEDTIME RFC 3339 string (or all-digit epoch)
774 CUSTOM primitive raw bytes
775  
776 You may also supply C<format> explicitly if you prefer to work with hex
777 or base64 representations:
778  
779 # these two produce identical DER
780 { type => "OCTET_STRING", value => "\x04\x01" }
781 { type => "OCTET_STRING", format => "hex", value => "0401" }
782  
783 =head1 FUNCTIONS
784  
785 =head2 asn1_decode_der
786  
787 my $tree = asn1_decode_der($der_bytes);
788 my $tree = asn1_decode_der($der_bytes, \%opts);
789  
790 Parses C<$der_bytes> and returns an arrayref of top-level node hashrefs.
791 Croaks on parse error.
792  
793 The optional C<%opts> hashref controls value formatting:
794  
795 =over
796  
797 =item C<int =E<gt> 'hex' | 'bytes'>
798  
799 How to represent C<INTEGER> values. Default is a decimal string
800 (C<< format=>"decimal" >>).
801 C<'hex'> gives a lowercase hex string (C<< format=>"hex" >>).
802 C<'bytes'> gives a raw big-endian binary string (C<< format=>"bytes" >>) for
803 non-negative INTEGER values only; decoding croaks if the DER INTEGER is
804 negative.
805  
806 =item C<bin =E<gt> 'hex' | 'base64'>
807  
808 How to represent C<OCTET_STRING>, C<BIT_STRING>, and primitive C<CUSTOM>
809 values. Default is raw binary bytes (C<< format=>"bytes" >>).
810 C<'hex'> gives a lowercase hex string (C<< format=>"hex" >>).
811 C<'base64'> gives a Base64-encoded string (C<< format=>"base64" >>).
812  
813 =item C<dt =E<gt> 'epoch'>
814  
815 How to represent C<UTCTIME> and C<GENERALIZEDTIME> values. Default is an
816 RFC 3339 string (C<< format=>"rfc3339" >>).
817 C<'epoch'> gives a Unix timestamp integer (C<< format=>"epoch" >>).
818 This works reliably only on Perls with 64-bit integers; on 32-bit integer
819 Perls, large timestamps may overflow or lose precision.
820  
821 =item C<oidmap =E<gt> \%map>
822  
823 A hashref mapping dotted OID strings to friendly names. When a decoded
824 C<OID> node's value exists as a key in C<%map>, the node gets an additional
825 C<name> key with the mapped value. Does not affect encoding.
826  
827 =back
828  
829 =head2 asn1_decode_pem
830  
831 my $tree = asn1_decode_pem($pem_string);
832 my $tree = asn1_decode_pem($pem_string, \%opts);
833  
834 Decodes the PEM envelope first (via L<Crypt::Misc/pem_to_der>), then parses
835 the resulting DER bytes. Accepts the same C<%opts> as C<asn1_decode_der>.
836  
837 =head2 asn1_decode_der_file
838  
839 my $tree = asn1_decode_der_file($filename);
840 my $tree = asn1_decode_der_file($filename, \%opts);
841  
842 Reads C<$filename> as raw binary and parses it as DER.
843  
844 =head2 asn1_decode_pem_file
845  
846 my $tree = asn1_decode_pem_file($filename);
847 my $tree = asn1_decode_pem_file($filename, \%opts);
848  
849 Reads C<$filename>, decodes the PEM envelope, then parses the DER bytes.
850  
851 =head2 asn1_encode_der
852  
853 my $der_bytes = asn1_encode_der($tree);
854  
855 Encodes C<$tree> (an arrayref of node hashrefs) to DER bytes. The input
856 may be a tree previously returned by C<asn1_decode_der> or one
857 built from scratch. Croaks on invalid input.
858  
859 The encoder normalizes every node before encoding: it reads C<format> (if
860 present) to determine how to interpret C<value>, converts it to the canonical
861 DER form, and encodes it.
862  
863 The current low-level encoder supports element content lengths up to
864 C<0xffffffff> bytes; larger values are rejected.
865  
866 =head2 asn1_encode_pem
867  
868 my $pem_string = asn1_encode_pem($tree, $header);
869  
870 Encodes C<$tree> to DER, then wraps in a PEM envelope with the given
871 C<$header> (e.g. C<"CERTIFICATE">, C<"RSA PRIVATE KEY">). Defaults to
872 C<"DATA"> if C<$header> is omitted.
873  
874 =head2 asn1_encode_der_file
875  
876 asn1_encode_der_file($tree, $filename);
877  
878 Encodes C<$tree> to DER and writes it to C<$filename>.
879  
880 =head2 asn1_encode_pem_file
881  
882 asn1_encode_pem_file($tree, $header, $filename);
883  
884 Encodes C<$tree> to PEM and writes it to C<$filename>.
885  
886 =head2 asn1_to_string
887  
888 my $text = asn1_to_string($tree);
889  
890 Returns a human-readable text representation of C<$tree> (an arrayref of
891 node hashrefs as returned by any C<asn1_decode_*> function). Useful for
892 debugging and inspection, similar to C<openssl asn1parse> output.
893  
894 print asn1_to_string(asn1_decode_pem_file("cert.pem"));
895  
896 produces output like:
897  
898 SEQUENCE (3 elem)
899 SEQUENCE (8 elem)
900 context_specific [0] cons (1 elem)
901 INTEGER:2
902 INTEGER:17923815188543234454
903 SEQUENCE (2 elem)
904 OBJECT:1.2.840.113549.1.1.11
905 NULL:
906 ...
907 BIT STRING:3082010a0282010100c242299a49420c21dcf9b957afcdc49... (2160 bit)
908  
909 Binary values (C<OCTET_STRING>, C<BIT_STRING>, primitive C<CUSTOM>) are
910 shown as lowercase hex, truncated to 64 characters with C<...> for longer
911 values. C<BIT_STRING> additionally shows the bit count in parentheses.
912 C<OID> nodes that have a C<name> key (via C<oidmap>) show the name in
913 parentheses after the dotted value.
914  
915 The function handles trees decoded with any combination of decode options
916 (C<int>, C<bin>, C<dt>).
917  
918 =head1 SEE ALSO
919  
920 L<CryptX>, L<Crypt::Misc>
921  
922 =cut
« blib/lib/Crypt/PK/DSA.pm ↑ Summary blib/lib/Math/BigInt/LTM.pm »