|
19 | 19 | using System.Security;
|
20 | 20 | using System.Security.Cryptography;
|
21 | 21 | using System.Text;
|
| 22 | +using static Neo.Helper; |
22 | 23 | using ECPoint = Neo.Cryptography.ECC.ECPoint;
|
23 | 24 |
|
24 | 25 | namespace Neo.Cryptography
|
@@ -123,29 +124,20 @@ public static byte[] Sha256(this Span<byte> value)
|
123 | 124 |
|
124 | 125 | public static byte[] AES256Encrypt(this byte[] plainData, byte[] key, byte[] nonce, byte[] associatedData = null)
|
125 | 126 | {
|
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]; |
134 | 130 | using var cipher = new AesGcm(key);
|
135 | 131 | 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); |
141 | 133 | }
|
142 | 134 |
|
143 | 135 | public static byte[] AES256Decrypt(this byte[] encryptedData, byte[] key, byte[] associatedData = null)
|
144 | 136 | {
|
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..]; |
149 | 141 | var decryptedData = new byte[cipherBytes.Length];
|
150 | 142 | using var cipher = new AesGcm(key);
|
151 | 143 | cipher.Decrypt(nonce, cipherBytes, tag, decryptedData, associatedData);
|
|
0 commit comments