Newbie Spellweaver
- Joined
- Aug 19, 2020
- Messages
- 8
- Reaction score
- 2
C#:
public static void XorDataWithKey(byte[] data, uint length)
{
int keyIndex = 0;
uint dataIndex = 0;
int[] xorKey = new int[] { 83952385, 16843521 };
while (dataIndex < length)
{
data[dataIndex++] ^= (byte)(xorKey[keyIndex] >> (8 * keyIndex));
keyIndex = (keyIndex + 1) < 8 ? keyIndex + 1 : 0;
}
}
public static void Encrypt(byte[] data, uint length, uint rotationBits)
{
int remainingBits = 8 - (int)rotationBits;
int currentIndex = 0;
for (int i = data[currentIndex]; currentIndex < length; ++currentIndex)
{
byte nextByte = (currentIndex >= length - 1) ? data[currentIndex] : data[currentIndex + 1];
byte rotatedBits = (byte)(nextByte >> remainingBits);
remainingBits = 8 - (int)rotationBits;
data[currentIndex] = (byte)((data[currentIndex] << (int)rotationBits) | rotatedBits);
}
}
public static void Decrypt(byte[] data, uint length, uint rotationBits)
{
int remainingBits = (int)rotationBits;
byte lastByte = data[length - 1];
for (int i = length - 1; i >= 0; --i)
{
byte prevByte = (i <= 0) ? lastByte : data[i - 1];
byte rotatedBits = (byte)(data[i] >> remainingBits);
remainingBits = (int)rotationBits;
data[i] = (byte)((prevByte << (8 - remainingBits)) | rotatedBits);
}
}
public static int EncryptPBM(byte[] dest, byte[] source, uint length, string key)
{
if (dest == null || source == null || length == 0)
return 0;
int[] keyArray = new int[4];
int keyLength = Math.Min(key.Length, 16);
for (int i = 0; i < keyLength / 4; i++)
{
keyArray[i] = BitConverter.ToInt32(Encoding.ASCII.GetBytes(key.Substring(i * 4, 4)), 0);
}
for (int i = keyLength; i < 16; i++)
{
keyArray[i / 4] = ((keyArray[i / 4] << 8) | key[i % keyLength]) % 0xFF + 1;
}
return SubEncryptPBM(dest, source, length, keyArray); //Marshal
}
public static int DecryptPBM(byte[] dest, byte[] source, uint length, string key)
{
if (dest == null || source == null || length == 0)
return 0;
int[] keyArray = new int[4];
int keyLength = Math.Min(key.Length, 16);
for (int i = 0; i < keyLength / 4; i++)
{
keyArray[i] = BitConverter.ToInt32(Encoding.ASCII.GetBytes(key.Substring(i * 4, 4)), 0);
}
for (int i = keyLength; i < 16; i++)
{
keyArray[i / 4] = ((keyArray[i / 4] << 8) | key[i % keyLength]) % 0xFF + 1;
}
SubDecryptPBM(dest, source, length, keyArray); //Marshal
return 1;
}