#!/usr/bin/perl

# Key: d6c60c8e688e0afa7f49416897aadc1f
# Encryption method: AES-128-ECB

# Note: Pre-treatment of the base64 string may be necessary to make it usable by some base64 decoding methods.
#   - All occurrences of "-" (minus) must be changed to "+" (plus)
#   - All occurrences of "_" (underscore) must be changed to "/" (slash)
#   - All occurrences of "%20%20" must be removed or converted to carriage return + linefeed or just linefeed.
#   - The length of the string, after whitespace has been removed, must be evenly divisible by 4. If it is not,
#     add one or two "=" (equals) characters to make it evenly divisible by 4.

use strict;
use Crypt::Rijndael;
use MIME::Base64;

my $key = 'd6c60c8e688e0afa7f49416897aadc1f'; # 128-bit/16-byte key, represented as series of sixteen hex doubles
my $BS = 16; # Block size for PKCS#7

my $atdataEqsValue = 'AeZFhZnm_ytYdj06wE5ikO4vPv302-SG9Osx_itiNbxF4gIY3CHdBpvpxd6Jaxvx%20%207i8-_fTb5Ib06zH-K2I1vEXiAhjcId0Gm-nF3olrG_HuLz799NvkhvTrMf4rYjW8%20%20rJmJDtsRTiTCWYfZfF6SDcHuTfwpOhubzIEAFNIeJRoOtRe-zev31MASpLRr2A_g%20%20wGPEJDvSZnokppAKPaWe2w';
print "URL-friendly EQS: $atdataEqsValue\n";

my $b64CipherText = standardizeBase64($atdataEqsValue);
print "Standardized B64: $b64CipherText\n";

my $encryptedBinary = decode_base64($b64CipherText);
my $binaryKey = pack('H*', $key);
my $cipherObject = Crypt::Rijndael->new($binaryKey, Crypt::Rijndael::MODE_ECB()); # AES means 16-byte block size
#$cipherObject->set_iv($iv) # Not executed -- ECB does not use an initialization vector.
my $clearText  = $cipherObject->decrypt($encryptedBinary);
$clearText = fixPKCS7($clearText); # Rijndael probably has a padding thing, but we're doing it manually
print "Clear text: $clearText\n";

sub standardizeBase64 {
  my $nonstandardBase64 = shift;
  $nonstandardBase64 =~ s/\-/+/g;
  $nonstandardBase64 =~ s/_/\//g;
  $nonstandardBase64 =~ s/\%20\%20//g;
  $nonstandardBase64 .= '=' x ((4 - (length($nonstandardBase64) % 4)) % 4);
  return $nonstandardBase64;
}

sub fixPKCS7 {
  my $string = shift;
  my $lastChar = substr($string, -1);
  my $lastCharOrd = ord($lastChar);
  if (($lastCharOrd >= 1) and ($lastCharOrd <= $BS)) {
    my $possiblePadding = substr($string, (-1 * $lastCharOrd));
    my $possiblePaddingMatch = $lastChar x $lastCharOrd;
    if ($possiblePadding eq $possiblePaddingMatch) {
      substr($string, (-1 * $lastCharOrd)) = '';
    }
  }
  return $string;
}
