Skip to content

Commit

Permalink
refactor: Reduce loop statements to one
Browse files Browse the repository at this point in the history
We can place the entire contents needed for the key generation before the inital iteration of the buffer.
  • Loading branch information
ArachisH committed Nov 1, 2023
1 parent 0fb8fbc commit 882afae
Showing 1 changed file with 7 additions and 15 deletions.
22 changes: 7 additions & 15 deletions Flazzy/Tools/FlashCrypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,14 @@ private static uint GetKey(ReadOnlySpan<byte> headerBytes)
dSum += headerBytes[i];
}

int dMod = dSum % GlobalKey.Length;
Span<byte> buffer = stackalloc byte[GlobalKey.Length];
Span<char> dSumChars = stackalloc char[4]; // Max Digits (255 * 8 = 2,040)
dSum.TryFormat(dSumChars, out int charsWritten);

Span<byte> buffer = stackalloc byte[GlobalKey.Length + SecondaryKey.Length + charsWritten];
SecondaryKey.CopyTo(buffer.Slice(GlobalKey.Length)); // Place 'SecondaryKey' at the tail of the buffer.
Encoding.Default.GetBytes(dSumChars.Slice(0, charsWritten), buffer.Slice(buffer.Length - charsWritten)); // Place 'dSum' at the tail of the buffer, after 'SecondaryKey'.

int dMod = dSum % GlobalKey.Length;
GlobalKey[dMod..].CopyTo(buffer);
GlobalKey[..dMod].CopyTo(buffer.Slice(GlobalKey.Length - dMod, dMod));

Expand All @@ -74,19 +79,6 @@ private static uint GetKey(ReadOnlySpan<byte> headerBytes)
key += buffer[i];
}

Span<char> dSumChars = stackalloc char[4]; // Max Digits (255 * 8 = 2,040)
dSum.TryFormat(dSumChars, out int charsWritten);

SecondaryKey.CopyTo(buffer);
int encoded = SecondaryKey.Length;

encoded += Encoding.Default.GetBytes(dSumChars.Slice(0, charsWritten), buffer.Slice(encoded));
for (int i = 0; i < encoded; i++)
{
key *= 31;
key += buffer[i];
}

return key & uint.MaxValue;
}
}

0 comments on commit 882afae

Please sign in to comment.