I am currently working on a TCP/IP New Desk Accessory (what else do I ever work on?) that requires “basic authentication”. Basic authentication is a really simple, very unsecure way of encoding a username and password. In essence, the username and password are joined together in a single string with a colon between the two:
username:password
and then encoded into Base64. As I’ve never tried to figure out how to encode into Base64 before, I decided this would be a nice exercise for my Pascal skills.
Working backwards, I can easily figure out what the end result of the encoding is supposed to be; there are many online Base64 encoding Web pages, so the string above would be encoded as:
dXNlcm5hbWU6cGFzc3dvcmQ=
How do we get there from here?
Wikipedia to the rescue! Wikipedia provides about as close to a plain English step by step on encoding a string as Base64.
First off, each character that needs conversion must be converted to its ASCII numeric equivalent. Well, actually, first, once we have the username:password string built–which are two p-strings combined to make a c-string; p-strings because that’s an easier way for me to get input from a IIgs LineEdit dialog, and a c-string because its longer length could be an advantage depending on how long the username and password are–we need to look at it character by character. So in order to do that, we take the assembled username:password string and use a loop to parse out the characters one by one:
Procedure CharParser; {parses out each character}
Var
username, password: pstring;
parsedchar: char;
rawauthstring, binauthstring: cstring;
ploop: integer;
begin
rawauthstring := concat(username, ':', password); {combine the username}
{and password with a }
{colon between them }
ploop := 1; {parsing loop--1 for 1st character}
While ploop <= length(rawauthstring) do begin
parsedchar := rawauthstring[ploop]; {sets parsedchar to the current}
{character as ploop increases }
ploop := ploop + 1; {increment ploop by a character}
end; {parsing loop}
end; {CharParser}
This procedure, while it will run right now, isn’t useful without a bit more code that we won’t get into yet. Basically as the ploop starts with the first character in rawauthstring and moves character by character through the string until it reaches its end, it assigns the character at the current position in the loop to the character value parsedchar, then moves onto the next character. In order for this procedure to be more useful, more has to be done with parsedchar, starting with converting from a character to an ASCII value, then converting the numeric ASCII value into a binary value, padding the length of the binary value so it’s eight digits long, and adding it to a progressively growing string of 0s and 1s for further conversion. We’ll tackle some of this next episode!