Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 0d03533

Browse files
committed
Remove an array allocation in Rfc2898DeriveBytes::Func.
Changed Helpers::Int to write the value inline, and changed its name to WriteInt.
1 parent b67b14a commit 0d03533

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/System.Security.Cryptography.DeriveBytes/src/Internal/Cryptography/Helpers.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) Microsoft. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4+
using System.Diagnostics;
45
using System.Security.Cryptography;
56

67
namespace Internal.Cryptography
@@ -25,9 +26,18 @@ public static byte[] GenerateRandom(int count)
2526
}
2627

2728
// encodes the integer i into a 4-byte array, in big endian.
28-
public static byte[] Int(uint i)
29+
public static void WriteInt(uint i, byte[] arr, int offset)
2930
{
30-
return unchecked(new byte[] { (byte)(i >> 24), (byte)(i >> 16), (byte)(i >> 8), (byte)i });
31+
unchecked
32+
{
33+
Debug.Assert(arr != null);
34+
Debug.Assert(arr.Length >= offset + sizeof(uint));
35+
36+
arr[offset] = (byte)(i >> 24);
37+
arr[offset + 1] = (byte)(i >> 16);
38+
arr[offset + 2] = (byte)(i >> 8);
39+
arr[offset + 3] = (byte)i;
40+
}
3141
}
3242
}
3343
}

src/System.Security.Cryptography.DeriveBytes/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,11 +178,9 @@ private void Initialize()
178178
// where i is the block number.
179179
private byte[] Func()
180180
{
181-
byte[] INT_block = Helpers.Int(_block);
182-
183-
byte[] temp = new byte[_salt.Length + INT_block.Length];
181+
byte[] temp = new byte[_salt.Length + sizeof(uint)];
184182
Buffer.BlockCopy(_salt, 0, temp, 0, _salt.Length);
185-
Buffer.BlockCopy(INT_block, 0, temp, _salt.Length, INT_block.Length);
183+
Helpers.WriteInt(_block, temp, _salt.Length);
186184

187185
temp = _hmacSha1.ComputeHash(temp);
188186

0 commit comments

Comments
 (0)