Search code examples
godelphipascal

delphi/pascal <> golang (XOR encryption)


I'm working with an old algorithm writen in delphi allowing to encrypt/decrypt messages via xor.

I am totally new with delphi and I would like to rewrite this little algorithm in golang, unfortunately I have some difficulty with xor.

For example, this code in delphi :

message:=Char(51) + Char(45) + Char(211) + Char(94) + Char(95) + Char(73) + Char(70);
j:=Byte(message[1]) xor 33;

return 18.

But this one is Golang return 12 :

message:=[]byte{51, 45, 211, 94, 95, 73, 70}
j:=int(message[1]) ^ 33

Here is the "complete" program in delphi :

program Test;
var
  i,j,k,l : integer;
  spec : boolean;
  ERREUR_JOY : array[0..255] of char;
  Texte : String;
begin
  ERREUR_JOY :=#182#88#135#157#49#18#172#73#47#76#243#72#132#102#33#161#227#40#114#157#95#47#163#105#239#226#60#154#77#223#35#146#189#224#77#0#28#207#117#19#4#123#98#77#205#226#67#186#55#110#8#38#39#43#197#133#164#28#171#211#164#60#196#249#8#135#231#79#70#108#124#39#162#67#171#90#158#207#164#159#32#2#145#48#176#14#155#28#177#30#62#77#56#234#118#24#25#225#207#167#132#228#73#6#228#168#106#44#5#82#97#159#156#176#169#124#44#118#168#173#36#237#99#39#34#119#13#0#226#135#59#244#207#0#224#188#133#48#110#207#169#186#141#37#24#82#167#163#215#188#0#95#221#14#211#215#38#140#97#224#192#246#29#248#72#34#216#245#31#195#211#175#234#156#76#163#79#154#164#18#49#233#40#217#184#94#144#59#170#22#88#14#103#175#53#71#42#113#67#236#48#208#0#129#194#182#188#176#112#69#129#248#187#188#58#103#99#70#212#103#192#40#212#205#238#30#7#64#214#200#172#111#32#50#137#80#203#1#13#236#11#239#222#122#59#166#202#216#115#148#44#212#25#22#195;
  Texte:=Char(51) + Char(45) + Char(211) + Char(94) + Char(95) + Char(73) + Char(70);
  
  begin
    j:=Byte(Texte[1]) xor 33;
    WriteLn(j);
    l:=j;
    k:=Byte(Texte[length(Texte)]) xor 66;
    spec:=(Texte[1]=#255);
    for i:=2 to length(Texte)-1 do
    begin
      
      if (spec) then
      begin
        spec:=false;
      end
      else
      begin
        spec:=(Texte[i]=#255);
        WriteLn(Texte);
        Texte[i]:=Char(Byte(Texte[i]) xor Byte(ERREUR_JOY[j]) xor l);
      end;
      j:=j+k;
      l:=l-k+3;
      if (j>=length(ERREUR_JOY)) then j:=1;
      if (l<1) then l:=j;
    end;
    WriteLn(copy(texte,2,length(texte)-2));
  end
end.

Can someone help me ? thank you.


Solution

  • Delphi uses 1 based string indexing and GoLang 0 based array indexing.

    Your Delphi code looks at the first character:

    j:=Byte(message[1]) xor 33;
    

    While in GoLang this looks at the second character/byte.

    j:=int(message[1]) ^ 33
    

    Note that in newer versions of Delphi byte and char are not interchangeable so this code would break be fragile.