Gah - a solution with more questions. – EntropicLqd
Legacy:XTEA
From Unreal Wiki, The Unreal Engine Documentation Site
This ia an implementation of the Wikipedia:XTEA cypher.
Contents |
Code
const DELTA = 0x9E3779B9;
const ROUNDS = 32;
static final function encipher(out int v[2], int k[4])
{
local int y, z, sum, n;
y=v[0]; z=v[1]; sum=0; n=0;
while(n++ < ROUNDS)
{
y += (z << 4 ^ z >>> 5) + z ^ sum + k[sum&3];
sum += DELTA;
z += (y << 4 ^ y >>> 5) + y ^ sum + k[sum>>>11 & 3];
}
v[0]=y; v[1]=z;
}
static final function decipher(out int v[2], int k[4])
{
local int y, z, sum, n;
y=v[0]; z=v[1]; sum=DELTA*ROUNDS; n=0;
while(n++ < ROUNDS)
{
z -= (y << 4 ^ y >>> 5) + y ^ sum + k[sum>>>11 & 3];
sum -= DELTA;
y -= (z << 4 ^ z >>> 5) + z ^ sum + k[sum&3];
}
v[0]=y; v[1]=z;
}
static final function buildkey(string key, out int k[4])
{
local int i;
for (i = 0; i < 4; i++)
{
k[i] = (asc(mid(key, i*4, 1)) << 24) | ((asc(mid(key, i*4+1, 1)) & 0xff) << 16) | ((asc(mid(key, i*4+2, 1)) & 0xff) << 8) | (asc(mid(key, i*4+3, 1)) & 0xff);
}
}
static function string encrypt(string str, string key)
{
local int i, v[2], k[4];
local string ret;
buildkey(key, k);
while (i < len(str))
{
v[0] = (asc(mid(str, i++, 1)) << 24) | ((asc(mid(str, i++, 1))&0xff) << 16) | ((asc(mid(str, i++, 1))&0xff) << 8) | (asc(mid(str, i++, 1))&0xff);
v[1] = (asc(mid(str, i++, 1)) << 24) | ((asc(mid(str, i++, 1))&0xff) << 16) | ((asc(mid(str, i++, 1))&0xff) << 8) | (asc(mid(str, i++, 1))&0xff);
encipher(v, k);
ret = ret $ DecToHex(v[0], 4) $ DecToHex(v[1], 4);
v[0] = 0; v[1] = 0;
}
return ret;
}
static function string decrypt(string str, string key)
{
local int i, v[2], k[4];
local string ret;
buildkey(key, k);
while (i < len(str))
{
v[0] = HexToDec(Mid(str, i, 8));
i+=8;
v[1] = HexToDec(Mid(str, i, 8));
i+=8;
decipher(v, k);
ret = ret $ Chr((v[0] >>> 24) & 0xff) $ Chr((v[0] >>> 16) & 0xff) $ Chr((v[0] >>> 8) & 0xff) $ Chr(v[0] & 0xff);
ret = ret $ Chr((v[1] >>> 24) & 0xff) $ Chr((v[1] >>> 16) & 0xff) $ Chr((v[1] >>> 8) & 0xff) $ Chr(v[1] & 0xff);
v[0] = 0; v[1] = 0;
}
return ret;
}
static final function int HexToDec(string hexcode) // Borrowed from ElMuerte's LibHTTP
{
local int res, i, cur;
res = 0;
hexcode = Caps(hexcode);
for (i = 0; i < len(hexcode); i++)
{
cur = Asc(Mid(hexcode, i, 1));
if (cur == 32) return res;
cur -= 48; // 0 = ascii 30
if (cur > 9) cur -= 7;
if ((cur > 15) || (cur < 0)) return -1; // not possible
res = res << 4;
res += cur;
}
return res;
}
static final function string DecToHex(int dec, int size)
{
const hex = "0123456789ABCDEF";
local string s;
local int i;
for (i = 0; i < size*2; i++)
{
s = mid(hex, dec & 0xf, 1) $ s;
dec = dec >>> 4;
}
return s;
}
Usage
To encrypt a message use:
EncryptedMessage = encrypt(Message, Key)
To decrypt a message use:
Message = decrypt(EncryptedMessage, Key)
License
Copyright 2004 (c) Petr Jelinek
Released under the LesserOpenUnrealModLicense
