Skip to content

Commit ce5691b

Browse files
committed
Faster RC4 again
stack yyds
1 parent 6ab2b92 commit ce5691b

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

CryptoBase/SymmetricCryptos/StreamCryptos/RC4/RC4Crypto.cs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,13 @@ private byte GetByte(Span<byte> stateSpan)
4848
{
4949
x = x + 1 & 0xFF;
5050
y = stateSpan[x] + y & 0xFF;
51-
Utils.Swap(ref stateSpan[x], ref stateSpan[y]);
52-
return stateSpan[stateSpan[x] + stateSpan[y] & 0xFF];
51+
52+
var x0 = stateSpan[x];
53+
var y0 = stateSpan[y];
54+
stateSpan[x] = y0;
55+
stateSpan[y] = x0;
56+
57+
return stateSpan[(byte)(x0 + y0)];
5358
}
5459

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

7175
if (Avx.IsSupported && Avx2.IsSupported)
7276
{
7377
while (length >= 32)
7478
{
7579
for (var i = 0; i < 32; ++i)
7680
{
77-
*(temp + i) = GetByte(stateSpan);
81+
*(destination + i) = GetByte(stateSpan);
7882
}
7983

80-
var v0 = Avx.LoadVector256(temp);
84+
var v0 = Avx.LoadVector256(destination);
8185
var v1 = Avx.LoadVector256(source);
8286
Avx.Store(destination, Avx2.Xor(v0, v1));
8387

@@ -93,10 +97,10 @@ private unsafe void Update(byte* source, byte* destination, int length)
9397
{
9498
for (var i = 0; i < 16; ++i)
9599
{
96-
*(temp + i) = GetByte(stateSpan);
100+
*(destination + i) = GetByte(stateSpan);
97101
}
98102

99-
var v0 = Sse2.LoadVector128(temp);
103+
var v0 = Sse2.LoadVector128(destination);
100104
var v1 = Sse2.LoadVector128(source);
101105
Sse2.Store(destination, Sse2.Xor(v0, v1));
102106

0 commit comments

Comments
 (0)