Base64 Encoding in Racket

Our program demonstrates base64 encoding and decoding. Here’s the full source code:

#lang racket

(require openssl/base64)

(define (main)
  ; Here's the string we'll encode/decode.
  (define data "abc123!?$*&()'-=@~")
  
  ; Racket supports both standard and URL-compatible base64.
  ; Here's how to encode using the standard encoder.
  (define sEnc (base64-encode (string->bytes/utf-8 data)))
  (displayln sEnc)
  
  ; Decoding may return an error, which you can check
  ; if you don't already know the input to be well-formed.
  (define sDec (bytes->string/utf-8 (base64-decode sEnc)))
  (displayln sDec)
  (newline)
  
  ; This encodes/decodes using a URL-compatible base64 format.
  (define uEnc (base64-encode-uri (string->bytes/utf-8 data)))
  (displayln uEnc)
  (define uDec (bytes->string/utf-8 (base64-decode-uri uEnc)))
  (displayln uDec))

(main)

In Racket, we use the openssl/base64 library for base64 encoding and decoding. This library provides functions for both standard and URL-compatible base64 operations.

To run the program, save it as base64-encoding.rkt and use the racket command:

$ racket base64-encoding.rkt
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

In Racket, we use string->bytes/utf-8 to convert strings to byte strings before encoding, and bytes->string/utf-8 to convert byte strings back to strings after decoding. The base64-encode and base64-decode functions are used for standard base64, while base64-encode-uri and base64-decode-uri are used for URL-compatible base64.