Skip to content
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#if NETCOREAPP
using System;
using System.Buffers;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
Expand Down Expand Up @@ -54,11 +55,11 @@ private static byte[] DeriveKeyImpl(string password, byte[] salt, KeyDerivationP
throw new ArgumentOutOfRangeException();
}

var passwordBytes = Encoding.UTF8.GetBytes(password);
using (var rfc = new Rfc2898DeriveBytes(passwordBytes, salt, iterationCount, algorithmName))
{
return rfc.GetBytes(numBytesRequested);
}
var maxBytes = Encoding.UTF8.GetMaxByteCount(password.Length);
Span<byte> bytes = (maxBytes > 256) ? ArrayPool<byte>.Shared.Rent(maxBytes) : stackalloc byte[256];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this turns it in to an Oracle since stackalloc is faster than the ArrayPool. Also, I just recalled @GrabYourPitchforks recommending against using the shared array pool for crypto things.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pranavkm how do you feel about if we just do stackalloc for up to 256 and use the old alloc from GetBytes for crazy long passwords (which has to be extremely uncommon)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chatted with @pranavkm offline, we will put this into the bucket of spanification things to revisit in a separate PR,

var byteCount = Encoding.UTF8.GetBytes(password.AsSpan(), bytes);
bytes = bytes.Slice(0, byteCount);
return Rfc2898DeriveBytes.Pbkdf2(bytes, salt, iterationCount, algorithmName, numBytesRequested);
}
}
}
Expand Down