Skip to content

Commit

Permalink
Faster RC4 again
Browse files Browse the repository at this point in the history
stack yyds
  • Loading branch information
HMBSbige committed Apr 30, 2021
1 parent 6ab2b92 commit ce5691b
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions CryptoBase/SymmetricCryptos/StreamCryptos/RC4/RC4Crypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,13 @@ private byte GetByte(Span<byte> stateSpan)
{
x = x + 1 & 0xFF;
y = stateSpan[x] + y & 0xFF;
Utils.Swap(ref stateSpan[x], ref stateSpan[y]);
return stateSpan[stateSpan[x] + stateSpan[y] & 0xFF];

var x0 = stateSpan[x];
var y0 = stateSpan[y];
stateSpan[x] = y0;
stateSpan[y] = x0;

return stateSpan[(byte)(x0 + y0)];
}

public override unsafe void Update(ReadOnlySpan<byte> source, Span<byte> destination)
Expand All @@ -66,18 +71,17 @@ public override unsafe void Update(ReadOnlySpan<byte> source, Span<byte> destina
private unsafe void Update(byte* source, byte* destination, int length)
{
var stateSpan = _state.AsSpan();
var temp = stackalloc byte[32];

if (Avx.IsSupported && Avx2.IsSupported)
{
while (length >= 32)
{
for (var i = 0; i < 32; ++i)
{
*(temp + i) = GetByte(stateSpan);
*(destination + i) = GetByte(stateSpan);
}

var v0 = Avx.LoadVector256(temp);
var v0 = Avx.LoadVector256(destination);
var v1 = Avx.LoadVector256(source);
Avx.Store(destination, Avx2.Xor(v0, v1));

Expand All @@ -93,10 +97,10 @@ private unsafe void Update(byte* source, byte* destination, int length)
{
for (var i = 0; i < 16; ++i)
{
*(temp + i) = GetByte(stateSpan);
*(destination + i) = GetByte(stateSpan);
}

var v0 = Sse2.LoadVector128(temp);
var v0 = Sse2.LoadVector128(destination);
var v1 = Sse2.LoadVector128(source);
Sse2.Store(destination, Sse2.Xor(v0, v1));

Expand Down

0 comments on commit ce5691b

Please sign in to comment.