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
7 changes: 3 additions & 4 deletions .github/workflows/benchmark.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
configuration: [release, debug]
include:
- os: ubuntu-latest
container: swiftlang/swift:nightly-6.4.x-noble
container: swift:6.4-noble

steps:
- name: Install dependencies (Linux)
Expand All @@ -47,9 +47,8 @@ jobs:
- name: Install Swift (macOS)
if: ${{ runner.os == 'macOS' }}
run: |
# Neither vapor/swiftly-action (Linux package managers only) nor swift-actions/setup-swift
# (hardcoded version table, no 6.4 yet) can install 6.4 on macOS, so drive swiftly directly:
# https://www.swift.org/install/macos/
# vapor/swiftly-action only supports Linux package managers and swift-actions/setup-swift's
# hardcoded version table still lacks 6.4, so drive swiftly directly (https://www.swift.org/install/macos/).
curl -sSL https://download.swift.org/swiftly/darwin/swiftly.pkg -o "${RUNNER_TEMP}/swiftly.pkg"
installer -pkg "${RUNNER_TEMP}/swiftly.pkg" -target CurrentUserHomeDirectory
~/.swiftly/bin/swiftly init --assume-yes --skip-install --no-modify-profile --quiet-shell-followup
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/fuzz.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
name: ${{ matrix.target }}
runs-on: ubuntu-latest
timeout-minutes: 40
container: swiftlang/swift:nightly-6.4.x-noble
container: swift:6.4-noble
strategy:
fail-fast: false
matrix:
Expand Down
32 changes: 21 additions & 11 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,25 @@ on:
branches: [main]

jobs:
unit-tests-linux:
name: Unit tests (Linux)
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main
test:
name: test
uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.15
with:
linux_swift_versions: '["nightly-6.4.x"]'
linux_swift_versions: '["6.4"]'
linux_os_versions: '["noble"]'
enable_macos_checks: false
enable_windows_checks: false
enable_linux_static_sdk_build: true
linux_static_sdk_versions: '["6.4"]'
enable_wasm_sdk_build: true
wasm_sdk_versions: '["6.4"]'
enable_embedded_wasm_sdk_build: true
enable_android_sdk_build: true
android_sdk_versions: '["6.4"]'
# enable_macos_checks: true
# macos_xcode_versions: '["swift_6.4"]'
# enable_ios_checks: true
# ios_host_xcode_versions: '["swift_6.4"]'
enable_windows_checks: true
windows_swift_versions: '["nightly-6.4.x"]'

unit-tests-macos:
name: Unit tests (macOS)
Expand All @@ -27,9 +38,6 @@ jobs:
steps:
- name: Install Swift
run: |
# Neither vapor/swiftly-action (Linux package managers only) nor swift-actions/setup-swift
# (hardcoded version table, no 6.4 yet) can install 6.4 on macOS, so drive swiftly directly:
# https://www.swift.org/install/macos/
curl -sSL https://download.swift.org/swiftly/darwin/swiftly.pkg -o "${RUNNER_TEMP}/swiftly.pkg"
installer -pkg "${RUNNER_TEMP}/swiftly.pkg" -target CurrentUserHomeDirectory
~/.swiftly/bin/swiftly init --assume-yes --skip-install --no-modify-profile --quiet-shell-followup
Expand All @@ -40,7 +48,7 @@ jobs:
echo "${SWIFTLY_BIN_DIR}" >> "${GITHUB_PATH}"
swift --version
- name: Check out code
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Build
run: swift build
- name: Test
Expand All @@ -52,7 +60,9 @@ jobs:
with:
format_check_enabled: true
api_breakage_check_enabled: true
api_breakage_check_container_image: "swiftlang/swift:nightly-6.4.x-noble"
api_breakage_check_container_image: "swift:6.4-noble"
# Intentional pre-1.0 breaks; entries are removed once the next tag becomes the baseline.
api_breakage_check_allowlist_path: ".api-breakage-allowlist.txt"
docs_check_enabled: false
docs_check_analyze: false
docs_check_macos_analyze: false
Expand Down
65 changes: 65 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,68 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--------------------------------------------------------------------------------

Third-party notices

This package is a Swift port of the bcrypt password hashing implementation
and Blowfish block cipher from OpenBSD (lib/libc/crypt/bcrypt.c,
lib/libc/crypt/blowfish.c, include/blf.h). The original copyright and
permission notices are reproduced below, as their licenses require.

bcrypt.c
--------

Copyright (c) 2014 Ted Unangst <tedu@openbsd.org>
Copyright (c) 1997 Niels Provos <provos@umich.edu>

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

This password hashing algorithm was designed by David Mazieres
<dm@lcs.mit.edu>.

blowfish.c, blf.h
-----------------

Blowfish block cipher for OpenBSD
Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
All rights reserved.

Implementation advice by David Mazieres <dm@lcs.mit.edu>.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The Blowfish code is derived from section 14.3 and the given source in
section V of Applied Cryptography, second edition. Blowfish is an
unpatented fast block cipher designed by Bruce Schneier.
48 changes: 44 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ A native, dependency and Foundation free Swift implementation of the bcrypt pass
## Installation

```swift
.package(url: "https://github.com/ptoffy/bcrypt.git", branch: "main")
.package(url: "https://github.com/ptoffy/bcrypt.git", branch: "0.4.0")
```

```swift
Expand All @@ -19,9 +19,12 @@ import Bcrypt

let password = "password"
let hash = try Bcrypt.hash(password: password)
let isValid = try Bcrypt.verify(password: password, hash: hash)
let isValid = try Bcrypt.verify(password: password, against: hash)
```

> [!NOTE]
> Hashing passwords longer than 72 characters will result in a `.passwordTooLong` error, whereas verifying them will result in the excess characters being ignored.

## Performance

Benchmarks for hashing the password "password" at cost factor 12 using the
Expand All @@ -34,9 +37,46 @@ func hash(
into output: inout OutputSpan<UInt8>
) throws(BcryptError)
```
API, compared to Vapor's C bcrypt ([vapor/authentication](https://github.com/vapor/authentication)), measured on an Apple M5 Pro with the [benchmark](https://github.com/ordo-one/benchmark) package.
API, compared to Vapor's C bcrypt ([vapor/authentication](https://github.com/vapor/authentication)) and the Rust [bcrypt](https://crates.io/crates/bcrypt) crate, measured on an Apple M5 Pro. The Swift rows use the [benchmark](https://github.com/ordo-one/benchmark) package; the Rust row uses `bcrypt::hash` (the `String`-returning API) in a plain timing loop with a counting global allocator, `lto = true` and `codegen-units = 1` for release.

| | Release ms | Debug ms | Allocations Release | Allocations Debug |
|------|------------|----------|---------------------|-------------------|
| vapor/authentication | 170ms | 270ms | 11 | 181 |
| bcrypt | 149ms | 440ms | 0 | 0 |
| vapor/authentication | 170ms | 270ms | 11 | 181 |
| bcrypt (Rust 0.17) | 170ms | 650ms | 7 | 7 |

## Security Information

### Versions

A bcrypt hash starts with a version prefix, chosen with the `version` parameter when hashing. All three compute exactly the same hash from the same password and salt; they differ only in the prefix and in how passwords longer than 72 bytes are treated.

| Prefix | `BcryptVersion` | Origin | Passwords over 72 bytes |
|--------|-----------------|--------|-------------------------|
| `$2b$` | `.v2b` (default) | OpenBSD, 2014 | Rejected with `passwordTooLong` |
| `$2y$` | `.v2y` | PHP `password_hash`, Apache `htpasswd` | Rejected with `passwordTooLong` |
| `$2a$` | `.v2a` | Original 1999 revision | Silently truncated |

`verify` accepts any of the three and keeps the prefix. Use the default unless you need to emit hashes for a system that only accepts a specific prefix.

### Cost

The cost is the base-2 logarithm of the number of key schedule rounds, so every increment doubles the time to hash and to verify. It ranges from 4 to 31; on an Apple M5 Pro in release builds:

| Cost | Time |
|------|------|
| 4 | ~0.6 ms |
| 10 (default) | ~37 ms |
| 12 | ~150 ms |
| 14 | ~600 ms |
| 31 | ~22 hours |

At this time 12 is considered a reasonable default cost factor for balancing security and performance. The cost is stored on the hash so verification of old hashes continues to work even if the default cost is increased in the future.

### RNG

Bcrypt relies on a secure random number generator (RNG) to generate salts for hashing passwords. This package currently uses `SystemRandomNumberGenerator`.

### Zeroization

Zeroization is the process of securely erasing sensitive data from memory, usually by overwriting it with zeros or random data before deallocating the memory. After using it, bcrypt zeroizes the key state which is derived from the password to ensure that no sensitive information remains in memory. The password itself is never copied so wiping it is the caller's responsibility.
8 changes: 8 additions & 0 deletions Sources/Bcrypt/Base64.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
// Ported from OpenBSD's bcrypt implementation (lib/libc/crypt/bcrypt.c).
// Copyright (c) 2014 Ted Unangst <tedu@openbsd.org>, Copyright (c) 1997 Niels Provos <provos@umich.edu>.
// Redistributed under the ISC license; the full notice is reproduced in LICENSE.

@usableFromInline
enum Base64Error: Error {
case invalidCharacter
Expand Down Expand Up @@ -119,6 +123,10 @@ struct Base64 {
}

c4 = char64(of: s[off])
if c4 == UInt8.max {
throw .invalidCharacter
}

off &+= 1
o = (c3 & 0x03) &<< 6
o |= c4
Expand Down
47 changes: 47 additions & 0 deletions Sources/Bcrypt/Bcrypt.swift
Original file line number Diff line number Diff line change
@@ -1 +1,48 @@
/// A native Swift implementation of the bcrypt password hashing function.
///
/// bcrypt derives a key from a password and a 128-bit salt with the EksBlowfish key schedule, whose cost
/// grows exponentially with the `cost` parameter, and encodes the result as a 60-character modular crypt
/// string:
///
/// ```
/// $2b$12$R9h/cIPz0gi.URNNX3kh2OPST9/PgBkqquzi.Ss7KIUgO2t0jWMUW
/// \__/\/ \____________________/\_____________________________/
/// Alg Cost Salt Hash
/// ```
///
/// Use ``hash(password:cost:version:)-(String,_,_)`` to hash a new password with a random salt, and
/// ``verify(password:against:)-(String,_)`` to check a password against a stored hash. Both have overloads
/// for `[UInt8]` and `Span<UInt8>`; the `Span` overloads and
/// ``hash(password:cost:salt:version:into:)`` do not allocate.
///
/// ## Password length
///
/// bcrypt only keys on the first 72 bytes of the password (UTF-8 bytes), so anything past
/// that is not considered. To make sure no password is silently weakened, `hash` throws
/// ``BcryptError/passwordTooLong`` for longer inputs when creating ``BcryptVersion/v2b`` or
/// ``BcryptVersion/v2y`` hashes. `verify` instead truncates to 72 bytes, as OpenBSD, PHP and most other
/// implementations do when hashing, so hashes created elsewhere from longer passwords keep verifying.
///
/// A trailing NUL byte in the password is treated as the C string terminator and not counted twice.
/// An empty password is rejected with ``BcryptError/emptyPassword``.
///
/// ## Cost
///
/// `cost` is the base-2 logarithm of the number of key schedule rounds and must be between 4 and 31.
/// Each increment doubles the time to hash and to verify; cost 12 takes around 150 ms on an Apple M5 Pro.
/// The default of 10 matches other implementations; 12 or more is recommended for new deployments.
///
/// ## Salts and randomness
///
/// Salts are 16 random bytes from `SystemRandomNumberGenerator`, which is backed by the platform's
/// cryptographic random source. Callers that supply their own salt must pass the 22-character
/// bcrypt-base64 encoding; the trailing bits that do not fit into 16 bytes are ignored and the salt
/// is re-encoded in the output.
///
/// ## Timing
///
/// Verification compares the full recomputed hash against the stored one without early exit. Malformed
/// hashes are rejected before any key schedule work is done, so invalid input costs nothing. The expanded
/// Blowfish state is zeroed after each hash; the password itself is never copied, so clearing it is the
/// caller's responsibility.
public enum Bcrypt: Sendable {}
12 changes: 11 additions & 1 deletion Sources/Bcrypt/BcryptError.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
public enum BcryptError: Error {
/// An error thrown by ``Bcrypt`` when a password, salt or hash cannot be processed.
@nonexhaustive public enum BcryptError: Error {
/// A caller-supplied salt is not exactly 22 characters long.
case invalidSaltLength
/// A caller-supplied salt contains a character outside the bcrypt-base64 alphabet (`./A-Za-z0-9`).
case invalidSalt
/// The hash passed to `verify` is not 60 characters long or does not have the `$2x$nn$` prefix layout.
case invalidHash
/// The password is empty.
case emptyPassword
/// The cost is outside the range 4...31, or the two cost digits in a hash are not decimal digits.
case invalidCost
/// The password is longer than 72 bytes and the version is ``BcryptVersion/v2b`` or ``BcryptVersion/v2y``.
///
/// Only thrown when creating a hash; `verify` truncates instead, see ``Bcrypt``.
case passwordTooLong
/// The hash passed to `verify` starts with a version prefix other than `$2a$`, `$2b$` or `$2y$`.
case invalidVersion
}
23 changes: 21 additions & 2 deletions Sources/Bcrypt/BcryptVersion.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
/// The variant identifier written at the start of a bcrypt hash.
///
/// All three variants compute the same hash from the same password and salt; they differ only in the
/// prefix and in how over-long passwords are treated. `verify` accepts any of them and preserves the
/// prefix, so a hash created with one variant round-trips unchanged.
public enum BcryptVersion: Equatable, Sendable {
/// `$2a$`, the original 1999 revision.
///
/// Passwords longer than 72 bytes are truncated rather than rejected, for compatibility with hashes
/// created by implementations that predate the length check.
case v2a
/// `$2b$`, OpenBSD's 2014 revision and the default.
///
/// Passwords longer than 72 bytes are rejected with ``BcryptError/passwordTooLong`` when hashing.
case v2b
/// `$2y$`, the prefix used by PHP's `password_hash` and Apache `htpasswd`.
///
/// Identical to ``v2b`` in every respect other than the prefix.
case v2y

@usableFromInline
var majorVersion: UInt8 {
switch self {
case .v2a, .v2b: 0x32
case .v2a, .v2b, .v2y: 0x32
}
}

Expand All @@ -14,6 +30,7 @@ public enum BcryptVersion: Equatable, Sendable {
switch self {
case .v2a: 0x61
case .v2b: 0x62
case .v2y: 0x79
}
}

Expand All @@ -27,12 +44,14 @@ public enum BcryptVersion: Equatable, Sendable {
guard identifier.count == 4 else { return nil }
switch (identifier[0], identifier[1], identifier[2], identifier[3]) {
case (0x24, 0x32, 0x61, 0x24): self = .v2a
case (0x24, 0x32, 0x62, 0x24), (0x24, 0x32, 0x79, 0x24): self = .v2b // 2y is an alias for 2b
case (0x24, 0x32, 0x62, 0x24): self = .v2b
case (0x24, 0x32, 0x79, 0x24): self = .v2y
default: return nil
}
}
}

extension UInt8 {
@usableFromInline
static let separator: UInt8 = 0x24 // $
}
4 changes: 4 additions & 0 deletions Sources/Bcrypt/Blowfish+InitialState.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
// Ported from OpenBSD's Blowfish implementation (lib/libc/crypt/blowfish.c, include/blf.h).
// Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>. All rights reserved.
// Redistributed under the BSD-3-Clause license; the full notice is reproduced in LICENSE.

extension EksBlowfish {
@usableFromInline
@inline(__always)
Expand Down
Loading
Loading