Atozed Forums
Need help implementing Base64Encode/DecodeBytes - Printable Version

+- Atozed Forums (https://www.atozed.com/forums)
+-- Forum: Indy (https://www.atozed.com/forums/forum-8.html)
+--- Forum: Indy General Discussion (https://www.atozed.com/forums/forum-9.html)
+--- Thread: Need help implementing Base64Encode/DecodeBytes (/thread-138.html)



Need help implementing Base64Encode/DecodeBytes - RaelB - 04-30-2018

Hello,

Can someone help me implement these functions (in Delphi XE4)


function Base64EncodeBytes(Input: TBytes): TBytes;
function Base64DecodeBytes(Input: TBytes): TBytes;

Could be using Indy or Soap.EncdDecd.

Thank you
Rael


RE: Need help implementing Base64Encode/DecodeBytes - rlebeau - 04-30-2018

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;
}



RE: Need help implementing Base64Encode/DecodeBytes - RaelB - 05-01-2018

Thanks!