KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility methods to encode blob to/decode from Base64URL format (v18R3 and older)
PRODUCT: 4D | VERSION: 18 | PLATFORM: Mac & Win
Published On: March 20, 2023

In v18R4, a third * parameter was introduced in the commands, BASE64 ENCODE and BASE64 DECODE; this parameter allows the developer to encode/decode Base64 text in Base64URL format, which is a derivative of the Base64 main format (you can read more about this format here: https://base64.guru/standards/base64url).

For 4D versions older than v18R4, there is no built-in function to handle Base64URL text; the following utility methods can be used to encode to/decode from Base64URL format.

Encode to Base64URL

// Encode to Base64URL method
// encodes $toDecode to Base64URL format and returns this value

// declare variables
C_BLOB($1; $blob)
C_TEXT($0; $base64; $base64URL)

// check that only 1 parameter is inputted
If (Count parameters=1)
  // assign input parameter to local variable
  $blob:=$1

  // encode to Base64 (main format)
  BASE64 ENCODE($blob; $base64)

  // translate from Base64 (main) to Base64URL
  $base64URL:=Replace string($base64; "+"; "-")
  $base64URL:=Replace string($base64URL; "/"; "_")
  $lastChar:=Substring($base64URL; Length($base64URL); 1)
  While ($lastChar="=") // remove padding characters ("=")
    $base64URL:=Substring($base64URL; 1; Length($base64URL)-1)
    $lastChar:=Substring($base64URL; Length($base64URL); 1)
  End while

  // return encoded Base64URL text
  $0:=$base64URL
End if


Decode From Base4URL
// Decode From Base64URL method
// decodes $base64URL from Base64URL format to a blob and returns this value

// declare variables
C_TEXT($1; $base64URL; $base64)
C_BLOB($0; $resultBlob)
C_LONGINT($length)

// check that only 1 parameter is inputted
If (Count parameters=1)
  // assign input parameter to local variable
  $base64URL:=$1
  
  // translate from Base64URL to Base64 (main)
  $base64:=Replace string($base64URL; "-"; "+")
  $base64:=Replace string($base64; "_"; "/")
  $length:=Length($base64)
  While (($length%4)#0) // add padding characters ("=")
    $base64:=$base64+"="
    $length:=Length($base64)
  End while
  
  // decode to plain text
  BASE64 DECODE($base64; $resultBlob)
  
  // return blob
  $0:=$resultBlob
End if


Examples
Example 1 - Encoding a string to Base64URL
$toEncodeText:="Hello, world! My name is John Doe."
TEXT TO BLOB($toEncodeText; $blob)
$base64URL:=encodeToBase64URL($blob)


Example 2 - Decoding from Base64URL back to string
$resultBlob:=decodeFromBase64URL($base64URL)
$resultText:=BLOB to text($resultBlob; UTF8 text without length)