27 May 2010

Decoding Base 64 encoded data

A while ago someone asked me how to go about decoding Base 64 encoded code in a single routine.

Here's what I came up with. It uses the Indy internet component suite to do the grunt work and simply wraps the various Indy calls into a function.

uses
  Classes, IdCoderMIME

...

function Base64Decode(const EncodedText: string): TBytes;
var
  DecodedStm: TBytesStream; 
  Decoder: TIdDecoderMIME;  
begin
  Decoder := TIdDecoderMIME.Create(nil);
  try
    DecodedStm := TBytesStream.Create;
    try
      Decoder.DecodeBegin(DecodedStm);
      Decoder.Decode(EncodedText);
      Decoder.DecodeEnd;
      Result := DecodedStm.Bytes;
    finally
      DecodedStm.Free;
    end;
  finally
    Decoder.Free;
  end;
end;

This function decodes the encoded text passed in EncodedText, which must contain only valid Base 64 encoding characters, and returns the resulting raw data as an array of bytes.

We use Indy's TIdDecoderMIME component to decode the text into a TByteStream and read of the result from the stream's Bytes property.

No comments: