Skip to content

Use one shot pbkdf2 #31200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
7 commits merged into from
Mar 30, 2021
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