• Welcome to Valhalla Legends Archive.
 

[C#] D2 & W2 CDKey Decoding

Started by shout, January 14, 2005, 06:39 PM

Previous topic - Next topic

shout

I am having trouble with alphanumeric keys. I figured it would be eaiser to pass they key as an array of bytes rather than a string, but mabye I am wrong. Could someone just glance at my code and see if I am doing wrongly?

Outputs:

BNLS:

[0x0] 0x10
[0x1] 0xc
[0x2] 0xe3d332
[0x3] 0x0
[0x4] 0x9ae79ec6
[0x5] 0x5728e3be
[0x6] 0xabeee404
[0x7] 0xb5e1af8e
[0x8] 0xd493f8ac


Mine:

[0x0] 0x10
[0x1] 0x24
[0x2] 0x5e5d30
        [0x3] 0x0
[0x4] 0x5889db6e
[0x5] 0x83835d24
[0x6] 0xe59aa967
[0x7] 0xe2d5ce17
[0x8] 0xeb9e0461


My beautifully uncommented code:


public static int[] DecodeAlphanumericKey(string Key)
{
byte[] bKey = new byte[cKey.Length];
for (int i = 0; i < cKey.Length; i++)
{
bKey[i] = (byte)Key[i];
}

byte[] BKey = d2Final(d2Shuffle(keyPass1(bKey)));

int[] rValues = new int[3];
string s = Encoding.ASCII.GetString(BKey);

rValues[0] = int.Parse(s.Substring(0,2), NumberStyles.AllowHexSpecifier);
rValues[1] = int.Parse(s.Substring(2,6), NumberStyles.AllowHexSpecifier);
rValues[2] = int.Parse(s.Substring(8,8), NumberStyles.AllowHexSpecifier);

return rValues;
}

static byte[] keyPass1(byte[] Key)
{
byte[] key = new byte[Key.Length];
Buffer.BlockCopy(Key, 0, key, 0, Key.Length);
byte codevalue1, codevalue2;
int keyvalue1, keyvalue2;

for (int i = 0; i < 16; i += 2)
{
codevalue1 = (byte)alphaMap[key[i]];
codevalue2 = (byte)alphaMap[key[i+1]];
keyvalue1 = codevalue1 * 3;
keyvalue1 = codevalue2 + keyvalue1 * 8;
if (keyvalue1 >= 0x100)
keyvalue1 -= 0x100;
keyvalue2 = keyvalue1 >> 4;
key[i] = (byte)getHexVal(keyvalue1);
key[i + 1] = (byte)getHexVal(keyvalue2);
}

return key;
}

static byte[] d2Shuffle(byte[] Key)
{
byte[] key = new byte[Key.Length];
Buffer.BlockCopy(Key, 0, key, 0, Key.Length);
byte keyIndex;

for (int i = 15; i >= 0; i--)
{
if (i > 8)
keyIndex = (byte)(i - 9);
else
keyIndex = (byte)(0xF - (8 - i));
keyIndex &= 0xF;
swap(key, i, keyIndex);
}
return key;
}

static byte[] swap(byte[] data, int posA, int posB)
{
byte a = data[posA];
data[posA] = data[posB];
data[posB] = a;
return data;
}

static byte[] d2Final(byte[] Key) //This is the same as the starcraft one,
{//                          only the loop changes.
int hashKey = 0x13AC9741;
byte[] key = new byte[Key.Length];
Buffer.BlockCopy(Key, 0, key, 0, Key.Length);

for (int i = 15; i >= 0; i--)
{
byte b = (byte)char.ToUpper((char)key[i]);
key[i] = b;
if (b <= '7')
{
b = (byte)(hashKey & 0xFF);
b &= 7;
b ^= key[i];
hashKey >>= 3;
key[i] = b;
}
else if (b < 'A')
{
b = (byte)i;
b &= 1;
b ^= key[i];
key[i] = b;
}
}
return key;
}

static char getHexVal(int v)
{
v &= 0xF;
if (v < 10)
return (char) (v + 0x30);
else
return (char) (v + 0x37);
}


Thanks to all who put up with me.

EDIT:Code Update.