I'm coding a "encryption" algorithm for learning and and don't know how good is it or how could I make it better:
private static byte[] encrypt(byte[] data, int session_id, byte[] password)
{
int session_key = (session_id & 0xFF);
if (session_key == 0) session_key = (session_id << 4);
byte[] output = new byte[data.Length];
for (int i = 0; i < output.Length; i++)
{
int index = getIndex(i, password.Length);
int num001 = session_key << 2;
int num002 = (session_id | i) >> (i+1);
int num003 = function(i, session_key, password[index]);
byte encrypted = XorByte(data[i], password);
output[i] = (byte)((encrypted ^ num003) + (num002 % num001) );
}
return output;
}
private static byte[] decrypt(byte[] data, int session_id, int length, byte[] password)
{
int session_key = (session_id & 0xFF);
if (session_key == 0) session_key = (session_id << 4);
byte[] output = new byte[data.Length];
for (int i = 0; i < output.Length; i++)
{
int index = getIndex(i, password.Length);
int num001 = session_key << 2;
int num002 = (session_id | i) >> (i + 1);
int num003 = function(i, session_key, password[index]);
byte decrypted = (byte)(data[i] - (num002 % num001) ^ num003);
output[i] = XorByte(decrypted, password);
}
return output;
}
private static int function(int index, int a, int b)
{
if (a > b)
if ((b + index) < a) return a - b - index;
else return a - b + index;
else
if ((a + index) < b) return b - a - index;
else return b - a + index;
}
public static int getIndex(int a, int b) => (a + b) >> 2;
private static byte XorByte(byte input, byte[] password)
{
byte output = input;
for (int i = 0; i < password.Length; i++) output ^= password[i];
return output;
}
Basically, this code takes a byte[]
(data) which will be encrypted. The session_id
is a randomly-generated number (this is supposed to be used in a client-server app, and every client is assigned an ID), and a password, which is a random generated byte[]
.
The main functions are encrypt
and decrypt
, and they call another 3:
function(int index, int a, int b)
- this creates a number based on another 3 that is used to XOR each byte the input of the encryption and decryption functions.getIndex(int a, int b)
- this returns the "middle" number (I don't know how to say it in English) of 2 numbers, that are the number of iterations and the password length. This is used to get a byte within the password.XorByte(byte input, byte[] password)
- this applies XOR to a byte recursively for each byte of the password, so the longer the password the harder to break.
Outputs:
Using a 32 byte random password, a random ID between 1000 and 10000, and the input data: "testing string":
UTF-8 bytes: 116 101 115 116 105 110 103 32 115 116 114 105 110 103 encrypted result: ?`R?o1?zqnrjb UTF-8 bytes: 160 96 82 15 237 111 49 205 122 113 110 114 106 98
Time: 112 ticks, less than 1 ms (encryption and decryption)
With the same inputs done 100.000 times:
Time: 0,08009ms each encryption/decryption, 8009ms overall