Base64 encoding

Connecting to the REST service on a Datacentre requires Authorization headers that need to be base64 encoded. As of v7.1.3 there is no built-in intrinsic function to do base64 encoding, so here's a utility routine to do it in MWScript

constant meta = "Script by Cognito Software. http://cognito.co.nz"

/***
 *	Base64Encode
 *
 *	Encodes the UTF-8 bytes of the given string in base64
 ***/

constant b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
	
on Base64Encode(s)
	let s_hex = HexEncode(s)	// get utf-8 encoding as hex
	let r = ""
	let p = ""
	let l = Length(s_hex) / 2
	let f = Mod(l, 3)
	
	if f > 0	// padding
		while f < 3
			let p = p + "="
			let s_hex = s_hex + "00"
			let f = f + 1
		endwhile
	endif
	foreach c in (1, l * 2, 6)
		let n = Val("#" + Mid(s_hex, c, 2)) * #10000 + Val("#" + Mid(s_hex, c + 2, 2)) * #100 + Val("#" + Mid(s_hex, c + 4, 2))
		let n1 = TestFlags(n / #40000, 63)
		let n2 = TestFlags(n / #1000, 63)
		let n3 = TestFlags(n / #40, 63)
		let n4 = TestFlags(n, 63)		
		let r = r + Mid(b64, n1 + 1, 1) + Mid(b64, n2 + 1, 1) + Mid(b64, n3 + 1, 1) + Mid(b64, n4 + 1, 1) 
	endfor
	return Left(r, Length(r) - Length(p)) + p
end
Posted in MWScript, Sample Code | Comments Off on Base64 encoding