Reputation: 31
How can I convert the specific code written in Delphi to JAVA?
Delphi code is encrypt code.
function Encrypt(const S: String; Key1, Key2, Key3: WORD): String;
var
i: Byte;
FirstResult: String;
begin
SetLength(FirstResult, Length(S));
for i:=1 to Length(S) do begin
FirstResult[i]:=Char(Byte(S[i]) xor (Key1 shr 8));
Key1 :=(Byte(FirstResult[i])+Key1)*Key2+Key3;
end;
Result:=ValueToHex(FirstResult);
end;
function ValueToHex(const S: String): String;
var i: Integer;
begin
SetLength(Result, Length(S)*2);
for i:=0 to Length(S)-1 do begin
Result[(i*2)+1]:=HexaChar[Integer(S[i+1]) shr 4];
Result[(i*2)+2]:=HexaChar[Integer(S[i+1]) and $0f];
end;
end;
so I was try to make source code. it's here
int key1=11; int key2=22; int key3=33;
String value = "ABCDE";
for(int i=0; i< value.length(); i++){
byte[] bValue = value.substring(i).getBytes();
int[] rValue = {0};
rValue[0] = bValue[0]^(key1>>8);
key1 = (bValue[0]+key1)*key2+key3;
System.out.print(ValueToHex(rValue));
}
But different results.
key1 = 11, key2 = 22, key3 = 33;
value : "ABCDE"
delphi encrypt : 4144DB69BF
java encrypt : 4144DB0901
Does not match
but
value : "ABC"
delphi encrypt : 4144DB
java encrypt : 4144DB
Is consistent
Why does not match the long?
Upvotes: 1
Views: 825
Reputation: 612954
There are two distinct errors.
Firstly, the updating of key1
must use rValue
rather than bValue
.
And secondly, the Delphi code performs arithmetic on key1
in the context of Word
which is a 2 byte unsigned integer. But the Java code performs the same calculations in the context of int
which is a 4 byte signed integer.
To fix this I believe you simply need to perform the arithmetic using 4 byte signed and then truncate key1
to a 2 byte value. Like this:
key1 = ((rValue[0]+key1)*key2+key3) & 0xffff;
I also think that you can simplify the Java code considerably. I know next to nothing about Java and so I'm sure a skilled Java expert could do very much better than this:
class SO15885898 {
private static String ValueToHex(int myInt)
{
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt & 0xff));
if (sb.length() < 2) {
sb.insert(0, '0'); // pad with leading zero if needed
}
return sb.toString();
}
public static void main(String[] args)
{
int key1=11;
int key2=22;
int key3=33;
String value = "ABCDE";
for(int i=0; i<value.length(); i++){
byte bValue = value.substring(i).getBytes()[0];
int rValue = bValue^(key1>>8);
key1 = ((rValue+key1)*key2+key3) & 0xffff;
System.out.print(ValueToHex(rValue));
}
}
}
Output:
4144db69bf
On a more general note, since you have both codes, you should arrange that both codes are as close to each other in organisation as possible. And then print off as much diagnostics as possible to pinpoint the calculation step where differences first appear.
Upvotes: 3