Skip to content

Commit 47f109b

Browse files
committed
Optimize
1 parent bb5be4b commit 47f109b

File tree

1 file changed

+9
-17
lines changed

1 file changed

+9
-17
lines changed

src/neo/Cryptography/Helper.cs

+9-17
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
using System.Security;
2020
using System.Security.Cryptography;
2121
using System.Text;
22+
using static Neo.Helper;
2223
using ECPoint = Neo.Cryptography.ECC.ECPoint;
2324

2425
namespace Neo.Cryptography
@@ -123,29 +124,20 @@ public static byte[] Sha256(this Span<byte> value)
123124

124125
public static byte[] AES256Encrypt(this byte[] plainData, byte[] key, byte[] nonce, byte[] associatedData = null)
125126
{
126-
var keyLen = key is null ? 0 : key.Length;
127-
var nonceLen = nonce is null ? 0 : nonce.Length;
128-
if (keyLen != 32) throw new ArgumentException();
129-
if (nonceLen != 12) throw new ArgumentException();
130-
var msgLen = plainData is null ? 0 : plainData.Length;
131-
var tagLen = 16;
132-
var cipherBytes = new byte[msgLen];
133-
var tag = new byte[tagLen];
127+
if (nonce.Length != 12) throw new ArgumentOutOfRangeException(nameof(nonce));
128+
var cipherBytes = new byte[plainData.Length];
129+
var tag = new byte[16];
134130
using var cipher = new AesGcm(key);
135131
cipher.Encrypt(nonce, plainData, cipherBytes, tag, associatedData);
136-
var cipherWithTag = new byte[nonceLen + msgLen + tagLen];
137-
Buffer.BlockCopy(nonce, 0, cipherWithTag, 0, nonceLen);
138-
Buffer.BlockCopy(cipherBytes, 0, cipherWithTag, nonceLen, msgLen);
139-
Buffer.BlockCopy(tag, 0, cipherWithTag, nonceLen + msgLen, tagLen);
140-
return cipherWithTag;
132+
return Concat(nonce, cipherBytes, tag);
141133
}
142134

143135
public static byte[] AES256Decrypt(this byte[] encryptedData, byte[] key, byte[] associatedData = null)
144136
{
145-
if (key.Length != 32) throw new ArgumentException();
146-
var nonce = encryptedData.Take(12).ToArray();
147-
var cipherBytes = encryptedData.Skip(12).Take(encryptedData.Length - 28).ToArray();
148-
var tag = encryptedData[^16..];
137+
ReadOnlySpan<byte> encrypted = encryptedData;
138+
var nonce = encrypted[..12];
139+
var cipherBytes = encrypted[12..^16];
140+
var tag = encrypted[^16..];
149141
var decryptedData = new byte[cipherBytes.Length];
150142
using var cipher = new AesGcm(key);
151143
cipher.Decrypt(nonce, cipherBytes, tag, decryptedData, associatedData);

0 commit comments

Comments
 (0)