Created
April 21, 2024 20:36
-
-
Save SalatielSauer/7fa15ed52cab6740720f7ba177c2fe1f to your computer and use it in GitHub Desktop.
CubeScript base64 encoder/decoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// base64 encoder/decoder, ported to cubescript by @SalatielSauer | |
// usage: /echo (base64 1 "Hello") // encode | |
// /echo (base64 0 "SGVsbG8") // decode | |
base64 = [ | |
local base64Chars base64CharAt encode decode isNaN | |
base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
base64CharAt = [substr $base64Chars $arg1 1] | |
isNaN = [! (codestr $arg1)] | |
encode = [ | |
local input output index charCodeAt | |
input = $arg2 | |
output = "" | |
index = 0 | |
charCodeAt = [ strcode (substr $input $arg1 1); index = (+ $index 1) ] | |
while [< $index (strlen $input)] [ | |
local byte1 byte2 byte3 enc1 enc2 enc3 enc4 | |
byte1 = (& (charCodeAt $index) 0xff) | |
byte2 = (? (< $index (strlen $input)) (& (charCodeAt $index) 0xff) 0) | |
byte3 = (? (< $index (strlen $input)) (& (charCodeAt $index) 0xff) 0) | |
enc1 = (>> $byte1 2) | |
enc2 = (| (<< (& $byte1 0x3) 4) (>> $byte2 4)) | |
enc3 = (| (<< (& $byte2 0xf) 2) (>> $byte3 6)) | |
enc4 = (& $byte3 0x3f) | |
if (isNaN $byte2) [ | |
enc3 = 64 | |
enc4 = 64 | |
] [ | |
if (isNaN $byte3) [ enc4 = 64 ] | |
] | |
output = (concatword $output (base64CharAt $enc1) (base64CharAt $enc2) (base64CharAt $enc3) (base64CharAt $enc4)) | |
] | |
result $output | |
] | |
decode = [ | |
local input output index charAt | |
input = $arg2 | |
output = "" | |
index = 0 | |
charAt = [ substr $input $arg1 1; index = (+ $index 1) ] | |
while [< $index (strlen $input)] [ | |
local enc1 enc2 enc3 enc4 byte1 byte2 byte3 | |
enc1 = (strstr $base64Chars (charAt $index)) | |
enc2 = (strstr $base64Chars (charAt $index)) | |
enc3 = (strstr $base64Chars (charAt $index)) | |
enc4 = (strstr $base64Chars (charAt $index)) | |
byte1 = (| (<< $enc1 2) (>> $enc2 4)) | |
byte2 = (| (<< (& $enc2 15) 4) (>> $enc3 2)) | |
byte3 = (| (<< (& $enc3 3) 6) $enc4) | |
output = (concatword $output (codestr $byte1)) | |
if (!= $enc3 64) [ output = (concatword $output (codestr $byte2)) ] | |
if (!= $enc4 64) [ output = (concatword $output (codestr $byte3)) ] | |
] | |
result $output | |
] | |
if (= $arg1 1) [ @encode ] [ @decode ] | |
] | |
_testbase64 = [ | |
local encode decode | |
encode = (base64 1 $arg1) | |
decode = (base64 0 $encode) | |
echo (format "^f0input: ^f8%1^n^f0base64: ^f8%2" $decode $encode) | |
] | |
//_testbase64 "Hello Sauer!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment