Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.
Improve DocC landing pages by mimicking Apple's CryptoKit docs
### Motivation:
Right now the DocC docs group all APIs by protocols, structures and
enums.
By adding a topics section in the landing page we can group them by type
("Ciphers", "Public key cryptography", etc.) exactly in the way Apple
does in [CryptoKit
docs](https://developer.apple.com/documentation/cryptokit/).
### Modifications:
- Fix DocC compilation errors in `_CryptoExtras`
- Add topics section in `_CryptoExtras` landing page
- Add topics section in `Crypto` landing page
### Result:
APIs will be grouped by type.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Fix FreeBSD support
### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
### Motivation:
To add FreeBSD support to Swift, we must ensure that swift crypto builds
on FreeBSD since it's a dependency of swiftpm and several essential
packages.
### Modifications:
- `Package.swift` - Ideally FreeBSD should use `.when(platforms:)` to
set the corresponding swift settings and dependencies. However,
`Platform.freebsd` is not yet available on swiftpm and therefore use
guard the settings behind a `isFreeBSD` boolean flag. This is chosen
because it minimize the diff and maintains the maximum readability.
- `cmake/modules/SwiftSupport.cmake` - add `amd64` arch support, maps to
`x86_64`.
- `**/CMakeLists.txt` - Use the Linux assembly files for FreeBSD. Both
Linux and FreeBSD uses SysV ABI, and there're no syscalls involved
(after all, they're supposed to be "pure") so there are no ABI
compatibility problem. After all, all the tests are passing on FreeBSD
with this PR.
### Result:
All the tests (via `swift test`) passed on x86_64 FreeBSD 14.1-p6, and
passed on aarch64 macOS.
Test log available here:
[swift-test-result.txt](https://github.com/user-attachments/files/18147920/swift-test-result.txt)
Fix DocC generation. Force Linux build on SPI to get it to render the
Crypto docs
### Motivation:
Currently the Crypto docs are empty on SPI because they're built on
macOS where there are no symbols. CryptoExtras index page also doesn't
work because of a name mismatch
### Modifications:
Force Linux build on SPI, fix name for extras documentation
### Result:
Working Docs
Adds some additional documentation. I don't know how far you want me to
go with documenting everything so let me know. This should at least get
the current APIs rendered on SPI. As an aside I'm not a huge fan of
linking out to the CryptoKit docs since not everything is available
here, all the code is already documented here and most of the tutorials
and articles on developer.apple.com for CryptoKit refer to Apple
Platform specific stuff, like interacting with the keychain, that is not
applicable here.
Resolves#273
### Checklist
- [x] I've run tests to see all new and existing tests pass
- [x] I've followed the code style of the rest of the project
- [x] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [x] I've updated the documentation if necessary
#### If you've made changes to `gyb` files
- [x] I've run `.script/generate_boilerplate_files_with_gyb` and
included updated generated files in a commit of this pull request
### Motivation:
Currently Swift Crypto has no documentation which is not great
### Modifications:
Adds additional DocC scaffolding to take advantage of the DocC comments
in Crypto and CryptoExtras. Adds an SPI config file for Swift Package
Index
### Result:
We will have some documentation
## Motivation
As part of the Github Actions CI migration we held off enabling the
format check and moving to the same formatting rules as Swift NIO, but
we'd like to do that now.
## Modifications
- Add a script to generate (and update) the `.swiftformatignore` file
since this repo only wants to format a specific set of files matching a
pattern.
- Generate and commit the `.swiftformatignore` file.
- Run the fomatter and commit the results.
- Additional commits to satisfy the remaining linter rules that weren't
auto-fixed by swift-format.
- Enable the format check in CI.
## Result
- Code that's not shared is formatted with a style consistent with the
other repos this team maintain.
- CI is now checking code format again.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
## Motivation
We would like to provide support for the P384-SHA384 Verifiable Oblivious Pseudorandom Function (VOPRF) as defined in [RFC 9497: VOPRF Protocol](https://www.rfc-editor.org/rfc/rfc9497.html#name-voprf-protocol).
## Modifications
- Add protocols for some "ECToolbox" abstractions: `Group`, `GroupElement`, `GroupScalar`, `HashToGroup`.
- Add implementations backed by BoringSSL.
- Duplicate some utilities from Crypto into _CryptoExtras: hexadecimal bytes and I2OSP.
- Add VOPRF API, rooted at `enum P384._VOPRF`.
## Results
- New internal abstractions that make it easier to bring up new implementations.
- New API for `OPRF(P-384, SHA-384)` in VOPRF mode.
## Tests
- Test vectors for internal `HashToField` implementation.
- Test vectors for internal VOPRF implementation.
- Tests of the VOPRF public API.
* Replaced potentially unexpected accesses to coordinate slices with consistent ranges no matter if the raw representation is a root or a slice of data
* Updated uses of `.suffix(from:)` with `.dropFirst()` to prevent issues with potential non-0 start indexes
Motivation:
I've added a proposed implementation of PBKDF2, as per proposal in issue #59 to allow easy creation of SymmetricKey from relatively low entropy data sets, such as user provided passwords.
Importance:
This API change is attempting to simplify the creation of SymmetricKeys from user entered passwords.
It uses an ageing algorithm – PBKDF2, but it is still widely supported and popular. A newer algorithm – scrypt is added as a better, more secure alternative.
Modifications:
I've proposed a new API: KDF namespace with Scrypt struct and an Insecure namespace with PBKDF2 struct with associated hash function and a single static method which takes a passphrase and salt, the size of the resulting key in bytes and optionally the number of rounds to use in the PBKDF2 algorithm.
In the case of scrypt algorithm there is no associated hash function due to the nature of the algorithm, the single static method takes passphrase and salt, the size of the resulting key in bytes and optionally: the number of rounds, block size and parallelism factor.
I implemented this functions using both CommonCrypto and BoringSSL where available.
The function names and parameters are heavily influenced by current HKDF implementation.
Additionally, I've added test cases to test the proposed API. I've decided to use test vectors described in RFC6070 for PBKDF2 and test vectors described in RFC7914 for scrypt.
Result:
This will add a new API to _CryptoKitExtras.
It follows the naming conventions from CryptoKit's HKDF implementation.
* wrapper: Remove _boring suffix from files in CryptoBoringWrapper
* wrapper: Move EC types and random bytes into CryptoBoringWrapper
* tests: Remove unused conditional compilation conditions in wrapper tests
* Support loading RSAPSS public keys with parameters
Parameters are stripped and the key is treated as a regular public key.
* address review + reset algorithm as well
* run update_cmakelists.sh
* attempt to fix the cmake build
* include FetchContent
* early return for non-PSS keys
* simplify code
This adds a _createFromNumbers API which creates an RSA key generating p and q primes based on n, e and d
Motivation:
There might be cases where private RSA keys have to be generated based on their raw elements (modulus n, exponent e and private exponent d) without p and q. These are random primes which are integral parts of the key but can be generated based on the former numbers, and are not always included when representing RSA keys, for example these parameters are not required in JWKs
Modifications:
This adds a static _createFromNumbers method which creates a new RSA key given its raw modulus, exponent and private exponent, generating the needed p and q primes without having to provide them as parameters. The algorithm to generate primes is based on a hybrid approach of the Miller Rabin primality test and the proof of Fact 1 in Dan Boneh's Twenty Years of Attacks on the RSA Cryptosystem paper. To write this algorithm, some additions had to be made to the ArbitraryPrecisionInteger
Result:
Private RSA keys can now be generated without providing p and q
Motivation:
At times we might need to get the raw elements of an RSA key, e.g when debugging.
Modifications:
Add a getKeyPrimitives method to the RSA (public and private) key structures that returns the elements.
To do this we leverage the built in BoringSSL methods (CCryptoBoringSSL_RSA_get0_n etc.) which return the raw elements of the key. In the Security version of the key we convert the key to a BoringSSL one and just call the BoringSSL method.
Once we get ASN.1 support in _CryptoExtras it might make sense switching the implementation of this method to decode the ASN.1 structure and returns the elements from there.
Result:
New APIs to fetch the key primitives.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
It is expected behavior of the swift-build build system to copy links as-is, so presenting these as symlinks results in broken symlinks being present in the produced resource bundles, which won't work properly.
On Windows, it even causes the build entirely to fail due to a related bug: https://github.com/apple/swift-foundation/issues/845
Convert these to flat files instead.
* Remove array allocation when computing digest
Instead of creating a temporary array, the digest bytes are stored in a temporary stack-allocated buffer.
This reduces the number of heap allocations needed to hash a message from 7 to 6.
* Store digest context inline
This reduces the number of heap allocations needed to hash a message from 6 to 2.
Before:
1. the DigestContext object is created
2. the EVP_MD_CTX struct is allocated by EVP_MD_CTX_new
3. md_data is allocated when initializing the context
After:
1. the DigestContext object is created
In both cases, the number is doubled because COW happens during finalize().
* Use temporary variable to finalize context
This reduces the number of heap allocations needed to hash a message from 2 to 1.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
* API for RSA blind signing and verification from RFC 9474
* Add blind signing backend for Security framework
* Hide PSSZERO variants from public API for now
* Update CMakeLists.txt
* Verify signature produced within SecurityRSAPrivateKey.blindSignature(_:)
* Update API: bake params into key, use wrappers for intermidiate values
* Throw specific error when message too large for key modulus
* Drop Security framework backend and support all variants
* Factor out withNewBignumContext helper
* Align parameter names and labels in internal functions with public API
* Fix typo in doc comments: public -> private
* Implement client operations for RSA Blind Signatures
* Remove the BlindedMessage type
* Move prepare function to public key method
* Throw (internal) errors defined in the RFC
* Fix test function names for Linux test discovery
* Factor saltLength into a computed property on Parameters
* Improve allocations for temporary bytes
* Fixup documentation typos
* Parameters are Sendable, regardless of H type parameter
* PublicKey and PrivateKey are also Sendable, regardless of H
* Wrap internal errors in most appropriate CryptoKitError
* Factor code differently
* Tweak API to return BlindingResult nominal type instead of tuple
* Prefer withUnsafeTemporaryAllocation(of:capacity:_:) to Array.init(unsafeUnitializedCapacity:_:)
* Move unsafe temporary allocations into BlindSigningHelpers methods
* Replace hand-rolled BN ops with ArbitraryPrecisionInteger and FFAC
* Fixup placement of paren in guards with closures
* Replace closure invocation let binding with looped var
* Use ERR_peek_last_error, not ERR_get_error
* Move ArbitraryPrecisionInteger_boring.swift to CryptoBoringWrapper
* Remove conditional compilation guards for ArbitraryPrecisionInteger
* Throw CryptoBoringWrapperError.internalBoringSSLError instead of CryptoKitError.internalBoringSSLError
* Make most operations public and add raw pointer APIs
* Move ArbitraryPrecisionIntegerTests to new CryptoBoringWrapperTests target
* rename some files
* Remove @_implementationOnly from imports and raw pointer APIs
* Also move over FiniteFieldArithmeticContext to CryptoBoringWrapper
* Add FiniteFieldArithmeticContext.inverse
* Remove conditional compilation guards for FFAC
* Update CMakeLists.txt for moved files
* Revert "Add FiniteFieldArithmeticContext.inverse"
This reverts commit e02700e07c.
* Fix CMakeLists.txt
* Make most public symbols @inlinable
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation
Add Sendable annotations to Crypto Extras to reflect current sandability
so that downstream packages can implement sendable conformance.
Modifications
* Add Sendable conformance to some missed public symbols.
* RSA public and private keys are now marked sendable with their backing storage on darwin OS marked unchecked sendable until SecKey from security framework has sendability annotations
Result
* More accurate Sendable annotations
Motivation
Add Sendable annotations to Crypto Extras to reflect current sandability
so that downstream packages can implement sendable conformance.
Modifications
* Add Sendable conformance to appropriate public symbols.
* RSA public and private keys are notable omissions, this is because
they are backed by SecKey from security framework and we have no
guarantees about their sendability
Result
* Accurate Sendable annotations
Motivation:
As described in #209, I personally need this to migrate an oracle driver from a third party crypto lib to swift-crypto. I think other users might benefit from this addition too.
Modifications:
I've added an overload to the encrypt and decrypt methods of AES._CBC, allowing the user to configure if padding should be added or not. With noPadding set to true, an error will be thrown if the plaintext isn't a multiple of the block size. I've added the corresponding inline documentation.
I've also added tests to ensure both encrypting and decrypting without padding work as expected. Although those tests might not be sufficient enough, because I couldn't find good resources online. I've created a bunch of random hex strings and encrypted/decrypted them using another implementation of paddingless CBC and checked if I receive the expected results. To further validate the feature, I've tested it as part of the authentication in oracle-nio, which worked in all test scenarios I've been running.
Result:
After merging this, it will be possible to use CBC without padding. This closes#209
Motivation
Add RSA OAEP-sha256 support in addition to the increasingly aged SHA-1
implementation.
Modifications
* Add a `Digest` enum to `_RSA.Encryption.Padding`
* Add a digest associated type to the `.pkcs1_oaep` padding enum case
to allow us to distinguish different digest hash functions.
* Add a `PKCS1_OAEP_SHA256` public static let to allow users to use the
new hash function.
* Enable SHA-256 RSA encryption tests
Result
* Support for RSA OAEP-sha256
Motivation
Increased versatility of the `BoringSSLRSAPublicKey` encrypt and decrypt
methods to make future extensions possible.
Modifications
Switch the `BoringSSLRSAPublicKey` encrypt and decrypt methods to use
the `EVP_PKEY_*` API directly rather than going through the RSA
abstractions.
Result
Increased versatility of the `BoringSSLRSAPublicKey` encrypt and decrypt
methods.