From 08b2ba0ca7cc8a5cac9d0cb50eb9cb0edce4f245 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Fri, 18 Dec 2020 18:03:21 -0800 Subject: [PATCH] CRM_Utils_String - Add URL-style base64 codec --- CRM/Utils/String.php | 25 +++++++++++++++++++++++++ tests/phpunit/CRM/Utils/StringTest.php | 13 +++++++++++++ 2 files changed, 38 insertions(+) diff --git a/CRM/Utils/String.php b/CRM/Utils/String.php index 7c08974365..8e761a5be8 100644 --- a/CRM/Utils/String.php +++ b/CRM/Utils/String.php @@ -221,6 +221,31 @@ class CRM_Utils_String { } } + /** + * Encode string using URL-safe Base64. + * + * @param string $v + * + * @return string + * @see https://tools.ietf.org/html/rfc4648#section-5 + */ + public static function base64UrlEncode($v) { + return rtrim(str_replace(['+', '/'], ['-', '_'], base64_encode($v)), '='); + } + + /** + * Decode string using URL-safe Base64. + * + * @param string $v + * + * @return false|string + * @see https://tools.ietf.org/html/rfc4648#section-5 + */ + public static function base64UrlDecode($v) { + // PHP base64_decode() is already forgiving about padding ("="). + return base64_decode(str_replace(['-', '_'], ['+', '/'], $v)); + } + /** * Determine the string replacements for redaction. * on the basis of the regular expressions diff --git a/tests/phpunit/CRM/Utils/StringTest.php b/tests/phpunit/CRM/Utils/StringTest.php index be31cfa8d0..dcc461568c 100644 --- a/tests/phpunit/CRM/Utils/StringTest.php +++ b/tests/phpunit/CRM/Utils/StringTest.php @@ -10,6 +10,19 @@ class CRM_Utils_StringTest extends CiviUnitTestCase { parent::setUp(); } + public function testBase64Url() { + $examples = [ + 'a' => 'YQ', + 'ab' => 'YWI', + 'abc' => 'YWJj', + '3f>' => 'M2Y-', + ]; + foreach ($examples as $raw => $b64) { + $this->assertEquals($b64, CRM_Utils_String::base64UrlEncode($raw)); + $this->assertEquals($raw, CRM_Utils_String::base64UrlDecode($b64)); + } + } + public function testStripPathChars() { $testSet = [ '' => '', -- 2.25.1