genhexbuf.pl 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/perl
  2. # genhexbuf.pl
  3. # Copyright (C) 2020 wolfSSL Inc.
  4. #
  5. use strict;
  6. use warnings;
  7. # ---- SCRIPT SETTINGS -------------------------------------------------------
  8. # output C header file to write cert/key buffers to
  9. my $outputFile = "certs_sig_data.h";
  10. # rsa keys and certs to be converted
  11. my @fileList = (
  12. # please add your der file and name of the data for C language
  13. # der file name name of the data
  14. #[ "./yourder.der", "your_der_name_in_C" ],
  15. [ "./ca-cert.der", "ca_cert_der" ],
  16. [ "./ca-cert.der.sign", "ca_cert_der_sign" ],
  17. );
  18. # ----------------------------------------------------------------------------
  19. my $num = @fileList;
  20. # open our output file, "+>" creates and/or truncates
  21. open OUT_FILE, "+>", $outputFile or die $!;
  22. print OUT_FILE "/* certs_sig_data.h */\n\n";
  23. print OUT_FILE "#ifndef WOLFSSL_CERTS_SIG_DATA_H\n";
  24. print OUT_FILE "#define WOLFSSL_CERTS_SIG_DATA_H\n\n";
  25. # convert and print 1024-bit cert/keys
  26. for (my $i = 0; $i < $num; $i++) {
  27. my $fname = $fileList[$i][0];
  28. my $sname = $fileList[$i][1];
  29. print OUT_FILE "/* $fname, */\n";
  30. print OUT_FILE "static const unsigned char $sname\[] =\n";
  31. print OUT_FILE "{\n";
  32. file_to_hex($fname);
  33. print OUT_FILE "};\n";
  34. print OUT_FILE "static const int sizeof_$sname = sizeof($sname);\n\n";
  35. }
  36. print OUT_FILE "#endif /* WOLFSSL_CERTS_SIG_DATA_H */\n\n";
  37. # print file as hex, comma-separated, as needed by C buffer
  38. sub file_to_hex {
  39. my $fileName = $_[0];
  40. open my $fp, "<", $fileName or die $!;
  41. binmode($fp);
  42. my $fileLen = -s $fileName;
  43. my $byte;
  44. for (my $i = 0, my $j = 1; $i < $fileLen; $i++, $j++)
  45. {
  46. if ($j == 1) {
  47. print OUT_FILE " ";
  48. }
  49. if ($j != 1) {
  50. print OUT_FILE " ";
  51. }
  52. read($fp, $byte, 1) or die "Error reading $fileName";
  53. my $output = sprintf("0x%02X", ord($byte));
  54. print OUT_FILE $output;
  55. if ($i != ($fileLen - 1)) {
  56. print OUT_FILE ",";
  57. }
  58. if ($j == 10) {
  59. $j = 0;
  60. print OUT_FILE "\n";
  61. }
  62. }
  63. print OUT_FILE "\n";
  64. close($fp);
  65. }