#! /usr/bin/perl

use strict;
use warnings;
use English qw( -no_match_vars );
use HTTP::PublicKeyPins();
use Getopt::Long();

our $VERSION = 0.01;

MAIN: {
    my %options;
    Getopt::Long::GetOptions( \%options, 'help', 'version' );
    if ( $options{help} ) {
        usage();
        exit 0;
    }
    elsif ( $options{version} ) {
        print "Version $VERSION\n"
          or Carp::croak("Failed to print to STDOUT:$EXTENDED_OS_ERROR");
    }
    foreach my $path (@ARGV) {
        print HTTP::PublicKeyPins::pin_sha256($path) . "\n"
          or Carp::croak("Failed to print to STDOUT:$EXTENDED_OS_ERROR");
    }
}

sub usage {
    print
      <<"__USAGE__" or Carp::croak("Failed to print to STDOUT:$EXTENDED_OS_ERROR");
Usage: $PROGRAM_NAME [--help] [--version] path_to_PEM_encoded_certificate_file

This program will print out the pin-sha256 value for a TLS/SSL certificate.  The pin-sha256 value for a certificate is used by HTTP Public Key Pins (HPKP) defined by RFC 7469

IMPORTANT - PLEASE UNDERSTAND WHAT THIS HEADER MEANS BEFORE USING IT

Example Public-Key-Pins headers for HTTP from RFC 7469 can be found below;

 * Public-Key-Pins: max-age=3000; pin-sha256="\$short_term_pin_sha256_for_primary_key"; pin-sha256="\$short_term_pin_sha256_for_offline_backup_primary_key"

 * Public-Key-Pins: max-age=2592000; pin-sha256="\$long_term_pin_sha256_for_primary_key"; pin-sha256="\$long_term_pin_sha256_for_offline_backup_primary_key"

 * Public-Key-Pins: max-age=2592000; pin-sha256="\$long_term_pin_sha256_for_primary_key"; pin-sha256="\$long_term_pin_sha256_for_offline_backup_primary_key"; report-uri="http://example.com/pkp-report"

 * Public-Key-Pins-Report-Only: max-age=2592000; pin-sha256="\$long_term_pin_sha256_for_primary_key"; pin-sha256="\$long_term_pin_sha256_for_offline_backup_primary_key"; report-uri="https://other.example.net/pkp-report"

 * Public-Key-Pins: pin-sha256="\$long_term_pin_sha256_for_primary_key"; pin-sha256="\$long_term_pin_sha256_for_offline_backup_primary_key"; max-age=259200

 * Public-Key-Pins: pin-sha256="\$medium_term_pin_sha256_for_primary_key"; pin-sha256="\$medium_term_pin_sha256_for_offline_backup_primary_key"; pin-sha256="\$medium_term_pin_sha256_for_second_offline_backup_primary_key"; max-age=10000; includeSubDomains

__USAGE__
    return;
}
