#!/usr/bin/env perl use v5.34; use warnings; use utf8; use autodie; use Digest::SHA 'hmac_sha256_hex'; use JSON::PP 'decode_json'; use MIME::Base64 'decode_base64'; use Pod::Usage 'pod2usage'; sub main { pod2usage if !@ARGV || $ARGV[0] eq '-h' || $ARGV[0] eq '--help'; die 'invalid number of args' unless @ARGV == 1 || @ARGV == 3; my @check_args = $ARGV[0]; if (@ARGV == 3) { push @check_args, $ARGV[1], $ARGV[2]; } my ($match, $res) = check_cookie(@check_args); if (defined $match && !$match) { say STDERR 'mismatched mac'; exit 1; } my $json = decode_json $res; print JSON::PP->new()->pretty(1)->canonical(1)->encode($json); } sub check_cookie { my $cookie = shift; # split my $splitAt = rindex $cookie, '--'; die 'invalid format' if $splitAt == -1; my $val = substr $cookie, 0, $splitAt; my $sig = substr $cookie, $splitAt+2; my $match; if (@_) { my ($cookie_name, $secret) = @_; # hmac my $check = hmac_sha256_hex "$cookie_name=$val", $secret; $match = $sig eq $check; } # change base64 padding $val =~ s/-*$/'=' x length $&/e; # base64 my $res = decode_base64 $val; # cookie content padding $res =~ s/Z*$//; return $match, $res; } main unless caller; 1 __END__ =encoding utf-8 =head1 NAME mojocookiecheck - Prints out a Signed Cookie of Mojolicious =head1 SYNOPSIS mojocookiecheck.pl [OPTIONS] COOKIE_BODY [COOKIE_NAME SECRET] Options: -h --help print this help =head1 DESCRIPTION This is a cookie checker for Mojolicious that converts them from an opaque character string to something nicely readable. It also can check the HMAC.