1#!/usr/bin/perl
2
3# dertoc.pl
4# version 1.0
5# Updated 07/31/2018
6#
7# Copyright (C) 2006-2018 wolfSSL Inc.
8#
9
10use strict;
11use warnings;
12
13my $num_args = $#ARGV + 1;
14if ($num_args != 3 ) {
15    print "usage: ./scripts/dertoc.pl ./certs/server-cert.der server_cert_der_2048 dertoc.c\n";
16    exit;
17}
18
19my $inFile = $ARGV[0];
20my $outName = $ARGV[1];
21my $outputFile = $ARGV[2];
22
23# open our output file, "+>" creates and/or truncates
24open OUT_FILE, "+>", $outputFile  or die $!;
25
26print OUT_FILE "/* $outputFile */\n\n";
27
28print OUT_FILE "static const unsigned char $outName\[] =\n";
29print OUT_FILE "{\n";
30file_to_hex($inFile);
31print OUT_FILE "};\n";
32print OUT_FILE "static const int sizeof_$outName = sizeof($outName);\n\n";
33
34# close file
35close OUT_FILE or die $!;
36
37
38
39# print file as hex, comma-separated, as needed by C buffer
40sub file_to_hex {
41    my $fileName = $_[0];
42
43    open my $fp, "<", $fileName or die $!;
44    binmode($fp);
45
46    my $fileLen = -s $fileName;
47    my $byte;
48
49    for (my $i = 0, my $j = 1; $i < $fileLen; $i++, $j++)
50    {
51        if ($j == 1) {
52            print OUT_FILE "\t";
53        }
54        read($fp, $byte, 1) or die "Error reading $fileName";
55        my $output = sprintf("0x%02X", ord($byte));
56        print OUT_FILE $output;
57
58        if ($i != ($fileLen - 1)) {
59            print OUT_FILE ", ";
60        }
61
62        if ($j == 10) {
63            $j = 0;
64            print OUT_FILE "\n";
65        }
66    }
67
68    print OUT_FILE "\n";
69
70    close($fp);
71}
72