Skip to content

Instantly share code, notes, and snippets.

@lukem512
Last active March 20, 2025 15:34
Show Gist options
  • Save lukem512/efefa4c0cd24d86c9a71711c6be7832d to your computer and use it in GitHub Desktop.
Save lukem512/efefa4c0cd24d86c9a71711c6be7832d to your computer and use it in GitHub Desktop.
Base64 and base64url encoding methods for Verj.io (RhinoJS)
// Encode a string using base64
function __encodeBase64(val) {
const bytes = java.lang.String(val).getBytes();
return services.file.base64Encode(bytes);
}
// Decode a base64-encoded string
function __decodeBase64(val) {
const bytes = services.file.base64Decode(val);
return java.lang.String(bytes).toString();
}
// Encode a string using base64url
function __encodeBase64url(val) {
return __base64ToBase64url(__encodeBase64(val));
}
// Decode a base64url-encoded string
function __decodeBase64url(val) {
return __decodeBase64(__base64urlToBase64(val));
}
// Convert a base64-encoded string to use base64url
// This process involves replacing '+' character with '-',
// replacing '/' with '_' and removing trailing '=' padding
function __base64ToBase64url(val) {
return val.replace(/\+/g, '-').replace(/\//g, '_').split('=')[0];
}
// Convert a base64url-encoded string to use base64
// This process performs the inverse of __base64ToBase64url
// and, additionally, pads the string with '=' characters to ensure the
// length is a multiple of 4
function __base64urlToBase64(val) {
const bval = val.replace(/-/g, '+').replace(/_/g, '/');
return bval.padEnd(bval.length % 4, '=');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment