C# .NET SSO Convert to PHP : UrlTokenDecode(), UrlTokenEncode(), PBKDF2

While implementing Absorb SSO into a Drupal CANVAS site, I needed to generate a key from a URL $_GET token variable which is generated by Absorb's proprietary SSO. When a user is directed to https://yourabsorbsite.myabsorb.com/account/externallogin, Absorb sends them back to your standard domain with a login token. For example, https://mydomain.com?token=MqsXexqpYRUNAH...

The documentation only showed how to accomplish this C#.

C# example

string idAndKey = "bob@company.com" + "7MpszrQpO95p7H";
byte[] salt = UrlTokenDecode("MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2");
string key = UrlTokenEncode(PBKDF2(idAndKey, salt));
// key = “aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0”;

The key pieces of the conversion are:
-Two helper functions: convertFromUrlTokenFormat(),convertToUrlTokenFormat()
-PHP functions: base64_decode(), base64_encode(), hash_pbkdf2()

PHP Conversion

$idandKey = "bob@company.com" . "7MpszrQpO95p7H";
$salt = convertFromUrlTokenFormat("MqsXexqpYRUNAHR_lHkPRic1g1BYhH6bFNVPagEkuaL8Mf80l_tOirhThQYIbfWYErgu4bDwl-7brVhXTWnJNQ2");
$hash = hash_pbkdf2("sha1", $idandKey, base64_decode($salt), 1000, 24, true);
$key = convertToUrlTokenFormat(base64_encode($hash));
// key = “aE1k9-djZ66WbUATqdHbWyJzskMI5ABS0”;
 
 
function convertToUrlTokenFormat($val){
  $padding = substr_count($val, '=');
  $val = str_replace('=', '', $val);
  $val .= $padding;
  $val = str_replace('+', '-', str_replace('/', '_', $val));
 
  return $val;
}
 
 
function convertFromUrlTokenFormat($val){
  $val = str_replace('-', '+', str_replace('_', '/', $val));
  $lastCharacter = substr($val, -1);
  $val = substr($val, 0, -1);
  switch($lastCharacter){
      case 1:
          $val = $val . "=";
          break;
      case 2:
          $val = $val . "==";
          break;
  }
 
  return $val;
}