Java Reference
In-Depth Information
String encode = base64Encode(hdr);
http.addRequestProperty("Authorization", "Basic " + encode);
Of course, it would be a bad idea to send the password as plain text. So both the user id
and password are encoded into base-64. It is very easy to encode/decode from base-64, so
this is not a very strong security system. However, it does keep someone casually examining
packets from determining the password.
When HTTP Authentication is combined with HTTPS, it is quite effective. HTTP Au-
thentication requires an id and password, and HTTPS encrypts the entire packet, password
included, thus preventing someone from examining the password. Base-64 is just another
number system, like decimal (base 10) or hexadecimal (base 16). To convert to base-64, this
program uses the function base64Encode . This method will now be examined.
The base64Encode method begins by creating a ByteArrayOutputStream
that holds the base-64 encoded data.
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Next, a Base64OutputStream class is created. This recipe also provides
this class. The Base64OutputStream class receives an output stream argument
to which it writes the base-64 encoded data. You then call the write method of the
Base64OutputStream object, and give it the data you want encoded. This is shown
below:
Base64OutputStream out = new Base64OutputStream(bout);
try
{
out.write(s.getBytes());
out.flush();
As you can see, the above lines of code create the Base64OutputStream object,
and then write the string to it. The stream is then flushed, ensuring all data is encoded and is
not being buffered.
It is unlikely that an exception will occur, since this is a completely “in memory” opera-
tion. However, if an exception does occur, the following line of code will catch it:
} catch (IOException e)
{
}
Finally, we return the converted base-64 string.
return bout.toString();
Search WWH ::




Custom Search