Question

I need to convert this code into Delphi. But it's too complicated to handle...

Thanks...

String key = xorString("STACKOVERFLOWCOM", "ASDFQWERTYKMLYDR");

String xorString(String txt, String xor) {
  StringBuffer str = new StringBuffer();
  for( int i = 0; i < txt.length(); i++ ) {
    int ch = txt.charAt(i) ^ xor.charAt(i);
    char digit = getHexDigit((ch >> 4) & 0x0f);
    str.append(digit);
    digit = getHexDigit(ch & 0x0f);
    str.append(digit);
  } // for()
  return str.toString();
} // xorString()

char getHexDigit(int nibble) {
  if( nibble >= 0 && nibble <= 9 ) return (char)((int)'0' + nibble);

  return (char)((int)'A' + nibble - 10);
} // getHexDigit()
Was it helpful?

Solution

What this is doing is pretty straightforward, really. It's taking an input string and a key and XORing them together, then returning the result as a stream of hex digits. Here's the Delphi equivalent:

function xorString(txt, key: string): string;
var
  i: integer;
  ch: byte; //change to word for D2009+
  digit: string;
begin
  result := '';
  for i := 1 to length(txt) do
  begin
    ch := byte(txt[i]) xor byte(key[i]); //change byte to word for D2009+
    digit := IntToHex(ch, 2);
    result := result + digit;
  end;
end;

I didn't bother translating the GetHexDigit routine, since SysUtils.IntToHex performs the same function. Also, as Ulrichb pointed out, this requires a key string at least as long as the "txt" string. Otherwise, you'll get a range check error. (You are compiling with range checking on, right?)

EDIT: Not sure why the >> 4 and 0x0f bit is there when converting. I don't have a Java compiler handy, so it might just be a language issue, but it looks to me like this bitshifting will always produce results within 0..3 for alphabetical characters, and also make it impossible to reverse the process, which is usually the entire point of xor encryption. If you don't need to maintain compatibility with this Java algorithm, I'd replace the digit line with:

digit := intToHex(ch, 2);

which will give you a more correct and reversible result.

EDIT2: OK, it was a little too early in the morning to be doing heavy logic when I wrote that. I totally missed the fact that it was calling GetHexDigit twice. Fixed the algorithm.

OTHER TIPS

function XorString(TextStr, XorStr: string): string;
var
  I, Xored: Integer;
begin
  Assert(Length(TextStr) <= Length(XorStr));
  Result := '';

  for I := 1 to Length(TextStr) do
  begin
    Xored := Ord(TextStr[I]) xor Ord(XorStr[I]);
    Result := Result + IntToHex(Xored AND $FF, 2);
  end;
end;

Java version:

xorString("STACKOVERFLOWCOM", "ASDFQWERTYKMLYDR")
 => gives "120705051A181317061F07021B1A0B1F"

Delphi version:

XorString('STACKOVERFLOWCOM', 'ASDFQWERTYKMLYDR')
 => gives '120705051A181317061F07021B1A0B1F'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top