Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in delphi to base64 encode a string without CRLF? [duplicate]

Tags:

delphi

Is there a function in delphi to base64 encode a string without CRLF? I try TnetEncoding.Base64.Encode(MyStr) but the result string contain CRLF (linebreak)

like image 775
zeus Avatar asked Jan 20 '18 11:01

zeus


2 Answers

Yes, there is: TBase64Encoding constructed with specific parameters. There are three different constructor overloads. Default TNetEncoding.Base64 instance is constructed with default one. With other two constructors you can specify how many characters will be per line as well as line separator.

constructor Create; overload; virtual;
constructor Create(CharsPerLine: Integer); overload; virtual;
constructor Create(CharsPerLine: Integer; LineSeparator: string); overload; virtual;

If you specify empty string as new line delimiter, result will not have new line characters.

var
  s, Encoded: string;
  Base64: TBase64Encoding;

  s := 'Some larger text that needs to be encoded in Base64 encoding';
  Base64 := TBase64Encoding.Create(10, '');
  Encoded := Base64.Encode(s);

Output:

U29tZSBsYXJnZXIgdGV4dCB0aGF0IG5lZWRzIHRvIGJlIGVuY29kZWQgaW4gQmFzZTY0IGVuY29kaW5n

There is a better solution for no breaks at all provided in David's answer

Using second constructor and passing 0 as parameter omits line breaks.

Base64 := TBase64Encoding.Create(0);
like image 112
Dalija Prasnikar Avatar answered Oct 27 '22 18:10

Dalija Prasnikar


You can write your own function for this. It's really simple:

function EncodeBase64(const Input: TBytes): string;
const
  Base64: array[0..63] of Char =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

  function Encode3Bytes(const Byte1, Byte2, Byte3: Byte): string;
  begin
    Result := Base64[Byte1 shr 2]
      + Base64[((Byte1 shl 4) or (Byte2 shr 4)) and $3F]
      + Base64[((Byte2 shl 2) or (Byte3 shr 6)) and $3F]
      + Base64[Byte3 and $3F];
  end;

  function EncodeLast2Bytes(const Byte1, Byte2: Byte): string;
  begin
    Result := Base64[Byte1 shr 2]
      + Base64[((Byte1 shl 4) or (Byte2 shr 4)) and $3F]
      + Base64[(Byte2 shl 2) and $3F] + '=';
  end;

  function EncodeLast1Byte(const Byte1: Byte): string;
  begin
    Result := Base64[Byte1 shr 2]
      + Base64[(Byte1 shl 4) and $3F] + '==';
  end;

var
  i, iLength: Integer;
begin
  Result := '';
  iLength := Length(Input);
  i := 0;
  while i < iLength do
  begin
    case iLength - i of
      3..MaxInt:
        Result := Result + Encode3Bytes(Input[i], Input[i+1], Input[i+2]);
      2:
        Result := Result + EncodeLast2Bytes(Input[i], Input[i+1]);
      1:
        Result := Result + EncodeLast1Byte(Input[i]);
    end;
    Inc(i, 3);
  end;
end;

Using with a string:

EncodeBase64(BytesOf(MyStr));
like image 22
kot-da-vinci Avatar answered Oct 27 '22 18:10

kot-da-vinci