Simple XOR encryption and nibble switch
Check out Complete Beginners PHP 101 Ebook and Video Course.
Just to make it a bit confusing.
When encrypting, first xor and then swap the nibbles.
When decrypting, first swap the nibbles and then xor.
How it works
Say we have string “AXE” (hex 41 58 45)
We start with A.
A = 0×41 = 65 = 0100 0001
In this example code our key is 0x7A
z = 0x7A = 122 = 0111 1010
'A' XOR 0x45 = 59
First we XOR it..
0x41 = 0100 0001
0x7A = 0111 1010
----------------
X OR = 0011 1011
And then we swap the nibbles by pushing both ways..
a = a >> 4
a = 0000 0011
c = c << 4
c = 1011 0000
a|c = 1011 0011
So ‘A’ becomes 0xB3 (179).
‘X’ becomes 0×22 (34)
and ‘E’ becomes 0xF3 (243)
So now we have B3 22 F3 instead of 41 58 45 ;)
To decrypt, just do the opposite. Swap the nibbles and then XOR by 0x7A
Source code
-
class PacketSecurity
-
{
-
// simple xor cipher
-
private byte cipher(byte c)
-
{
-
c ^= 0x7A; // 122 is ‘key’, change to anything
-
return c;
-
}
-
-
// nibble swap
-
private byte swap(byte c)
-
{
-
byte a = (byte)(c >> 4); // add 4 0′s before c so we get high nibble as low
-
c = (byte)(c << 4); // add 4 0′s after c so we get low nibble as high
-
return (byte)(a|c); // use OR to add them together
-
}
-
-
public byte[] encrypt(string s)
-
{
-
-
for(int i = 0; i < s.Length; i++)
-
{
-
b[i] = cipher((byte)s[i]);
-
b[i] = swap(b[i]);
-
}
-
-
return b;
-
}
-
-
public string decrypt(byte[] b)
-
{
-
string s = "";
-
-
for (int i = 0; i < b.Length; i++)
-
{
-
b[i] = swap(b[i]);
-
s += cipher(b[i]);
-
}
-
-
return s;
-
}
-
}
Leave a Reply