unit TEAU;
interface
type
PInteger = ^Integer;
TTEAEncryptor = class(TObject)
private
class procedure Encode(V,K
Integer);
class procedure Decode(V,K
Integer);
public
class procedure
EncodeBuffer(Buffer
ointer;BufLen:Integ
er;Key:String);
class procedure
DecodeBuffer(Buffer
ointer;BufLen:Integ
er;Key:String);
class function EncodeString(Value,Key:String):String;
class function DecodeString(Value,Key:String):String;
end;
implementation
{TTEAEncryptor}
// TEA encode a 64bit text with a 128bit key
// 64bit text in 2 32bit integers
// 128bit key in 4 32bit integers
class procedure TTEAEncryptor.Encode(V,K
Integer);
var
Y,Z:Integer;
A,B,C,D:Integer;
N:Integer;
Delta:Integer;
Sum:Integer;
begin
Delta:=$9e3779b9;
Sum:=0;
Y:=V^; Inc(V); Z:=V^; Dec(V);
A:=K^; Inc(K); B:=K^; Inc(K); C:=K^; Inc(K); D:=K^;
N:=32;
while N > 0 do
begin
Inc(Sum,delta);
Inc(Y,(Z shl 4)+A XOR Z+Sum XOR (Z Shr 5)+B);
Inc(Z,(Y shl 4)+C XOR Y+Sum XOR (Y Shr 5)+D);
Dec(N);
end;
V^:=Y; Inc(V); V^:=Z;
end;
// TEA decode a 64bit text with a 128bit key
// 64bit text in 2 32bit integers
// 128bit key in 4 32bit integers
class procedure TTEAEncryptor.Decode(V,K
Integer);
var
Y,Z:Integer;
A,B,C,D:Integer;
N:Integer;
Delta:Integer;
Sum:Integer;
begin
Delta:=$9e3779b9;
Sum:=Delta Shl 5 ;
Y:=V^; Inc(V); Z:=V^; Dec(V);
A:=K^; Inc(K); B:=K^; Inc(K); C:=K^; Inc(K); D:=K^;
N:=32;
while N > 0 do
begin
Dec(Z,(Y shl 4)+C XOR Y+Sum XOR (Y Shr 5)+D);
Dec(Y,(Z shl 4)+A XOR Z+Sum XOR (Z Shr 5)+B);
Dec(Sum,delta);
Dec(N);
end;
V^:=Y; Inc(V); V^:=Z;
end;
// Buffer pointer to 32 bit integers must be 64bit aligned
// BufLen = number of 32 bit integers
// key must be 128 bits (16 chars)
class procedure TTEAEncryptor. EncodeBuffer(Buffer
ointer;BufLen:Integ
er;Key:String);
var
Ptr
Integer;
begin
Ptr:=Buffer;
BufLen:=((BufLen+1) div 2);
while BufLen > 0 do
begin
Encode(Ptr,PInteger(PChar(Key)));
Inc(Ptr,2);
Dec(BufLen);
end;
end;
// Buffer pointer to 32 bit integers must be 64bit aligned
// BufLen = number of 32 bit integers
// key must be 128 bits (16 chars)
class procedure TTEAEncryptor. DecodeBuffer(Buffer
ointer;BufLen:Integ
er;Key:String);
var
Ptr
Integer;
begin
Ptr:=Buffer;
BufLen:=((BufLen+1) div 2);
while BufLen > 0 do
begin
Decode(Ptr,PInteger(PChar(Key)));
Inc(Ptr,2);
Dec(BufLen);
end;
end;
class function TTEAEncryptor.EncodeString(Value,Key:String):String;
begin
// pad key to 128 bits
while Length(Key) < 16 do Key:=Key+#$A5;
// pad Value to next 64 bit boundary
while (Length(Value) mod 8) <> 0 do Value:=Value+#0;
EncodeBuffer(PChar(Value),Length(Value) div 4,Key);
Result:=Value;
end;
class function TTEAEncryptor.DecodeString(Value,Key:String):String;
begin
// pad key to 128 bits
while Length(Key) < 16 do Key:=Key+#$A5;
// Value should already be 64 bit aligned
DecodeBuffer(PChar(Value),Length(Value) div 4,Key);
Result:=Value;
end;
end.