Skip to content

Commit cd2ee76

Browse files
committed
ProcessXor: optimisations
1 parent da5a050 commit cd2ee76

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

KaitaiStream.cs

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -508,32 +508,50 @@ public static byte[] BytesTerminate(byte[] src, byte terminator, bool includeTer
508508

509509
/// <summary>
510510
/// Perform XOR processing between given data and single-byte key.
511+
/// WARNING: May return same byte array if key is zero.
511512
/// </summary>
512-
/// <param name="value">The data to process, as byte array</param>
513+
/// <param name="data">The data to process, as byte array</param>
513514
/// <param name="key">The key to XOR with, as integer</param>
514-
public byte[] ProcessXor(byte[] value, int key)
515+
public byte[] ProcessXor(byte[] data, int key)
515516
{
516-
byte[] result = new byte[value.Length];
517-
for (int i = 0; i < value.Length; i++)
517+
if (key == 0)
518+
return data;
519+
520+
byte[] result = new byte[data.Length];
521+
522+
for (int i = 0; i < data.Length; i++)
518523
{
519-
result[i] = (byte)(value[i] ^ key);
524+
result[i] = (byte)(data[i] ^ key);
520525
}
526+
521527
return result;
522528
}
523529

524530
/// <summary>
525531
/// Perform XOR processing between given data and multiple-byte key.
532+
/// WARNING: May return same byte array if key is zero.
526533
/// </summary>
527-
/// <param name="value">The data to process, as byte array</param>
534+
/// <param name="data">The data to process, as byte array</param>
528535
/// <param name="key">The key to XOR with, as byte array</param>
529-
public byte[] ProcessXor(byte[] value, byte[] key)
536+
public byte[] ProcessXor(byte[] data, byte[] key)
530537
{
538+
if (key.Length == 1)
539+
return ProcessXor(data, key[0]);
540+
if (key.Length <= 64 && IsByteArrayZero(key))
541+
return data;
542+
543+
byte[] result = new byte[data.Length];
531544
int keyLen = key.Length;
532-
byte[] result = new byte[value.Length];
533-
for (int i = 0, j = 0; i < value.Length; i++, j = (j + 1) % keyLen)
545+
546+
int k = 0;
547+
for (int i = 0; i < data.Length; i++)
534548
{
535-
result[i] = (byte)(value[i] ^ key[j]);
549+
result[i] = (byte)(data[i] ^ key[k]);
550+
k++;
551+
if (k == keyLen)
552+
k = 0;
536553
}
554+
537555
return result;
538556
}
539557

0 commit comments

Comments
 (0)