Skip to content

Commit

Permalink
Optimise encryption, avoid creating multiple transformer per transform
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaioru committed Oct 10, 2023
1 parent f7f7c32 commit 577def4
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions src/common/Edelstein.Common.Crypto/AESCipher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace Edelstein.Common.Crypto;

public class AESCipher
{
private readonly SymmetricAlgorithm _cipher;
private readonly ICryptoTransform _transformer;

public AESCipher() : this(new byte[] { 0x13, 0x08, 0x06, 0xb4, 0x1b, 0x0f, 0x33, 0x52 })
{
Expand All @@ -13,14 +13,15 @@ public AESCipher() : this(new byte[] { 0x13, 0x08, 0x06, 0xb4, 0x1b, 0x0f, 0x33,
public AESCipher(ReadOnlySpan<byte> userKey)
{
var expandedKey = new byte[userKey.Length * 4];
var cipher = Aes.Create();

for (var i = 0; i < userKey.Length; i++)
expandedKey[i * 4] = userKey[i];

_cipher = Aes.Create();
_cipher.KeySize = 256;
_cipher.Key = expandedKey;
_cipher.Mode = CipherMode.ECB;
cipher.KeySize = 256;
cipher.Key = expandedKey;
cipher.Mode = CipherMode.ECB;
_transformer = cipher.CreateEncryptor();
}

public void Transform(Span<byte> input, uint pSrc)
Expand All @@ -32,8 +33,6 @@ public void Transform(Span<byte> input, uint pSrc)
var srcExp = new byte[sizeof(int) * 4];
var srcBytes = BitConverter.GetBytes(pSrc);

using var crypt = _cipher.CreateEncryptor();

while (remaining > 0)
{
for (var i = 0; i < srcExp.Length; ++i)
Expand All @@ -48,7 +47,7 @@ public void Transform(Span<byte> input, uint pSrc)

if (sub % srcExp.Length == 0)
{
var result = crypt.TransformFinalBlock(srcExp, 0, srcExp.Length);
var result = _transformer.TransformFinalBlock(srcExp, 0, srcExp.Length);
Array.Copy(result, srcExp, srcExp.Length);
}

Expand Down

0 comments on commit 577def4

Please sign in to comment.