Hwau
Hwau

Reputation: 880

Encode base64 and Decode base64 using delphi 2007

I have to encode an array of bytes to a base64 string (and decode this string) on an old Delphi 2007. How could I do?

Further Informations:

I've tried synapse (As suggested here Binary to Base64 (Delphi)).

Upvotes: 5

Views: 40989

Answers (6)

Remy Lebeau
Remy Lebeau

Reputation: 597906

Indy ships with Delphi, and has TIdEncoderMIME and TIdDecoderMIME classes for handling base64. For example:

uses
  ..., IdCoder, IdCoderMIME;

var
  Bytes: TIdBytes;
  Base64String: String;
begin
  //...
  Bytes := ...; // array of bytes
  //...
  Base64String := TIdEncoderMIME.EncodeBytes(Bytes);
  //...
  Bytes := TIdDecoderMIME.DecodeBytes(Base64String);
  //...
end;

There are also methods for encoding/decoding String and TStream data as well.

Update: alternatively, if your version does not have the class methods shown above:

// TBytesStream was added in D2009, so define it manually for D2007

uses
  ..., IdCoder, IdCoderMIME
  {$IF RTLVersion < 20}
  , RTLConsts
  {$IFEND}
  ;

{$IF RTLVersion < 20}
type
  TBytesStream = class(TMemoryStream)
  private
    FBytes: TBytes;
  protected
    function Realloc(var NewCapacity: Longint): Pointer; override;
  public
    constructor Create(const ABytes: TBytes); overload;
    property Bytes: TBytes read FBytes;
  end;

constructor TBytesStream.Create(const ABytes: TBytes);
begin
  inherited Create;
  FBytes := ABytes;
  SetPointer(Pointer(FBytes), Length(FBytes));
  FCapacity := FSize;
end;

const
  MemoryDelta = $2000; // Must be a power of 2

function TBytesStream.Realloc(var NewCapacity: Integer): Pointer;
begin
  if (NewCapacity > 0) and (NewCapacity <> FSize) then
    NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
  Result := Pointer(FBytes);
  if NewCapacity <> FCapacity then
  begin
    SetLength(FBytes, NewCapacity);
    Result := Pointer(FBytes);
    if NewCapacity = 0 then
      Exit;
    if Result = nil then raise EStreamError.CreateRes(@SMemoryStreamError);
  end;
end;
{$IFEND}

var
  Bytes: TBytes;
  BStrm: TBytesStream;
  Encoder: TIdEncoderMIME;
  Decoder: TIdDecoderMIME;
  Base64String: String;
begin
  //...
  Bytes := ...; // array of bytes
  //...
  BStrm := TBytesStream.Create(Bytes);
  try
    Encoder := TIdEncoderMIME.Create;
    try
      Base64String := Encoder.Encode(BStrm);
    finally
      Encoder.Free;
    end;
  finally
    BStrm.Free;
  end;
  //...
  BStrm := TBytesStream.Create;
  try
    Decoder := TIdDecoderMIME.Create;
    try
      Decoder.DecodeBegin(BStrm);
      Decoder.Decode(Base64String);
      Decoder.DecodeEnd;
    finally
      Decoder.Free;
    end;
    Bytes := BStrm.Bytes;
  finally
    BStrm.Free;
  end;
  //...
end;

Upvotes: 11

Valient Newman
Valient Newman

Reputation: 1

The TBytesStream class given by Remy Lebeau is erratic and will not be compiled.

Even the compiler directive {$IF RTLVersion < 20) was written with mistake, the compiler directive begins with "{" and ends with "}" not ")"!

Here is my code, checked in IDE and can be compiled.

unit BytesStream;
// My Github Repository <https://github.com/valient-newman>
// CompilerVersion is 18.5 for Delphi 2007 Win32

interface

{$IF CompilerVersion = 18.5}
uses
   Classes, SysUtils, RTLConsts;
{$IFEND}

// This code was taken from unit System.Classes of Delphi 10.4.2 and remade
{$IF CompilerVersion = 18.5}
type
  TBytesStream = class(TMemoryStream)
  private
    FBytes: TBytes;
    FCapacity: Longint;
    FSize: Longint;
  protected
    function Realloc(var NewCapacity: Longint): Pointer; override;
  public
    constructor Create(const ABytes: TBytes); overload;
    property Bytes: TBytes read FBytes;
  end;
{$IFEND}

implementation
{$IF CompilerVersion = 18.5}
const
  MemoryDelta = $2000; // Must be a power of 2
{$IFEND}

// This code was taken from unit System.Classes of Delphi 10.4.2
{$IF CompilerVersion = 18.5}
constructor TBytesStream.Create(const ABytes: TBytes);
begin
  inherited Create;
  FBytes := ABytes;
  SetPointer(Pointer(FBytes), Length(FBytes));
  FCapacity := FSize;
end;

function TBytesStream.Realloc(var NewCapacity: Integer): Pointer;
begin
  if (NewCapacity > 0) and (NewCapacity <> FSize) then
    NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
  Result := Pointer(FBytes);
  if NewCapacity <> FCapacity then
  begin
    SetLength(FBytes, NewCapacity);
    Result := Pointer(FBytes);
    if NewCapacity = 0 then
      Exit;
    if Result = nil then raise EStreamError.CreateRes(@SMemoryStreamError);
  end;
end;
{$IFEND}

end.

Upvotes: 0

Marlon Nardi
Marlon Nardi

Reputation: 74

For OLDER versions of Delphi (before of Delphi XE7), use:

uses 
Soap.EncdDecd
procedure DecodeFile(const Base64: AnsiString; const FileName: string);
var
  BStream: TBytesStream;
begin
  BStream := TBytesStream.Create(DecodeBase64(Base64));
  try
    BStream.SaveToFile(Filename);
  finally
    BStream.Free;
  end;
end;

For NEWS versions of Delphi, use:

uses
System.NetEncoding;
procedure DecodeFile(const Base64: String; const FileName: string);
var
  BStream: TBytesStream;
begin
  BStream:= TBytesStream.Create(TNetEncoding.Base64.DecodeStringToBytes(Base64));
  try
    BStream.SaveToFile(Filename);
  finally
    BStream.Free;
  end;
end;

Upvotes: 1

David Heffernan responded very well!

Add in your uses the class "EncdDecd", it will have the procedures:

function DecodeString (const Input: string): string;
function DecodeBase64 (const Input: string): TBytes;

Testing with https://www.base64encode.org/

The String "Working" in both Delphi and the site resulted in: "V29ya2luZw =="

ShowMessage ('Working =' + EncodeString ('Working'));
ShowMessage ('Working =' + DecodeString ('V29ya2luZw =='));

Upvotes: 5

Dejan Dozet
Dejan Dozet

Reputation: 1019

Here goes EncodeToBase64:

uses
classes, sysutils;

function EncodeToBase64(var Buffer: TBytes): Longint;
const
  EncodingTable: PChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var
  WriteBuf: array[0..3] of Byte;
  Buf: array[0..2] of Byte;
  Dest: TMemoryStream;
  i, j, Count: Integer;
begin
  Result := 0;

  Count := Length(Buffer);
  j := Count div 3;

  if j > 0 then
  begin
    Dest:= TMemoryStream.Create();  
    try
      Dest.Position := 0;
      for i := 0 to j - 1  do
      begin
        Move(Buffer[i * 3], Buf[0], 3); 
        WriteBuf[0] := Ord(EncodingTable[Buf[0] shr 2]);
        WriteBuf[1] := Ord(EncodingTable[(Buf[0] and 3) shl 4 or (Buf[1] shr 4)]);
        WriteBuf[2] := Ord(EncodingTable[(Buf[1] and 15) shl 2 or (Buf[2] shr 6)]);
        WriteBuf[3] := Ord(EncodingTable[Buf[2] and 63]);  
        Dest.Write(WriteBuf, 4);  
        Inc(Result, 4);
        Dec(Count, 3);    
      end;          

      if Count in [1, 2] then  
      begin           
        Move(Buffer[i * 3], Buf[0], Count);
        WriteBuf[0] := Ord(EncodingTable[Buf[0] shr 2]);
        WriteBuf[1] := Ord(EncodingTable[(Buf[0] and 3) shl 4 or (Buf[1] shr 4)]); 
        if Count = 1 then
          WriteBuf[2] := Ord('=')
        else                                           
          WriteBuf[2] := Ord(EncodingTable[(Buf[1] and 15) shl 2 or (Buf[2] shr 6)]);
        WriteBuf[3] := Ord('='); 
        Dest.Write(WriteBuf, 4);  
        Inc(Result, 4);
        Dec(Count, Count);
      end;

      if Result > 0 then
      begin
        SetLength(Buffer, Result);
        Dest.Position := 0;
        Dest.Read(Buffer[0], Result);   
      end;  
    finally
      Dest.Free;
    end;
  end;

end; 

And this should work without any special units or components.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613422

Contrary to what you state in the question, the EncdDecd unit is included in Delphi 2007. You can simply use that.

Upvotes: 7

Related Questions