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.
* 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.
# Motivation
We want to support AES-CBC for encryption and decryption purposes.
# Modification
This PR adds support AES-CBC. Furthermore, it adds wycheproof tests for it.
* Add basic RSA encrypt/decrypt API.
* Add test vectors and tests for RSA encryption API
* Fix build failures
* Fix soundness issue
* Remove support for RSA encryption using the unsafe PKCS1 v1.5 padding
* Fix deprecation warning about the "pointer" version of Data.withUnsafeMutableBytes() by nudging the compiler to infer the "buffer" version.
* Fix deprecation warning about String.init(bytesNoCopy:length:freeWhenDone:) by using String.init(unsafeInitializedCapacity:initializingWith:) instead.
* Make _RSA.Encryption.[Public|Private]Key their own types
* Remove _RSA.Encryption.RSA[Encrypted|Decrypted]Data and just use Data directly. Don't use intermediate Array in BoringSSL implementations.
* Document the message size limits on RSA encrypt/decrypt operations
* Mark `_RSA` visible to documentation so the new docs can actually be seen (underscored name is assumed private by default)
* Fix generic type parameter shadowing warning (new warning in Swift 5.9)
* Fix pre-5.8 build
* Un-correct switch case indentation to make it wrong
* OpenSSLChaCha20CTR Implementation. Wraps CCryptoBoringSSL_CRYPTO_chacha_20.
* Insecure extension implementing the ChaCha20 CTR encrypt method.
* Added ChaCha20CTR Tests based on vectors provided in RFC9001 Appendix A.5
* Corrected year in header
* Changed return type to Data. Removed redundant pointer castings. Removed unnecessary array allocations in favor of withUnsafeBytes.
* Introduced a typed ChaCha20CTR Nonce and Counter struct in order to help enforce parameter constraints and type safety.
* Formatting
* Updated tests to use new Nonce and Counter structs. Added additional test checking for invalid parameters.
* Switch to HexStrings for better readability.
* Removed empty line at top of file
* Fixed UInt32.max counter assertion.
* Moved the bindMemory calls out of the function and copied a note from a similar situation elsewhere in the codebase.
* Formatting
* Implemented an _encryptContiguous function that prevents having to use the withContiguousStorageIfAvailable method. If our DataProtocol is contiguous we encrypt directly, otherwise we consolidate before encrypting. Removed inLen param from chacha20CTR call.
* Replaced the chacha20CTR function with a direct call to CCryptoBoringSSL_CRYPTO_chacha_20.
* Counter is now backed by a UInt32 instead of Data. Removed Sequence conformance.
* Formatting
* Formatting
* Replaced unsafe code (unsafeBytes and load) with a more generic and safer UInt32 construction.
* Replaced counterAsUInt32 definitions with integer literals to avoid symmetric bugs in the load.
* Updated _CryptoExtras/CMakeList.txt
* Exclude AES from CMake
SwiftPM doesn't need it and this would allow removal of CCryptoBoringSSL dependency on non-Darwin platforms, thus reducing SwiftPM size.
* Update update_cmakelists.sh to exclude AES source files
Motivation
CryptoExtras RSA public keys support being exported in DER and PEM form.
These exports work great, but it turns out they are inconsistent between
the Darwin and non-Darwin implementations. Darwin platforms would export
the public keys in PKCS1 format, while non-Darwin was exporting them as
SPKI. This isn't great!
Modifications
- Make the two consistent. `.derRepresentation` should export SPKI
formatted public keys, because that's what it does for all the EC
keys.
- Add `.pkcs1DERRepresentation` and `.pkcs1PEMRepresentation` for those
users that require the PKCS1 formatted key.
Result
Key export types are now consistent on all platforms.
In some cases developers have need of AES modes other than what we
support today, or need the ability to implement algorithms that require
access to the core AES permutation function. As a starting point, we can
provide access to the AES block function in CryptoExtras.
Motivation
The init(derRepresentation:) and init(pemRepresentation:) constructors
for RSA public keys support both PKCS#8 and PKCS#1 key formats on
Darwin. This support was missing from Linux, with only PKCS#8 support.
This patch brings the two platforms into parity.
Modifications
Add code to try both versions on Linux.
Add tests.
Results
PKCS#1 keys are supported on Linux too!
# Motivation
BoringSSL exposes AES-GCM-SIV algorithms which are in general useful to have and provide a nonce-misuse resistant mode of AES-GCM. Since, `CryptoKit` is not exposing AES-GCM-SIV we need to add this to `_CryptoExtras`
# Modification
Exposes `AES-GCM-SIV` through `_CryptoExtras`.
# Result
We can now use `AES-GCM-SIV` through `_CryptoExtras`.
Motivation:
I couldn't build for Android armv7 on the CI I set up without this.
Modifications:
Initialize with the right size of UInt to BoringSSL.
Result:
I can build for armv7 again.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Some critical use-cases require RSA signing support. This is most
commonly required when interacting with legacy systems. While RSA is an
older and less efficient cryptosystem than the elliptic-curve algorithms
supported by Swift Crypto already, those interop use-cases are
unavoidable.
This version of the patch does not promote RSA to supported API at this
time, as we'd like to let the API bake somewhat. Users are free to use
it, but these APIs are not covered by semantic versioning at this time
and may break in future.
Modifications:
- Defined new RSA API
- Implemented on top of `Security` when available
- Implemented on top of BoringSSL when `Security` is unavailable
Result:
Users can do RSA if needed.