EnableExplicit
; -------------------------------------------------------------------------------------------------
Procedure.s Base64Encode(Text.s)
Protected base64chars.s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", i.i,
encodedstr.s = "", paddingstr.s = "", three_byte_number.i, n1.i, n2.i, n3.i, n4.i,
padcount = Len(Text) % 3
; right pad to make the length of the incoming string a multiple of 3
If (padcount > 0)
paddingstr = Left("==", 3 - padcount)
Text + Left(Chr(0) + Chr(0), 3 - padcount)
EndIf
; iterate over the length of the incoming string, three characters at a time
For i = 1 To Len(Text) Step 3
; these three 8-bit (ASCII) characters become one 24-bit number
three_byte_number = Asc(Mid(Text, i, 1)) << 16 + Asc(Mid(Text, i + 1, 1)) << 8 + Asc(Mid(Text, i + 2, 1))
; this 24-bit number then gets split into four 6-bit numbers
n1 = 1 + (three_byte_number >> 18) & 63
n2 = 1 + (three_byte_number >> 12) & 63
n3 = 1 + (three_byte_number >> 6) & 63
n4 = 1 + (three_byte_number) & 63
; those four 6-bit numbers are used as indices into the base64 character list
encodedstr + Mid(base64chars, n1, 1) + Mid(base64chars, n2, 1) + Mid(base64chars, n3, 1) + Mid(base64chars, n4, 1)
; need newlines after every 76 output characters, according to MIME RFC 2045
If ((i * 4) / 3) % 76 = 0
encodedstr + Chr(13) + Chr(10)
EndIf
Next
ProcedureReturn Mid(encodedstr, 0, Len(encodedstr) - Len(paddingstr)) + paddingstr ; RFC 2045: trailing CR/LF ?
EndProcedure
Procedure.s BasicAuth(Username.s, Password.s)
ProcedureReturn "Basic " + Base64Encode(Username + ":" + Password)
EndProcedure
; Test cases - verified against base64encode.org results
Debug Base64Encode("Show me the cow") ; should return 'U2hvdyBtZSB0aGUgY293'
Debug Base64Encode("Send money & cigarettes") ; should return 'U2VuZCBtb25leSAmIGNpZ2FyZXR0ZXM='
Debug BasicAuth("test", "password") ; should return 'dGVzdDpwYXNzd29yZA==''
Last edited by kpeters58 on Thu Dec 20, 2018 8:32 pm, edited 1 time in total.