Indy has base64 encoder/decoder classes, TIdEncoderMIME and TIdDecoderMIME, for example:
Code:
uses
Classes, SysUtils, IdGlobal, IdCoderMIME;
type
TBytesStreamAccess = class(TBytesStream)
end;
function Base64EncodeBytes(Input: TBytes): TBytes;
type
PIdBytes = ^TIdBytes;
var
Strm: TBytesStream;
begin
Strm := TBytesStream.Create(nil);
try
TIdEncoderMIME.EncodeBytes(PIdBytes(@Input)^, Strm);
if TBytesStreamAccess(Strm).Capacity > Strm.Size then
Result := Copy(Strm.Bytes, 0, Strm.Size)
else
Result := Strm.Bytes;
finally
Strm.Free;
end;
end;
{ alternatively:
function Base64EncodeBytes(Input: TBytes): TBytes;
type
PIdBytes = ^TIdBytes;
PBytes = ^TBytes;
var
S: String;
Bytes: TIdBytes;
begin
S := TIdEncoderMIME.EncodeBytes(PIdBytes(@Input)^);
Bytes := IndyTextEncoding_ASCII.GetBytes(S);
Result := PBytes(@Bytes)^;
end;
}
function Base64DecodeBytes(Input: TBytes): TBytes;
var
InStrm, OutStrm: TBytesStream;
Decoder: TIdDecoderMIME;
begin
OutStrm := TBytesStream.Create(nil);
try
Decoder := TIdDecoderMIME.Create;
try
Decoder.DecodeBegin(OutStrm);
try
InStrm := TBytesStream.Create(Input);
try
Decoder.Decode(InStrm);
finally
InStrm.Free;
end;
finally
Decoder.DecodeEnd;
end;
finally
Decoder.Free;
end;
if TBytesStreamAccess(OutStrm).Capacity > OutStrm.Size then
Result := Copy(OutStrm.Bytes, 0, OutStrm.Size)
else
Result := OutStrm.Bytes;
finally
OutStrm.Free;
end;
end;
{ alternatively:
function Base64DecodeBytes(Input: TBytes): TBytes;
type
PIdBytes = ^TIdBytes;
PBytes = ^TBytes;
var
S: String;
Bytes: PIdBytes;
begin
S := IndyTextEncoding_ASCII.GetString(PIdBytes(@Input)^);
Bytes := TIdDecoderMIME.DecodeBytes(S);
Result := PBytes(@Bytes)^;
end;
}