Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
43 changes: 41 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# CodeFusion.Security.Bcrypt

bcrypt for .NET 8, 9 and 10, tested on .NET 11 too. A check allocates no memory at all, and a new hash only its
string. Up to five hashes run interleaved on one thread, each for a quarter to two fifths of the CPU time of a hash
string, or nothing when it's written as bytes. Up to five hashes run interleaved on one thread, each for a quarter to two fifths of the CPU time of a hash
alone, and `BcryptQueue` gives a server that batching without blocking its thread pool.

Hashes are interchangeable with OpenBSD, Go, PHP, Python's bcrypt and BCrypt.Net-Next, including BCrypt.Net-Next's
Expand Down Expand Up @@ -72,7 +72,7 @@ makes one:
```csharp
builder.Services.AddSingleton(new BcryptQueue(new BcryptQueueOptions
{
MaxQueued = 1024, // past that, calls fail at once with BcryptQueueFullException: answer 503
MaxQueued = 1024, // past that, calls fail at once with BcryptQueueFullException (TryVerifyAsync says Busy): answer 503
}));

string dummyHash = Bcrypt.Hash(Guid.NewGuid().ToString(), 12);
Expand Down Expand Up @@ -122,6 +122,43 @@ up to 200 ms of latency.
| A check now and then, or not a server | `Bcrypt.Verify(password, hash)` |
| A batch you already hold | `Bcrypt.Verify(passwords, hashes, results)` |
| A web server's sign-in and sign-up | `BcryptQueue.VerifyAsync` and `HashAsync` |
| A server that reads passwords and keeps hashes as bytes | the byte overloads below |

## Bytes instead of strings

A server reads the password off the wire as bytes and may keep the hash as bytes too. The overloads that take spans
skip both strings, and none of them allocates:

```csharp
bool ok = Bcrypt.Verify(passwordUtf8, storedHash); // two ReadOnlySpan<byte>
int written = Bcrypt.Hash(passwordUtf8, 12, destination); // 60 ASCII bytes into a Span<byte>

bool ok = await bcrypt.VerifyAsync(passwordUtf8, storedHash, aborted);
BcryptHash hash = await bcrypt.HashAsync(passwordUtf8, 12); // the 60 bytes, held inline
hash.CopyTo(row.PasswordHash);
```

- The queue copies both spans before the call returns, so their buffers can be reused at once.
- The password's bytes are the key as they are. UTF-8 gives the same hashes as the string overloads, and other bytes
are taken too, as Go takes them. A NUL counts, as it does in a string; C implementations stop at the first one.
Over 72 bytes is refused, as with strings. The enhanced hashes take strings only.
- `BcryptHash` reads out with `CopyTo`, `TryFormat` (to bytes or chars) or `AsSpan`; `ToString` makes the string.

`TryVerifyAsync` and `TryHashAsync` report a full queue or a fired token as a status instead of an exception, so
overload costs no exception either:

```csharp
switch (await bcrypt.TryVerifyAsync(passwordUtf8, storedHash, aborted))
{
case BcryptStatus.Match: return Results.Ok(Token(user));
case BcryptStatus.Busy: return Results.StatusCode(503);
case BcryptStatus.Cancelled: return Results.Empty; // the client went away
default: return Results.Unauthorized(); // NoMatch, or a malformed hash
}

BcryptHashResult made = await bcrypt.TryHashAsync(passwordUtf8, 12);
if (made.Status == BcryptStatus.Hashed) made.CopyTo(row.PasswordHash); // CopyTo throws when there is no hash
```

## Passwords over 72 bytes

Expand Down Expand Up @@ -165,6 +202,8 @@ there are. Bytes allocated per call, measured over 2,000 calls (the cost doesn't
| `EnhancedVerify` | **0 B** | 5,856 B |
| `BcryptQueue.VerifyAsync` | **0 B** | |
| `Hash` | 144 B: the returned string | 5,416 B |
| `Verify` and `Hash` from bytes | **0 B** | |
| `BcryptQueue.VerifyAsync`, `HashAsync`, `TryVerifyAsync` and `TryHashAsync` from bytes | **0 B** | |

At 1,000 sign-ins a second, BCrypt.Net-Next makes 5 MB of garbage a second; this package makes none.
BCrypt.Net-Next allocates a new 4 KB copy of the Blowfish tables for every hash. This package does the following:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
Expand All @@ -19,6 +20,7 @@ public class VerifyBenchmarks
// From Go's golang.org/x/crypto/bcrypt.
const string Hash = "$2a$10$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wq";

static readonly byte[] PasswordUtf8 = Encoding.UTF8.GetBytes(Password), HashAscii = Encoding.ASCII.GetBytes(Hash);
static readonly string[] Passwords = [Password, Password, Password, Password, Password];
static readonly string[] Hashes = [Hash, Hash, Hash, Hash, Hash];
readonly bool[] _results = new bool[Bcrypt.MaxLanes];
Expand All @@ -36,6 +38,10 @@ public class VerifyBenchmarks
[Benchmark, BenchmarkCategory("verify")]
public bool Verify() => Bcrypt.Verify(Password, Hash);

/// <summary>The same check from bytes, as a server reads them off the wire.</summary>
[Benchmark, BenchmarkCategory("verify")]
public bool VerifyUtf8() => Bcrypt.Verify(PasswordUtf8, HashAscii);

[Benchmark(OperationsPerInvoke = 2), BenchmarkCategory("verify")]
public bool Lanes2() => Lanes(2);

Expand All @@ -62,23 +68,54 @@ async ValueTask<bool> FiveThroughTheQueue()
return await a & await b & await c & await d & await e;
}

/// <summary><see cref="Queue5"/> through the byte overload.</summary>
[Benchmark(OperationsPerInvoke = 5), BenchmarkCategory("verify")]
public ValueTask<bool> Queue5Utf8() => FiveUtf8ThroughTheQueue();

[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
async ValueTask<bool> FiveUtf8ThroughTheQueue()
{
ValueTask<bool> a = _queue.VerifyAsync(PasswordUtf8, HashAscii), b = _queue.VerifyAsync(PasswordUtf8, HashAscii),
c = _queue.VerifyAsync(PasswordUtf8, HashAscii), d = _queue.VerifyAsync(PasswordUtf8, HashAscii), e = _queue.VerifyAsync(PasswordUtf8, HashAscii);
return await a & await b & await c & await d & await e;
}

bool Lanes(int n)
{
Bcrypt.Verify(Passwords.AsSpan(0, n), Hashes.AsSpan(0, n), _results.AsSpan(0, n));
return _results[n - 1];
}
}

/// <summary>A new hash at cost 10: the string it returns is all it allocates.</summary>
/// <summary>A new hash at cost 10: the string overloads allocate only the string they return, the byte ones nothing.</summary>
[MemoryDiagnoser]
public class HashBenchmarks
{
static readonly byte[] PasswordUtf8 = "password123"u8.ToArray();
readonly byte[] _destination = new byte[Bcrypt.HashLength];
BcryptQueue _queue = null!;

[GlobalSetup]
public void Setup() => _queue = new BcryptQueue(new BcryptQueueOptions { Threads = 1 });

[GlobalCleanup]
public void Cleanup() => _queue.Dispose();

[Benchmark(Baseline = true)]
public string BCryptNetNext() => BCrypt.Net.BCrypt.HashPassword("password123", 10);

[Benchmark]
public string Hash() => Bcrypt.Hash("password123", 10);

[Benchmark]
public int HashUtf8() => Bcrypt.Hash(PasswordUtf8, 10, _destination);

[Benchmark]
public string EnhancedHash() => Bcrypt.EnhancedHash("password123", 10);

[Benchmark]
public ValueTask<string> QueueHash() => _queue.HashAsync("password123", 10);

[Benchmark]
public ValueTask<BcryptHash> QueueHashUtf8() => _queue.HashAsync(PasswordUtf8, 10);
}
73 changes: 66 additions & 7 deletions src/CodeFusion.Security.Bcrypt/Bcrypt.Core.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,24 @@ static bool IsWholeHash(ReadOnlySpan<char> hash, int end)
internal static bool PrepareVerify(ReadOnlySpan<char> password, ReadOnlySpan<char> hash, BcryptPrehash prehash, Input* input)
{
Span<byte> salt = stackalloc byte[SaltBytes];
int end = ParseSettings(hash, out char revision, out int cost, salt);
if (!IsWholeHash(hash, end)) return false;
return Prepare(password, salt, cost, revision, prehash, input);
return ParseHash(hash, out char revision, out int cost, salt) && Prepare(password, salt, cost, revision, prehash, input);
}

/// <summary><see cref="PrepareVerify(ReadOnlySpan{char}, ReadOnlySpan{char}, BcryptPrehash, Input*)"/> of a password
/// and a hash as bytes; false when the hash is malformed or the password is over 72 bytes.</summary>
internal static bool PrepareVerify(ReadOnlySpan<byte> password, ReadOnlySpan<byte> hash, Input* input)
{
if (hash.Length > HashLength) return false;
Span<char> text = stackalloc char[HashLength];
for (int i = 0; i < hash.Length; i++) text[i] = (char)hash[i]; // a byte past ASCII widens to a char the parser refuses
Span<byte> salt = stackalloc byte[SaltBytes];
return ParseHash(text[..hash.Length], out char revision, out int cost, salt) && Prepare(password, salt, cost, revision, input);
}

/// <summary>The settings of a whole hash; false when it's malformed.</summary>
static bool ParseHash(ReadOnlySpan<char> hash, out char revision, out int cost, Span<byte> salt) =>
IsWholeHash(hash, ParseSettings(hash, out revision, out cost, salt));

internal static bool Prepare(ReadOnlySpan<char> password, ReadOnlySpan<byte> salt, int cost, char revision, BcryptPrehash prehash, Input* input)
{
if (!PrepareKey(password, revision, prehash, input->Key)) return false;
Expand All @@ -231,6 +244,24 @@ internal static bool Prepare(ReadOnlySpan<char> password, ReadOnlySpan<byte> sal
return true;
}

/// <summary><see cref="Prepare(ReadOnlySpan{char}, ReadOnlySpan{byte}, int, char, BcryptPrehash, Input*)"/> of a
/// password as bytes, taken as they are: false when they are over 72.</summary>
internal static bool Prepare(ReadOnlySpan<byte> password, ReadOnlySpan<byte> salt, int cost, char revision, Input* input)
{
if (password.Length > MaxPasswordBytes) return false;
Span<byte> key = stackalloc byte[MaxPasswordBytes + 1];
password.CopyTo(key);
int n = password.Length;
if (revision != '\0') key[n++] = 0;
StreamWords(key[..n], input->Key);
CryptographicOperations.ZeroMemory(key);
StreamWords(salt, input->Salt);
salt.CopyTo(new Span<byte>(input->SaltBytes, SaltBytes));
input->Cost = cost;
input->Revision = revision;
return true;
}

/// <summary>
/// The key's words: the password's UTF-8 and, except for "$2$", a terminating NUL. False when the UTF-8 is over
/// 72 bytes (bcrypt would ignore the rest) or the text isn't valid UTF-16. With a prehash the key is instead the
Expand Down Expand Up @@ -332,11 +363,13 @@ static int DigestInChunks(ReadOnlySpan<char> password, BcryptPrehash prehash, Sp
}
}

/// <summary>Why <see cref="Prepare"/> refused <paramref name="password"/>, for the exception.</summary>
/// <summary>Why <see cref="Prepare(ReadOnlySpan{char}, ReadOnlySpan{byte}, int, char, BcryptPrehash, Input*)"/> refused <paramref name="password"/>, for the exception.</summary>
internal static string RefusalOf(ReadOnlySpan<char> password) => IsValidUtf16(password)
? "bcrypt reads at most 72 UTF-8 bytes of a password; use an enhanced hash for longer ones"
? TooLong
: "the password isn't valid UTF-16: it has a lone surrogate";

internal const string TooLong = "bcrypt reads at most 72 UTF-8 bytes of a password; use an enhanced hash for longer ones";

static bool IsValidUtf16(ReadOnlySpan<char> text)
{
for (int i = 0; i < text.Length; i++)
Expand Down Expand Up @@ -421,15 +454,41 @@ internal static bool Matches(uint* c, ReadOnlySpan<char> stored)
return CryptographicOperations.FixedTimeEquals(MemoryMarshal.AsBytes(encoded), MemoryMarshal.AsBytes(stored));
}

/// <summary><see cref="Matches(uint*, ReadOnlySpan{char})"/> of a stored hash as ASCII bytes.</summary>
internal static bool Matches(uint* c, ReadOnlySpan<byte> stored)
{
Span<byte> hash = stackalloc byte[HashBytes];
HashBytesOf(c, hash);
Span<char> encoded = stackalloc char[HashChars];
Encode(hash, encoded);
Span<byte> ascii = stackalloc byte[HashChars];
for (int i = 0; i < HashChars; i++) ascii[i] = (byte)encoded[i];
return CryptographicOperations.FixedTimeEquals(ascii, stored);
}

/// <summary>The finished hash: "$2b$10$" + salt + hash, or "$2$10$" + ... for the original revision.</summary>
internal static string Format(Input* input, uint* c)
{
Span<char> s = stackalloc char[60];
Span<char> s = stackalloc char[HashLength];
return new string(s[..Format(input, c, s)]);
}

/// <summary>The finished hash as ASCII bytes; returns the length written.</summary>
internal static int Format(Input* input, uint* c, Span<byte> destination)
{
Span<char> s = stackalloc char[HashLength];
int n = Format(input, c, s);
for (int i = 0; i < n; i++) destination[i] = (byte)s[i];
return n;
}

static int Format(Input* input, uint* c, Span<char> s)
{
int at = WriteSettings(s, input->Revision, input->Cost, new ReadOnlySpan<byte>(input->SaltBytes, SaltBytes));
Span<byte> hash = stackalloc byte[HashBytes];
HashBytesOf(c, hash);
Encode(hash, s.Slice(at, HashChars));
return new string(s[..(at + HashChars)]);
return at + HashChars;
}

/// <summary>Writes "$2b$10$" + 22 salt characters; returns the length written.</summary>
Expand Down
44 changes: 44 additions & 0 deletions src/CodeFusion.Security.Bcrypt/Bcrypt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,40 @@ public static unsafe partial class Bcrypt
/// <summary>The longest password, in UTF-8 bytes, that bcrypt reads in full.</summary>
public const int MaxPasswordBytes = 72;

/// <summary>The length of a hash this library makes, in characters or ASCII bytes: "$2b$", the cost, "$", 22 salt
/// characters and 31 hash characters.</summary>
public const int HashLength = 60;

/// <summary>A new "$2b$" hash of <paramref name="password"/> with a random salt.</summary>
/// <exception cref="ArgumentException">The password is over 72 UTF-8 bytes or isn't valid UTF-16.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="cost"/> is outside 4 to 31.</exception>
public static string Hash(string password, int cost = DefaultCost) => Hash(password, cost, BcryptPrehash.None);

/// <summary>
/// A new "$2b$" hash of the password in <paramref name="passwordUtf8"/>, written to <paramref name="destination"/>
/// as ASCII. Allocates nothing. The bytes are the key as they are: UTF-8 gives the hash
/// <see cref="Hash(string, int)"/> gives the same text, and other bytes are taken too, as Go takes them. A NUL
/// counts, as in the string overloads; C implementations stop at the first one, so they won't verify such a hash.
/// </summary>
/// <returns>The bytes written: <see cref="HashLength"/>.</returns>
/// <exception cref="ArgumentException">The password is over 72 bytes, or <paramref name="destination"/> is shorter
/// than <see cref="HashLength"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="cost"/> is outside 4 to 31.</exception>
public static int Hash(ReadOnlySpan<byte> passwordUtf8, int cost, Span<byte> destination)
{
CheckCost(cost);
if (destination.Length < HashLength) throw new ArgumentException($"the destination must hold {HashLength} bytes", nameof(destination));
Input input;
Span<byte> salt = stackalloc byte[SaltBytes];
RandomNumberGenerator.Fill(salt);
if (!Prepare(passwordUtf8, salt, cost, 'b', &input)) throw new ArgumentException(TooLong, nameof(passwordUtf8));
uint* ct = stackalloc uint[6];
Run(&input, 1, ct);
int written = Format(&input, ct, destination);
Wipe(&input, 1);
return written;
}

/// <summary>
/// The hash of <paramref name="password"/> with the revision, cost and salt of <paramref name="salt"/>: a value
/// from <see cref="GenerateSalt"/>, or a whole hash.
Expand All @@ -48,6 +77,21 @@ public static unsafe partial class Bcrypt
/// over 72 UTF-8 bytes or not valid UTF-16, never matches. Never throws for any non-null input.</summary>
public static bool Verify(string password, string hash) => Verify(password, hash, BcryptPrehash.None);

/// <summary>
/// Whether the password in <paramref name="passwordUtf8"/> matches <paramref name="hash"/>, its ASCII bytes. As
/// <see cref="Verify(string, string)"/> for the UTF-8 of the same text; other bytes are taken as they are. A
/// malformed hash, or a password over 72 bytes, never matches. Allocates nothing and never throws.
/// </summary>
public static bool Verify(ReadOnlySpan<byte> passwordUtf8, ReadOnlySpan<byte> hash)
{
Input input;
if (!PrepareVerify(passwordUtf8, hash, &input)) return false;
uint* ct = stackalloc uint[6];
Run(&input, 1, ct);
Wipe(&input, 1);
return Matches(ct, hash[^HashChars..]);
}

/// <summary>
/// Checks <c>passwords[i]</c> against <c>hashes[i]</c> into <c>results[i]</c>, up to five at a time interleaved on
/// this thread: five checks take 1.3 to 2 times as long as one, depending on the CPU.
Expand Down
62 changes: 62 additions & 0 deletions src/CodeFusion.Security.Bcrypt/BcryptHash.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;

namespace CodeFusion.Security;

/// <summary>
/// A new bcrypt hash as its 60 ASCII bytes, held inline instead of in a string: what
/// <see cref="BcryptQueue.HashAsync(ReadOnlySpan{byte}, int, System.Threading.CancellationToken)"/> returns. Copy it
/// where it is stored with <see cref="CopyTo"/> or <see cref="TryFormat(Span{byte}, out int, ReadOnlySpan{char}, IFormatProvider?)"/>;
/// <see cref="ToString()"/> makes the string.
/// </summary>
public readonly struct BcryptHash : ISpanFormattable, IUtf8SpanFormattable
{
readonly Buffer _bytes;

internal BcryptHash(in Buffer bytes) => _bytes = bytes;

/// <summary><see cref="Bcrypt.HashLength"/>; 0 for <c>default</c>, which holds no hash.</summary>
public int Length => _bytes[0] == (byte)'$' ? Bcrypt.HashLength : 0;

/// <summary>The hash's ASCII bytes, read in place.</summary>
[UnscopedRef]
public ReadOnlySpan<byte> AsSpan() => ((ReadOnlySpan<byte>)_bytes)[..Length];

/// <summary>Copies the hash's ASCII bytes to the start of <paramref name="destination"/>.</summary>
/// <exception cref="ArgumentException"><paramref name="destination"/> is shorter than <see cref="Length"/>.</exception>
public void CopyTo(Span<byte> destination)
{
if (!AsSpan().TryCopyTo(destination)) throw new ArgumentException($"the destination must hold {Length} bytes", nameof(destination));
}

/// <summary>Writes the hash's ASCII bytes; false, writing nothing, when <paramref name="utf8Destination"/> is too short.</summary>
public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
bytesWritten = AsSpan().TryCopyTo(utf8Destination) ? Length : 0;
return bytesWritten == Length;
}

/// <summary>Writes the hash's characters; false, writing nothing, when <paramref name="destination"/> is too short.</summary>
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
charsWritten = 0;
if (destination.Length < Length) return false;
charsWritten = Encoding.ASCII.GetChars(AsSpan(), destination);
return true;
}

/// <summary>The hash as a string, "$2b$..."; empty for <c>default</c>.</summary>
public override string ToString() => Encoding.ASCII.GetString(AsSpan());

/// <inheritdoc cref="ToString()"/>
public string ToString(string? format, IFormatProvider? formatProvider) => ToString();

/// <summary>A hash's bytes, inline.</summary>
[InlineArray(Bcrypt.HashLength)]
internal struct Buffer
{
byte _first;
}
}
Loading
Loading