mmbasic:base64_mime_encode_and_decode_functions
Base64 Mime Encode and Decode Functions
Base 64 encoding is a method of passing binary data between systems that normally only accept “typeable” characters e.g. binary attachments to emails etc. It also provides a good method of obfuscating sensitive data although it is not encryption (it is easily decoded without a key).
B64Enc$() returns a Base64 encoded version of the original input string. Note: B64 encoded strings have a, roughly, 33% increase in size over the original. B64Dec$() decodes a Base64 string back to its original data.
Syntax:
a$=B64Enc$(expression) b$=B64Dec$(expression)
Example:
a$=B64Enc$(plain_text_password$) my_jpeg$=B64Dec$(email_attachment$) \\
Assumptions:
<code> OPTION BASE 0 CONST Mime$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"</code>
Code:
FUNCTION B64Enc$(x$) LOCAL INTEGER c1,c2,c3,w1,w2,w3,w4,n LOCAL STRING so$ FOR n=1 TO LEN(x$) STEP 3 c1=ASC(MID$(x$,n,1)): c2=ASC(MID$(x$,n+1,1)+CHR$(0)): c3=ASC(MID$(x$,n+2,1)+CHR$(0)): w1=INT(c1/4): w2=(c1 AND 3)*16+INT(c2/16) IF LEN(x$)>=n+1 THEN w3=(c2 AND 15)*4+INT(c3/64) ELSE w3=-1 IF LEN(x$)>=n+2 THEN w4=c3 AND 63 ELSE w4=-1 so$=so$+ME$(w1)+ME$(w2)+ME$(w3)+ME$(w4) NEXT B64Enc$=so$+"==" END FUNCTION FUNCTION B64Dec$(x$) LOCAL INTEGER w1,w2,w3,w4,n LOCAL STRING so$ FOR n=1 TO LEN(x$) STEP 4 w1=MD(MID$(x$,n,1)): w2=MD(MID$(x$,n+1,1)): w3=MD(MID$(x$,n+2,1)): w4=MD(MID$(x$,n+3,1)) IF w2>=0 THEN so$=so$+CHR$(((w1*4+INT(w2/16)) AND 255)) IF w3>=0 THEN so$=so$+CHR$(((w2*16+INT(w3/4)) AND 255)) IF w4>=0 THEN so$=so$+CHR$(((w3*64+w4) AND 255)) NEXT B64Dec$=so$ END FUNCTION ' support functions FUNCTION ME$(i) IF i>=0 THEN ME$=MID$(Mime$,i+1, 1) ELSE ME$="" END FUNCTION FUNCTION MD(x$) IF LEN(x$)=0 THEN MD=-1 ELSE MD=INSTR(Mime$,x$)-1 END FUNCTION
mmbasic/base64_mime_encode_and_decode_functions.txt · Last modified: 2024/02/24 22:06 by gerryuser