mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Enable swift-format in CI (#302)
## 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>
This commit is contained in:
42 files changed
+1704
-506
No files matched your search
@@ -10,7 +10,6 @@ jobs:
|
||||
uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main
|
||||
with:
|
||||
license_header_check_project_name: "SwiftCrypto"
|
||||
format_check_enabled: false
|
||||
docs_check_enabled: false
|
||||
|
||||
cmake-lists:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
**/.gitignore
|
||||
.licenseignore
|
||||
.unacceptablelanguageignore
|
||||
.swiftformatignore
|
||||
.gitattributes
|
||||
.git-blame-ignore-revs
|
||||
.mailfilter
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"version" : 1,
|
||||
"indentation" : {
|
||||
"spaces" : 4
|
||||
},
|
||||
"tabWidth" : 4,
|
||||
"fileScopedDeclarationPrivacy" : {
|
||||
"accessLevel" : "private"
|
||||
},
|
||||
"spacesAroundRangeFormationOperators" : false,
|
||||
"indentConditionalCompilationBlocks" : false,
|
||||
"indentSwitchCaseLabels" : false,
|
||||
"lineBreakAroundMultilineExpressionChainComponents" : false,
|
||||
"lineBreakBeforeControlFlowKeywords" : false,
|
||||
"lineBreakBeforeEachArgument" : true,
|
||||
"lineBreakBeforeEachGenericRequirement" : true,
|
||||
"lineLength" : 120,
|
||||
"maximumBlankLines" : 1,
|
||||
"respectsExistingLineBreaks" : true,
|
||||
"prioritizeKeepingFunctionOutputTogether" : true,
|
||||
"rules" : {
|
||||
"AllPublicDeclarationsHaveDocumentation" : false,
|
||||
"AlwaysUseLiteralForEmptyCollectionInit" : false,
|
||||
"AlwaysUseLowerCamelCase" : false,
|
||||
"AmbiguousTrailingClosureOverload" : true,
|
||||
"BeginDocumentationCommentWithOneLineSummary" : false,
|
||||
"DoNotUseSemicolons" : true,
|
||||
"DontRepeatTypeInStaticProperties" : true,
|
||||
"FileScopedDeclarationPrivacy" : true,
|
||||
"FullyIndirectEnum" : true,
|
||||
"GroupNumericLiterals" : true,
|
||||
"IdentifiersMustBeASCII" : true,
|
||||
"NeverForceUnwrap" : false,
|
||||
"NeverUseForceTry" : false,
|
||||
"NeverUseImplicitlyUnwrappedOptionals" : false,
|
||||
"NoAccessLevelOnExtensionDeclaration" : true,
|
||||
"NoAssignmentInExpressions" : true,
|
||||
"NoBlockComments" : true,
|
||||
"NoCasesWithOnlyFallthrough" : true,
|
||||
"NoEmptyTrailingClosureParentheses" : true,
|
||||
"NoLabelsInCasePatterns" : true,
|
||||
"NoLeadingUnderscores" : false,
|
||||
"NoParensAroundConditions" : true,
|
||||
"NoVoidReturnOnFunctionSignature" : true,
|
||||
"OmitExplicitReturns" : true,
|
||||
"OneCasePerLine" : true,
|
||||
"OneVariableDeclarationPerLine" : true,
|
||||
"OnlyOneTrailingClosureArgument" : true,
|
||||
"OrderedImports" : true,
|
||||
"ReplaceForEachWithForLoop" : true,
|
||||
"ReturnVoidInsteadOfEmptyTuple" : true,
|
||||
"UseEarlyExits" : false,
|
||||
"UseExplicitNilCheckInConditions" : false,
|
||||
"UseLetInEveryBoundCaseVariable" : false,
|
||||
"UseShorthandTypeNames" : true,
|
||||
"UseSingleLinePropertyGetter" : false,
|
||||
"UseSynthesizedInitializer" : false,
|
||||
"UseTripleSlashForDocumentationComments" : true,
|
||||
"UseWhereClausesInForLoops" : false,
|
||||
"ValidateDocumentationComments" : false
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
# file options
|
||||
|
||||
--swiftversion 5.4
|
||||
--exclude .build
|
||||
|
||||
# format options
|
||||
|
||||
--self insert
|
||||
--patternlet inline
|
||||
--stripunusedargs unnamed-only
|
||||
--ifdef no-indent
|
||||
|
||||
# rules
|
||||
@@ -0,0 +1,141 @@
|
||||
Package.swift
|
||||
Sources/Crypto/AEADs/AES/GCM/AES-GCM.swift
|
||||
Sources/Crypto/AEADs/ChachaPoly/ChaChaPoly.swift
|
||||
Sources/Crypto/AEADs/Cipher.swift
|
||||
Sources/Crypto/AEADs/Nonces.swift
|
||||
Sources/Crypto/ASN1/ASN1.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Any.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1BitString.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Boolean.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Identifier.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Integer.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Null.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1OctetString.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ASN1Strings.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/GeneralizedTime.swift
|
||||
Sources/Crypto/ASN1/Basic ASN1 Types/ObjectIdentifier.swift
|
||||
Sources/Crypto/ASN1/ECDSASignature.swift
|
||||
Sources/Crypto/ASN1/PEMDocument.swift
|
||||
Sources/Crypto/ASN1/PKCS8PrivateKey.swift
|
||||
Sources/Crypto/ASN1/SEC1PrivateKey.swift
|
||||
Sources/Crypto/ASN1/SubjectPublicKeyInfo.swift
|
||||
Sources/Crypto/CryptoKitErrors.swift
|
||||
Sources/Crypto/Digests/Digest.swift
|
||||
Sources/Crypto/Digests/Digests.swift
|
||||
Sources/Crypto/Digests/HashFunctions.swift
|
||||
Sources/Crypto/Digests/HashFunctions_SHA2.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-AEAD.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-Ciphersuite.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-KDF.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-KexKeyDerivation.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-LabeledExtract.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/HPKE-Utils.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/DHKEM.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-KEM-Curve25519.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/KEM/Conformances/HPKE-NIST-EC-KEMs.swift
|
||||
Sources/Crypto/HPKE/Ciphersuite/KEM/HPKE-KEM.swift
|
||||
Sources/Crypto/HPKE/HPKE-Errors.swift
|
||||
Sources/Crypto/HPKE/HPKE.swift
|
||||
Sources/Crypto/HPKE/Key Schedule/HPKE-Context.swift
|
||||
Sources/Crypto/HPKE/Key Schedule/HPKE-KeySchedule.swift
|
||||
Sources/Crypto/HPKE/Modes/HPKE-Modes.swift
|
||||
Sources/Crypto/Insecure/Insecure.swift
|
||||
Sources/Crypto/Insecure/Insecure_HashFunctions.swift
|
||||
Sources/Crypto/KEM/KEM.swift
|
||||
Sources/Crypto/Key Agreement/DH.swift
|
||||
Sources/Crypto/Key Agreement/ECDH.swift
|
||||
Sources/Crypto/Key Derivation/HKDF.swift
|
||||
Sources/Crypto/Key Wrapping/AESWrap.swift
|
||||
Sources/Crypto/Keys/EC/Curve25519.swift
|
||||
Sources/Crypto/Keys/EC/Ed25519Keys.swift
|
||||
Sources/Crypto/Keys/EC/NISTCurvesKeys.swift
|
||||
Sources/Crypto/Keys/EC/X25519Keys.swift
|
||||
Sources/Crypto/Keys/Symmetric/SymmetricKeys.swift
|
||||
Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift
|
||||
Sources/Crypto/Message Authentication Codes/MACFunctions.swift
|
||||
Sources/Crypto/Message Authentication Codes/MessageAuthenticationCode.swift
|
||||
Sources/Crypto/PRF/AES.swift
|
||||
Sources/Crypto/Signatures/ECDSA.swift
|
||||
Sources/Crypto/Signatures/Ed25519.swift
|
||||
Sources/Crypto/Signatures/Signature.swift
|
||||
Sources/Crypto/Util/PrettyBytes.swift
|
||||
Sources/Crypto/Util/SafeCompare.swift
|
||||
Sources/Crypto/Util/SecureBytes.swift
|
||||
Sources/Crypto/Util/Zeroization.swift
|
||||
Sources/_CryptoExtras/AES/AES_CBC.swift
|
||||
Sources/_CryptoExtras/AES/AES_CFB.swift
|
||||
Sources/_CryptoExtras/AES/AES_CTR.swift
|
||||
Sources/_CryptoExtras/AES/AES_GCM_SIV.swift
|
||||
Sources/_CryptoExtras/AES/Block Function.swift
|
||||
Sources/_CryptoExtras/ChaCha20CTR/ChaCha20CTR.swift
|
||||
Sources/_CryptoExtras/ECToolbox/ECToolbox.swift
|
||||
Sources/_CryptoExtras/H2G/HashToField.swift
|
||||
Sources/_CryptoExtras/Key Derivation/KDF.swift
|
||||
Sources/_CryptoExtras/Key Derivation/PBKDF2/PBKDF2.swift
|
||||
Sources/_CryptoExtras/Key Derivation/Scrypt/Scrypt.swift
|
||||
Sources/_CryptoExtras/OPRFs/OPRF.swift
|
||||
Sources/_CryptoExtras/OPRFs/OPRFClient.swift
|
||||
Sources/_CryptoExtras/OPRFs/OPRFServer.swift
|
||||
Sources/_CryptoExtras/OPRFs/VOPRF+API.swift
|
||||
Sources/_CryptoExtras/OPRFs/VOPRFClient.swift
|
||||
Sources/_CryptoExtras/OPRFs/VOPRFServer.swift
|
||||
Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift
|
||||
Sources/_CryptoExtras/RSA/RSA.swift
|
||||
Sources/_CryptoExtras/RSA/RSA_security.swift
|
||||
Sources/_CryptoExtras/Util/BoringSSLHelpers.swift
|
||||
Sources/_CryptoExtras/Util/DigestType.swift
|
||||
Sources/_CryptoExtras/Util/Error.swift
|
||||
Sources/_CryptoExtras/Util/I2OSP.swift
|
||||
Sources/_CryptoExtras/Util/PEMDocument.swift
|
||||
Sources/_CryptoExtras/Util/PrettyBytes.swift
|
||||
Sources/_CryptoExtras/Util/SubjectPublicKeyInfo.swift
|
||||
Sources/_CryptoExtras/ZKPs/DLEQ.swift
|
||||
Sources/crypto-shasum/main.swift
|
||||
Tests/CryptoTests/ASN1/ASN1Tests.swift
|
||||
Tests/CryptoTests/ASN1/GeneralizedTimeTests.swift
|
||||
Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift
|
||||
Tests/CryptoTests/Authenticated Encryption/ChaChaPoly-Runner.swift
|
||||
Tests/CryptoTests/Digests/DigestsTests.swift
|
||||
Tests/CryptoTests/ECDH/X25519-Runner.swift
|
||||
Tests/CryptoTests/ECDH/secpECDH_Runner.swift
|
||||
Tests/CryptoTests/Encodings/DERTests.swift
|
||||
Tests/CryptoTests/Encodings/ECKeyEncodingsTests.swift
|
||||
Tests/CryptoTests/HPKE/HPKETests-TestVectors.swift
|
||||
Tests/CryptoTests/HPKE/HPKETests.swift
|
||||
Tests/CryptoTests/Key Derivation/ECprivateKeysFromSeeds.swift
|
||||
Tests/CryptoTests/Key Derivation/HKDFTests.swift
|
||||
Tests/CryptoTests/Key Derivation/SharedSecretTests.swift
|
||||
Tests/CryptoTests/Key Derivation/X963KDFTests.swift
|
||||
Tests/CryptoTests/Key Wrapping/KeyWrapping.swift
|
||||
Tests/CryptoTests/MAC/HMACTests.swift
|
||||
Tests/CryptoTests/SecureBytes/SecureBytesTests.swift
|
||||
Tests/CryptoTests/Signatures/ECDSA/ECDSASignatureTests.swift
|
||||
Tests/CryptoTests/Signatures/ECDSA/RawECDSASignaturesTests.swift
|
||||
Tests/CryptoTests/Signatures/EdDSA/Ed25519-Runner.swift
|
||||
Tests/CryptoTests/Utils/PrettyBytes.swift
|
||||
Tests/CryptoTests/Utils/RFCVector.swift
|
||||
Tests/CryptoTests/Utils/SplitData.swift
|
||||
Tests/CryptoTests/Utils/Wycheproof.swift
|
||||
Tests/CryptoTests/Utils/XCTestUtils.swift
|
||||
Tests/_CryptoExtrasTests/AES Block Function Tests.swift
|
||||
Tests/_CryptoExtrasTests/AES-GCM-SIV-Runner.swift
|
||||
Tests/_CryptoExtrasTests/AES_CBCTests.swift
|
||||
Tests/_CryptoExtrasTests/AES_CFBTests.swift
|
||||
Tests/_CryptoExtrasTests/AES_CTRTests.swift
|
||||
Tests/_CryptoExtrasTests/ChaCha20CTRTests.swift
|
||||
Tests/_CryptoExtrasTests/ECToolbox/HashToCurveTests.swift
|
||||
Tests/_CryptoExtrasTests/OPRFs/ECVOPRFTests.swift
|
||||
Tests/_CryptoExtrasTests/OPRFs/VOPRFAPITests.swift
|
||||
Tests/_CryptoExtrasTests/OPRFs/VOPRFPublicAPITests.swift
|
||||
Tests/_CryptoExtrasTests/PBKDF2Tests.swift
|
||||
Tests/_CryptoExtrasTests/ScryptTests.swift
|
||||
Tests/_CryptoExtrasTests/TestRSABlindSigning.swift
|
||||
Tests/_CryptoExtrasTests/TestRSABlindSigningAPI.swift
|
||||
Tests/_CryptoExtrasTests/TestRSAEncryption.swift
|
||||
Tests/_CryptoExtrasTests/TestRSASigning.swift
|
||||
Tests/_CryptoExtrasTests/Utils/BytesUtil.swift
|
||||
Tests/_CryptoExtrasTests/Utils/RFCVector.swift
|
||||
Tests/_CryptoExtrasTests/Utils/SplitData.swift
|
||||
Tests/_CryptoExtrasTests/Utils/Wycheproof.swift
|
||||
Tests/_CryptoExtrasTests/Utils/XCTestUtils.swift
|
||||
@@ -20,8 +20,12 @@ import Foundation
|
||||
|
||||
enum OpenSSLAESGCMImpl {
|
||||
@inlinable
|
||||
static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>
|
||||
(key: SymmetricKey, message: Plaintext, nonce: AES.GCM.Nonce?, authenticatedData: AuthenticatedData? = nil) throws -> AES.GCM.SealedBox {
|
||||
static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>(
|
||||
key: SymmetricKey,
|
||||
message: Plaintext,
|
||||
nonce: AES.GCM.Nonce?,
|
||||
authenticatedData: AuthenticatedData? = nil
|
||||
) throws -> AES.GCM.SealedBox {
|
||||
let nonce = nonce ?? AES.GCM.Nonce()
|
||||
|
||||
let aead = try Self._backingAEAD(key: key)
|
||||
@@ -29,23 +33,48 @@ enum OpenSSLAESGCMImpl {
|
||||
let ciphertext: Data
|
||||
let tag: Data
|
||||
if let ad = authenticatedData {
|
||||
(ciphertext, tag) = try aead.seal(message: message, key: key, nonce: nonce, authenticatedData: ad)
|
||||
(ciphertext, tag) = try aead.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
(ciphertext, tag) = try aead.seal(message: message, key: key, nonce: nonce, authenticatedData: [])
|
||||
(ciphertext, tag) = try aead.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: []
|
||||
)
|
||||
}
|
||||
|
||||
return try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func open<AuthenticatedData: DataProtocol>
|
||||
(key: SymmetricKey, sealedBox: AES.GCM.SealedBox, authenticatedData: AuthenticatedData? = nil) throws -> Data {
|
||||
static func open<AuthenticatedData: DataProtocol>(
|
||||
key: SymmetricKey,
|
||||
sealedBox: AES.GCM.SealedBox,
|
||||
authenticatedData: AuthenticatedData? = nil
|
||||
) throws -> Data {
|
||||
let aead = try Self._backingAEAD(key: key)
|
||||
|
||||
if let ad = authenticatedData {
|
||||
return try aead.open(ciphertext: sealedBox.ciphertext, key: key, nonce: sealedBox.nonce, tag: sealedBox.tag, authenticatedData: ad)
|
||||
return try aead.open(
|
||||
ciphertext: sealedBox.ciphertext,
|
||||
key: key,
|
||||
nonce: sealedBox.nonce,
|
||||
tag: sealedBox.tag,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
return try aead.open(ciphertext: sealedBox.ciphertext, key: key, nonce: sealedBox.nonce, tag: sealedBox.tag, authenticatedData: [])
|
||||
return try aead.open(
|
||||
ciphertext: sealedBox.ciphertext,
|
||||
key: key,
|
||||
nonce: sealedBox.nonce,
|
||||
tag: sealedBox.tag,
|
||||
authenticatedData: []
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,4 +92,4 @@ enum OpenSSLAESGCMImpl {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -21,20 +21,40 @@ import Foundation
|
||||
|
||||
extension BoringSSLAEAD {
|
||||
/// Seal a given message.
|
||||
func seal<Plaintext: DataProtocol, Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(message: Plaintext, key: SymmetricKey, nonce: Nonce, authenticatedData: AuthenticatedData) throws -> (ciphertext: Data, tag: Data) {
|
||||
func seal<Plaintext: DataProtocol, Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||
message: Plaintext,
|
||||
key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> (ciphertext: Data, tag: Data) {
|
||||
do {
|
||||
let context = try AEADContext(cipher: self, key: key)
|
||||
return try context.seal(message: message, nonce: nonce, authenticatedData: authenticatedData)
|
||||
return try context.seal(
|
||||
message: message,
|
||||
nonce: nonce,
|
||||
authenticatedData: authenticatedData
|
||||
)
|
||||
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
|
||||
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a given message.
|
||||
func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(ciphertext: Data, key: SymmetricKey, nonce: Nonce, tag: Data, authenticatedData: AuthenticatedData) throws -> Data {
|
||||
func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||
ciphertext: Data,
|
||||
key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
tag: Data,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> Data {
|
||||
do {
|
||||
let context = try AEADContext(cipher: self, key: key)
|
||||
return try context.open(ciphertext: ciphertext, nonce: nonce, tag: tag, authenticatedData: authenticatedData)
|
||||
return try context.open(
|
||||
ciphertext: ciphertext,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: authenticatedData
|
||||
)
|
||||
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
|
||||
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||
}
|
||||
@@ -42,7 +62,12 @@ extension BoringSSLAEAD {
|
||||
}
|
||||
|
||||
enum OpenSSLChaChaPolyImpl {
|
||||
static func encrypt<M: DataProtocol, AD: DataProtocol>(key: SymmetricKey, message: M, nonce: ChaChaPoly.Nonce?, authenticatedData: AD?) throws -> ChaChaPoly.SealedBox {
|
||||
static func encrypt<M: DataProtocol, AD: DataProtocol>(
|
||||
key: SymmetricKey,
|
||||
message: M,
|
||||
nonce: ChaChaPoly.Nonce?,
|
||||
authenticatedData: AD?
|
||||
) throws -> ChaChaPoly.SealedBox {
|
||||
guard key.bitCount == ChaChaPoly.keyBitsCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
@@ -51,24 +76,50 @@ enum OpenSSLChaChaPolyImpl {
|
||||
let ciphertext: Data
|
||||
let tag: Data
|
||||
if let ad = authenticatedData {
|
||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(message: message, key: key, nonce: nonce, authenticatedData: ad)
|
||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(message: message, key: key, nonce: nonce, authenticatedData: [])
|
||||
(ciphertext, tag) = try BoringSSLAEAD.chacha20.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: []
|
||||
)
|
||||
}
|
||||
|
||||
return try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
|
||||
}
|
||||
|
||||
static func decrypt<AD: DataProtocol>(key: SymmetricKey, ciphertext: ChaChaPoly.SealedBox, authenticatedData: AD?) throws -> Data {
|
||||
static func decrypt<AD: DataProtocol>(
|
||||
key: SymmetricKey,
|
||||
ciphertext: ChaChaPoly.SealedBox,
|
||||
authenticatedData: AD?
|
||||
) throws -> Data {
|
||||
guard key.bitCount == ChaChaPoly.keyBitsCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
if let ad = authenticatedData {
|
||||
return try BoringSSLAEAD.chacha20.open(ciphertext: ciphertext.ciphertext, key: key, nonce: ciphertext.nonce, tag: ciphertext.tag, authenticatedData: ad)
|
||||
return try BoringSSLAEAD.chacha20.open(
|
||||
ciphertext: ciphertext.ciphertext,
|
||||
key: key,
|
||||
nonce: ciphertext.nonce,
|
||||
tag: ciphertext.tag,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
return try BoringSSLAEAD.chacha20.open(ciphertext: ciphertext.ciphertext, key: key, nonce: ciphertext.nonce, tag: ciphertext.tag, authenticatedData: [])
|
||||
return try BoringSSLAEAD.chacha20.open(
|
||||
ciphertext: ciphertext.ciphertext,
|
||||
key: key,
|
||||
nonce: ciphertext.nonce,
|
||||
tag: ciphertext.tag,
|
||||
authenticatedData: []
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -155,7 +155,7 @@ struct OpenSSLDigestImpl<H: BoringSSLBackedHashFunction> {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate final class DigestContext<H: BoringSSLBackedHashFunction> {
|
||||
private final class DigestContext<H: BoringSSLBackedHashFunction> {
|
||||
private var context: H.Context
|
||||
|
||||
init() {
|
||||
@@ -196,4 +196,4 @@ fileprivate final class DigestContext<H: BoringSSLBackedHashFunction> {
|
||||
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -17,23 +17,29 @@
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
|
||||
extension P256.KeyAgreement.PrivateKey {
|
||||
internal func openSSLSharedSecretFromKeyAgreement(with publicKeyShare: P256.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
internal func openSSLSharedSecretFromKeyAgreement(
|
||||
with publicKeyShare: P256.KeyAgreement.PublicKey
|
||||
) throws -> SharedSecret {
|
||||
let key = try self.impl.key.keyExchange(publicKey: publicKeyShare.impl.key)
|
||||
return SharedSecret(ss: key)
|
||||
}
|
||||
}
|
||||
|
||||
extension P384.KeyAgreement.PrivateKey {
|
||||
internal func openSSLSharedSecretFromKeyAgreement(with publicKeyShare: P384.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
internal func openSSLSharedSecretFromKeyAgreement(
|
||||
with publicKeyShare: P384.KeyAgreement.PublicKey
|
||||
) throws -> SharedSecret {
|
||||
let key = try self.impl.key.keyExchange(publicKey: publicKeyShare.impl.key)
|
||||
return SharedSecret(ss: key)
|
||||
}
|
||||
}
|
||||
|
||||
extension P521.KeyAgreement.PrivateKey {
|
||||
internal func openSSLSharedSecretFromKeyAgreement(with publicKeyShare: P521.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
internal func openSSLSharedSecretFromKeyAgreement(
|
||||
with publicKeyShare: P521.KeyAgreement.PublicKey
|
||||
) throws -> SharedSecret {
|
||||
let key = try self.impl.key.keyExchange(publicKey: publicKeyShare.impl.key)
|
||||
return SharedSecret(ss: key)
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -30,7 +30,11 @@ enum BoringSSLAESWRAPImpl {
|
||||
// Memory bind is safe: we cannot alias the pointer here.
|
||||
let keyToWrapPtr = keyToWrapPtr.bindMemory(to: UInt8.self)
|
||||
return CCryptoBoringSSL_AES_wrap_key(
|
||||
aesKey, nil, outputPtr.baseAddress, keyToWrapPtr.baseAddress, keyToWrapPtr.count
|
||||
aesKey,
|
||||
nil,
|
||||
outputPtr.baseAddress,
|
||||
keyToWrapPtr.baseAddress,
|
||||
keyToWrapPtr.count
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -45,7 +49,12 @@ enum BoringSSLAESWRAPImpl {
|
||||
return output.prefix(Int(rc))
|
||||
}
|
||||
|
||||
static func unwrap<WrappedKey: DataProtocol>(key: SymmetricKey, wrappedKey: WrappedKey) throws -> SymmetricKey {
|
||||
static func unwrap<WrappedKey: DataProtocol>(
|
||||
key: SymmetricKey,
|
||||
wrappedKey: WrappedKey
|
||||
) throws
|
||||
-> SymmetricKey
|
||||
{
|
||||
if wrappedKey.regions.count == 1 {
|
||||
return try self.unwrap(key: key, contiguousWrappedKey: wrappedKey.regions.first!)
|
||||
} else {
|
||||
@@ -54,14 +63,21 @@ enum BoringSSLAESWRAPImpl {
|
||||
}
|
||||
}
|
||||
|
||||
private static func unwrap<WrappedKey: ContiguousBytes>(key: SymmetricKey, contiguousWrappedKey: WrappedKey) throws -> SymmetricKey {
|
||||
private static func unwrap<WrappedKey: ContiguousBytes>(
|
||||
key: SymmetricKey,
|
||||
contiguousWrappedKey: WrappedKey
|
||||
) throws -> SymmetricKey {
|
||||
let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in
|
||||
try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
|
||||
// Bind is safe: we cannot violate the aliasing rules here as we never call to arbitrary code.
|
||||
let inPtr = inPtr.bindMemory(to: UInt8.self)
|
||||
let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in
|
||||
CCryptoBoringSSL_AES_unwrap_key(
|
||||
aesKey, nil, outputPtr.baseAddress, inPtr.baseAddress, inPtr.count
|
||||
aesKey,
|
||||
nil,
|
||||
outputPtr.baseAddress,
|
||||
inPtr.baseAddress,
|
||||
inPtr.count
|
||||
)
|
||||
}
|
||||
|
||||
@@ -85,7 +101,10 @@ extension SymmetricKey {
|
||||
case decrypting
|
||||
}
|
||||
|
||||
fileprivate func withUnsafeAESKEY<ResultType>(mode: AESKeyMode, _ body: (UnsafePointer<AES_KEY>) throws -> ResultType) throws -> ResultType {
|
||||
fileprivate func withUnsafeAESKEY<ResultType>(
|
||||
mode: AESKeyMode,
|
||||
_ body: (UnsafePointer<AES_KEY>) throws -> ResultType
|
||||
) throws -> ResultType {
|
||||
try self.withUnsafeBytes { bytesPointer in
|
||||
// Bind is safe: cannot alias the pointer here.
|
||||
let bytesPointer = bytesPointer.bindMemory(to: UInt8.self)
|
||||
@@ -97,11 +116,15 @@ extension SymmetricKey {
|
||||
switch mode {
|
||||
case .encrypting:
|
||||
rc = CCryptoBoringSSL_AES_set_encrypt_key(
|
||||
bytesPointer.baseAddress!, bitsInKey, &aesKey
|
||||
bytesPointer.baseAddress!,
|
||||
bitsInKey,
|
||||
&aesKey
|
||||
)
|
||||
case .decrypting:
|
||||
rc = CCryptoBoringSSL_AES_set_decrypt_key(
|
||||
bytesPointer.baseAddress!, bitsInKey, &aesKey
|
||||
bytesPointer.baseAddress!,
|
||||
bitsInKey,
|
||||
&aesKey
|
||||
)
|
||||
}
|
||||
|
||||
@@ -110,10 +133,10 @@ extension SymmetricKey {
|
||||
}
|
||||
|
||||
return try withUnsafePointer(to: aesKey) {
|
||||
return try body($0)
|
||||
try body($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -22,18 +22,23 @@ import Foundation
|
||||
extension Curve25519.Signing {
|
||||
@usableFromInline
|
||||
struct OpenSSLCurve25519PrivateKeyImpl {
|
||||
/* private but @usableFromInline */ var _privateKey: SecureBytes
|
||||
/* private but @usableFromInline */ @usableFromInline var _publicKey: [UInt8]
|
||||
var _privateKey: SecureBytes
|
||||
@usableFromInline var _publicKey: [UInt8]
|
||||
|
||||
@usableFromInline
|
||||
init() {
|
||||
// BoringSSL's Ed25519 implementation stores the private key concatenated with the public key, so we do
|
||||
// as well. We also store the public key because it makes our lives easier.
|
||||
var publicKey = Array(repeating: UInt8(0), count: 32)
|
||||
let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) { privateKeyPtr, privateKeyBytes in
|
||||
let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) {
|
||||
privateKeyPtr,
|
||||
privateKeyBytes in
|
||||
privateKeyBytes = 64
|
||||
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
||||
CCryptoBoringSSLShims_ED25519_keypair(publicKeyPtr.baseAddress, privateKeyPtr.baseAddress)
|
||||
CCryptoBoringSSLShims_ED25519_keypair(
|
||||
publicKeyPtr.baseAddress,
|
||||
privateKeyPtr.baseAddress
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,10 +64,16 @@ extension Curve25519.Signing {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) { privateKeyPtr, privateKeyBytes in
|
||||
let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) {
|
||||
privateKeyPtr,
|
||||
privateKeyBytes in
|
||||
privateKeyBytes = 64
|
||||
publicKey.withUnsafeMutableBytes { publicKeyPtr in
|
||||
CCryptoBoringSSLShims_ED25519_keypair_from_seed(publicKeyPtr.baseAddress, privateKeyPtr.baseAddress, seedPtr.baseAddress)
|
||||
CCryptoBoringSSLShims_ED25519_keypair_from_seed(
|
||||
publicKeyPtr.baseAddress,
|
||||
privateKeyPtr.baseAddress,
|
||||
seedPtr.baseAddress
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,4 +116,4 @@ extension Curve25519.Signing {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -144,7 +144,7 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
|
||||
// If we've been asked to generate a compact representable key, we need to try a few times. This loop shouldn't
|
||||
// execute more than 100 times: if it does, we'll crash because something bad is happening.
|
||||
for _ in 0 ..< 100 {
|
||||
for _ in 0..<100 {
|
||||
// We generate FIPS compliant keys to match the behaviour of CryptoKit on Apple platforms.
|
||||
guard CCryptoBoringSSL_EC_KEY_generate_key(self.key) != 0 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
@@ -155,7 +155,9 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
continue
|
||||
}
|
||||
|
||||
if !compactRepresentable || _isCompactRepresentable(group: group, publicKeyPoint: self.publicKeyPoint) {
|
||||
if !compactRepresentable
|
||||
|| _isCompactRepresentable(group: group, publicKeyPoint: self.publicKeyPoint)
|
||||
{
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -221,7 +223,10 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
try y.withUnsafeMutableBignumPointer { yPointer in
|
||||
// This function is missing some const declarations here, which is why we need the bignums inout.
|
||||
// If that gets fixed, we can clean this function up.
|
||||
guard CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer) != 0 else {
|
||||
guard
|
||||
CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer)
|
||||
!= 0
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
@@ -244,7 +249,10 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
|
||||
@usableFromInline
|
||||
var publicKeyPoint: EllipticCurvePoint {
|
||||
try! EllipticCurvePoint(copying: CCryptoBoringSSL_EC_KEY_get0_public_key(self.key)!, on: Curve.group)
|
||||
try! EllipticCurvePoint(
|
||||
copying: CCryptoBoringSSL_EC_KEY_get0_public_key(self.key)!,
|
||||
on: Curve.group
|
||||
)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -258,7 +266,10 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
// consistency errors.
|
||||
var bytes = Data()
|
||||
bytes.reserveCapacity(Curve.group.coordinateByteCount)
|
||||
try! bytes.append(bytesOf: self.privateKeyScalar, paddedToSize: Curve.group.coordinateByteCount)
|
||||
try! bytes.append(
|
||||
bytesOf: self.privateKeyScalar,
|
||||
paddedToSize: Curve.group.coordinateByteCount
|
||||
)
|
||||
return bytes
|
||||
}
|
||||
|
||||
@@ -289,7 +300,13 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
|
||||
return try SecureBytes(unsafeUninitializedCapacity: outputSize) { secretPtr, secretSize in
|
||||
let rc = pubKeyPoint.withPointPointer { pointPtr in
|
||||
CCryptoBoringSSL_ECDH_compute_key(secretPtr.baseAddress, secretPtr.count, pointPtr, self.key, nil)
|
||||
CCryptoBoringSSL_ECDH_compute_key(
|
||||
secretPtr.baseAddress,
|
||||
secretPtr.count,
|
||||
pointPtr,
|
||||
self.key,
|
||||
nil
|
||||
)
|
||||
}
|
||||
|
||||
if rc == -1 {
|
||||
@@ -301,7 +318,8 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
}
|
||||
|
||||
func sign<D: Digest>(digest: D) throws -> ECDSASignature {
|
||||
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes { digestPtr in
|
||||
let optionalRawSignature: UnsafeMutablePointer<ECDSA_SIG>? = digest.withUnsafeBytes {
|
||||
digestPtr in
|
||||
CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key)
|
||||
}
|
||||
guard let rawSignature = optionalRawSignature else {
|
||||
@@ -488,7 +506,10 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
|
||||
@usableFromInline
|
||||
var publicKeyPoint: EllipticCurvePoint {
|
||||
try! EllipticCurvePoint(copying: CCryptoBoringSSL_EC_KEY_get0_public_key(self.key)!, on: Curve.group)
|
||||
try! EllipticCurvePoint(
|
||||
copying: CCryptoBoringSSL_EC_KEY_get0_public_key(self.key)!,
|
||||
on: Curve.group
|
||||
)
|
||||
}
|
||||
|
||||
func setPublicKey(x: inout ArbitraryPrecisionInteger, y: inout ArbitraryPrecisionInteger) throws {
|
||||
@@ -496,7 +517,10 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
try y.withUnsafeMutableBignumPointer { yPointer in
|
||||
// This function is missing some const declarations here, which is why we need the bignums inout.
|
||||
// If that gets fixed, we can clean this function up.
|
||||
guard CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer) != 0 else {
|
||||
guard
|
||||
CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer)
|
||||
!= 0
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
@@ -513,7 +537,13 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
CCryptoBoringSSL_EC_POINT_free(point)
|
||||
}
|
||||
let rc = Curve.group.withUnsafeGroupPointer { groupPtr in
|
||||
CCryptoBoringSSL_EC_POINT_set_compressed_coordinates_GFp(groupPtr, point, xPointer, yBit ? 1 : 0, nil)
|
||||
CCryptoBoringSSL_EC_POINT_set_compressed_coordinates_GFp(
|
||||
groupPtr,
|
||||
point,
|
||||
xPointer,
|
||||
yBit ? 1 : 0,
|
||||
nil
|
||||
)
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
@@ -529,7 +559,12 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
|
||||
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
|
||||
digest.withUnsafeBytes { digestPointer in
|
||||
CCryptoBoringSSLShims_ECDSA_do_verify(digestPointer.baseAddress, digestPointer.count, signaturePointer, self.key)
|
||||
CCryptoBoringSSLShims_ECDSA_do_verify(
|
||||
digestPointer.baseAddress,
|
||||
digestPointer.count,
|
||||
signaturePointer,
|
||||
self.key
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -538,21 +573,23 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
|
||||
}
|
||||
|
||||
extension ContiguousBytes {
|
||||
func readx963PrivateNumbers() throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger, k: ArbitraryPrecisionInteger) {
|
||||
func readx963PrivateNumbers() throws -> (
|
||||
x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger, k: ArbitraryPrecisionInteger
|
||||
) {
|
||||
// The x9.63 private key format is a discriminator byte (0x4) concatenated with the X and Y points
|
||||
// of the public key, and the K value of the secret scalar. Let's load that in.
|
||||
return try self.withUnsafeBytes { bytesPtr in
|
||||
try self.withUnsafeBytes { bytesPtr in
|
||||
guard bytesPtr.first == 0x04 else {
|
||||
throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms.
|
||||
throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms.
|
||||
}
|
||||
|
||||
let stride = (bytesPtr.count - 1) / 3
|
||||
var offset = 1
|
||||
let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)])
|
||||
let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)])
|
||||
offset += stride
|
||||
let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)])
|
||||
let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)])
|
||||
offset += stride
|
||||
let kPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)])
|
||||
let kPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)])
|
||||
|
||||
let x = try ArbitraryPrecisionInteger(bytes: xPointer)
|
||||
let y = try ArbitraryPrecisionInteger(bytes: yPointer)
|
||||
@@ -563,15 +600,19 @@ extension ContiguousBytes {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func readx963PublicNumbers() throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger) {
|
||||
func readx963PublicNumbers() throws -> (
|
||||
x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger
|
||||
) {
|
||||
// The x9.63 public key format is a discriminator byte (0x4) concatenated with the X and Y points
|
||||
// of the public key. Let's load that in.
|
||||
return try self.withUnsafeBytes { bytesPtr in
|
||||
try self.withUnsafeBytes { bytesPtr in
|
||||
guard bytesPtr.first == 0x04 else {
|
||||
throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms.
|
||||
throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms.
|
||||
}
|
||||
|
||||
return try readRawPublicNumbers(copyingBytes: UnsafeRawBufferPointer(rebasing: bytesPtr[1...]))
|
||||
return try readRawPublicNumbers(
|
||||
copyingBytes: UnsafeRawBufferPointer(rebasing: bytesPtr[1...])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,7 +620,7 @@ extension ContiguousBytes {
|
||||
func readx963CompressedPublicNumbers() throws -> (x: ArbitraryPrecisionInteger, yBit: Bool) {
|
||||
// The x9.63 compressed public key format is a discriminator byte (0x2 or 0x3) that signals which
|
||||
// of the possible two Y values is being used, concatenated with the X point of the key.
|
||||
return try self.withUnsafeBytes { bytesPtr in
|
||||
try self.withUnsafeBytes { bytesPtr in
|
||||
let yBit: Bool
|
||||
|
||||
switch bytesPtr.first {
|
||||
@@ -588,7 +629,7 @@ extension ContiguousBytes {
|
||||
case 0x02:
|
||||
yBit = false
|
||||
default:
|
||||
throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms.
|
||||
throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms.
|
||||
}
|
||||
|
||||
let xBytes = UnsafeRawBufferPointer(rebasing: bytesPtr.dropFirst())
|
||||
@@ -600,12 +641,16 @@ extension ContiguousBytes {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func readRawPublicNumbers(copyingBytes bytesPtr: UnsafeRawBufferPointer) throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger) {
|
||||
func readRawPublicNumbers(
|
||||
copyingBytes bytesPtr: UnsafeRawBufferPointer
|
||||
) throws -> (
|
||||
x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger
|
||||
) {
|
||||
let stride = bytesPtr.count / 2
|
||||
var offset = 0
|
||||
let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)])
|
||||
let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)])
|
||||
offset += stride
|
||||
let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)])
|
||||
let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)])
|
||||
|
||||
// We cannot handle allocation errors, so we check for fatal error.
|
||||
let x = try ArbitraryPrecisionInteger(bytes: xPointer)
|
||||
@@ -619,7 +664,10 @@ func readRawPublicNumbers(copyingBytes bytesPtr: UnsafeRawBufferPointer) throws
|
||||
/// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a
|
||||
/// point is compact representable if its y coordinate is the smaller of min(y, p-y) where p is the order of the prime field.
|
||||
@usableFromInline
|
||||
func _isCompactRepresentable(group: BoringSSLEllipticCurveGroup, publicKeyPoint: EllipticCurvePoint) -> Bool {
|
||||
func _isCompactRepresentable(
|
||||
group: BoringSSLEllipticCurveGroup,
|
||||
publicKeyPoint: EllipticCurvePoint
|
||||
) -> Bool {
|
||||
// We have three try!s here: any of those failing is the result of an allocation error, and we cannot recover from
|
||||
// those.
|
||||
let (_, y) = try! publicKeyPoint.affineCoordinates(group: group)
|
||||
@@ -630,4 +678,4 @@ func _isCompactRepresentable(group: BoringSSLEllipticCurveGroup, publicKeyPoint:
|
||||
// The point is compact representable if y is less than or equal to newY.
|
||||
return y <= newY
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -59,13 +59,18 @@ extension Curve25519.KeyAgreement {
|
||||
init() {
|
||||
var publicKey = Array(repeating: UInt8(0), count: Curve25519.KeyAgreement.keySizeBytes)
|
||||
|
||||
self.key = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { privateKeyBytes, privateKeySize in
|
||||
self.key = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) {
|
||||
privateKeyBytes,
|
||||
privateKeySize in
|
||||
publicKey.withUnsafeMutableBytes { publicKeyBytes in
|
||||
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||
precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||
CCryptoBoringSSLShims_X25519_keypair(publicKeyBytes.baseAddress, privateKeyBytes.baseAddress)
|
||||
CCryptoBoringSSLShims_X25519_keypair(
|
||||
publicKeyBytes.baseAddress,
|
||||
privateKeyBytes.baseAddress
|
||||
)
|
||||
}
|
||||
privateKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing.
|
||||
privateKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing.
|
||||
}
|
||||
self.publicKey = .init(publicKey)
|
||||
|
||||
@@ -80,12 +85,19 @@ extension Curve25519.KeyAgreement {
|
||||
|
||||
init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
let publicBytes: [UInt8] = try rawRepresentation.withUnsafeBytes { privatePointer in
|
||||
try OpenSSLCurve25519PrivateKeyImpl.validateX25519PrivateKeyData(rawRepresentation: privatePointer)
|
||||
try OpenSSLCurve25519PrivateKeyImpl.validateX25519PrivateKeyData(
|
||||
rawRepresentation: privatePointer
|
||||
)
|
||||
|
||||
return Array(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { publicKeyBytes, publicKeySize in
|
||||
return Array(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) {
|
||||
publicKeyBytes,
|
||||
publicKeySize in
|
||||
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
|
||||
CCryptoBoringSSLShims_X25519_public_from_private(publicKeyBytes.baseAddress, privatePointer.baseAddress)
|
||||
publicKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing.
|
||||
CCryptoBoringSSLShims_X25519_public_from_private(
|
||||
publicKeyBytes.baseAddress,
|
||||
privatePointer.baseAddress
|
||||
)
|
||||
publicKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +106,14 @@ extension Curve25519.KeyAgreement {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func sharedSecretFromKeyAgreement(with publicKeyShare: OpenSSLCurve25519PublicKeyImpl) throws -> SharedSecret {
|
||||
let sharedSecret = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { secretPointer, secretSize in
|
||||
func sharedSecretFromKeyAgreement(
|
||||
with publicKeyShare: OpenSSLCurve25519PublicKeyImpl
|
||||
) throws
|
||||
-> SharedSecret
|
||||
{
|
||||
let sharedSecret = SecureBytes(
|
||||
unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes
|
||||
) { secretPointer, secretSize in
|
||||
self.key.withUnsafeBytes { privateKeyPointer in
|
||||
// We precondition on all of these sizes because bounds checking is cool.
|
||||
// These are fatal instead of guards because we allocated the secret (so it must be right),
|
||||
@@ -110,10 +128,14 @@ extension Curve25519.KeyAgreement {
|
||||
// politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple
|
||||
// platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it.
|
||||
// We may elect to revisit this decision if the security best-practice thinking changes.
|
||||
CCryptoBoringSSLShims_X25519(secretPointer.baseAddress, privateKeyPointer.baseAddress, publicKeyShare.keyBytes)
|
||||
CCryptoBoringSSLShims_X25519(
|
||||
secretPointer.baseAddress,
|
||||
privateKeyPointer.baseAddress,
|
||||
publicKeyShare.keyBytes
|
||||
)
|
||||
}
|
||||
|
||||
secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
|
||||
secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
|
||||
}
|
||||
|
||||
return SharedSecret(ss: sharedSecret)
|
||||
@@ -133,4 +155,4 @@ extension Curve25519.KeyAgreement {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -25,7 +25,9 @@ class ECDSASignature {
|
||||
|
||||
init<ContiguousBuffer: ContiguousBytes>(contiguousDERBytes derBytes: ContiguousBuffer) throws {
|
||||
self._baseSig = try derBytes.withUnsafeBytes { bytesPtr in
|
||||
guard let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count) else {
|
||||
guard
|
||||
let sig = CCryptoBoringSSLShims_ECDSA_SIG_from_bytes(bytesPtr.baseAddress, bytesPtr.count)
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
return sig
|
||||
@@ -83,7 +85,10 @@ class ECDSASignature {
|
||||
|
||||
// We force-unwrap here because a valid ECDSA_SIG cannot fail to have both R and S components.
|
||||
CCryptoBoringSSL_ECDSA_SIG_get0(self._baseSig, &rPtr, &sPtr)
|
||||
return (r: try! ArbitraryPrecisionInteger(copying: rPtr!), s: try! ArbitraryPrecisionInteger(copying: sPtr!))
|
||||
return (
|
||||
r: try! ArbitraryPrecisionInteger(copying: rPtr!),
|
||||
s: try! ArbitraryPrecisionInteger(copying: sPtr!)
|
||||
)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -101,8 +106,12 @@ class ECDSASignature {
|
||||
return Data(UnsafeBufferPointer(start: dataPtr, count: length))
|
||||
}
|
||||
|
||||
func withUnsafeSignaturePointer<T>(_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T) rethrows -> T {
|
||||
func withUnsafeSignaturePointer<T>(
|
||||
_ body: (UnsafeMutablePointer<ECDSA_SIG>) throws -> T
|
||||
)
|
||||
rethrows -> T
|
||||
{
|
||||
try body(self._baseSig)
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -18,7 +18,10 @@
|
||||
import Foundation
|
||||
|
||||
extension Data {
|
||||
init<D: DataProtocol, Curve: OpenSSLSupportedNISTCurve>(derSignature derBytes: D, over: Curve.Type = Curve.self) throws {
|
||||
init<D: DataProtocol, Curve: OpenSSLSupportedNISTCurve>(
|
||||
derSignature derBytes: D,
|
||||
over: Curve.Type = Curve.self
|
||||
) throws {
|
||||
// BoringSSL requires a contiguous buffer of memory, so if we don't have one we need to create one.
|
||||
if derBytes.regions.count == 1 {
|
||||
self = try Data(contiguousDERBytes: derBytes.regions.first!, over: Curve.self)
|
||||
@@ -28,13 +31,18 @@ extension Data {
|
||||
}
|
||||
}
|
||||
|
||||
init<ContiguousBuffer: ContiguousBytes, Curve: OpenSSLSupportedNISTCurve>(contiguousDERBytes derBytes: ContiguousBuffer,
|
||||
over curve: Curve.Type = Curve.self) throws {
|
||||
init<ContiguousBuffer: ContiguousBytes, Curve: OpenSSLSupportedNISTCurve>(
|
||||
contiguousDERBytes derBytes: ContiguousBuffer,
|
||||
over curve: Curve.Type = Curve.self
|
||||
) throws {
|
||||
let sig = try ECDSASignature(contiguousDERBytes: derBytes)
|
||||
self = try Data(rawSignature: sig, over: curve)
|
||||
}
|
||||
|
||||
init<Curve: OpenSSLSupportedNISTCurve>(rawSignature signature: ECDSASignature, over curve: Curve.Type = Curve.self) throws {
|
||||
init<Curve: OpenSSLSupportedNISTCurve>(
|
||||
rawSignature signature: ECDSASignature,
|
||||
over curve: Curve.Type = Curve.self
|
||||
) throws {
|
||||
// We need to bring this into the raw representation, which is r || s as defined in https://tools.ietf.org/html/rfc4754.
|
||||
let (r, s) = signature.components
|
||||
let curveByteCount = Curve.coordinateByteCount
|
||||
@@ -67,8 +75,14 @@ extension P256.Signing.PrivateKey {
|
||||
}
|
||||
|
||||
extension P256.Signing.PublicKey {
|
||||
func openSSLIsValidSignature<D: Digest>(_ signature: P256.Signing.ECDSASignature, for digest: D) -> Bool {
|
||||
guard let baseSignature = try? ECDSASignature(rawRepresentation: signature.rawRepresentation) else {
|
||||
func openSSLIsValidSignature<D: Digest>(
|
||||
_ signature: P256.Signing.ECDSASignature,
|
||||
for digest: D
|
||||
)
|
||||
-> Bool
|
||||
{
|
||||
guard let baseSignature = try? ECDSASignature(rawRepresentation: signature.rawRepresentation)
|
||||
else {
|
||||
// If we can't create a signature, it's not valid.
|
||||
return false
|
||||
}
|
||||
@@ -95,8 +109,14 @@ extension P384.Signing.PrivateKey {
|
||||
}
|
||||
|
||||
extension P384.Signing.PublicKey {
|
||||
func openSSLIsValidSignature<D: Digest>(_ signature: P384.Signing.ECDSASignature, for digest: D) -> Bool {
|
||||
guard let baseSignature = try? ECDSASignature(rawRepresentation: signature.rawRepresentation) else {
|
||||
func openSSLIsValidSignature<D: Digest>(
|
||||
_ signature: P384.Signing.ECDSASignature,
|
||||
for digest: D
|
||||
)
|
||||
-> Bool
|
||||
{
|
||||
guard let baseSignature = try? ECDSASignature(rawRepresentation: signature.rawRepresentation)
|
||||
else {
|
||||
// If we can't create a signature, it's not valid.
|
||||
return false
|
||||
}
|
||||
@@ -123,8 +143,14 @@ extension P521.Signing.PrivateKey {
|
||||
}
|
||||
|
||||
extension P521.Signing.PublicKey {
|
||||
func openSSLIsValidSignature<D: Digest>(_ signature: P521.Signing.ECDSASignature, for digest: D) -> Bool {
|
||||
guard let baseSignature = try? ECDSASignature(rawRepresentation: signature.rawRepresentation) else {
|
||||
func openSSLIsValidSignature<D: Digest>(
|
||||
_ signature: P521.Signing.ECDSASignature,
|
||||
for digest: D
|
||||
)
|
||||
-> Bool
|
||||
{
|
||||
guard let baseSignature = try? ECDSASignature(rawRepresentation: signature.rawRepresentation)
|
||||
else {
|
||||
// If we can't create a signature, it's not valid.
|
||||
return false
|
||||
}
|
||||
@@ -132,4 +158,4 @@ extension P521.Signing.PublicKey {
|
||||
return self.impl.key.isValidSignature(baseSignature, for: digest)
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -24,7 +24,12 @@ extension Curve25519.Signing.PublicKey {
|
||||
static let signatureByteCount = Curve25519.Signing.signatureByteCount
|
||||
|
||||
@inlinable
|
||||
func openSSLIsValidSignature<S: DataProtocol, D: DataProtocol>(_ signature: S, for data: D) -> Bool {
|
||||
func openSSLIsValidSignature<S: DataProtocol, D: DataProtocol>(
|
||||
_ signature: S,
|
||||
for data: D
|
||||
)
|
||||
-> Bool
|
||||
{
|
||||
if signature.count != Curve25519.Signing.PublicKey.signatureByteCount {
|
||||
return false
|
||||
}
|
||||
@@ -33,21 +38,36 @@ extension Curve25519.Signing.PublicKey {
|
||||
switch (signature.regions.count, data.regions.count) {
|
||||
case (1, 1):
|
||||
// Both data protocols are secretly contiguous.
|
||||
return self.openSSLIsValidSignature(contiguousSignature: signature.regions.first!, contiguousData: data.regions.first!)
|
||||
return self.openSSLIsValidSignature(
|
||||
contiguousSignature: signature.regions.first!,
|
||||
contiguousData: data.regions.first!
|
||||
)
|
||||
case (1, _):
|
||||
// The data isn't contiguous: we make it so.
|
||||
return self.openSSLIsValidSignature(contiguousSignature: signature.regions.first!, contiguousData: Array(data))
|
||||
return self.openSSLIsValidSignature(
|
||||
contiguousSignature: signature.regions.first!,
|
||||
contiguousData: Array(data)
|
||||
)
|
||||
case (_, 1):
|
||||
// The signature isn't contiguous, make it so.
|
||||
return self.openSSLIsValidSignature(contiguousSignature: Array(signature), contiguousData: data.regions.first!)
|
||||
return self.openSSLIsValidSignature(
|
||||
contiguousSignature: Array(signature),
|
||||
contiguousData: data.regions.first!
|
||||
)
|
||||
case (_, _):
|
||||
// Neither are contiguous.
|
||||
return self.openSSLIsValidSignature(contiguousSignature: Array(signature), contiguousData: Array(data))
|
||||
return self.openSSLIsValidSignature(
|
||||
contiguousSignature: Array(signature),
|
||||
contiguousData: Array(data)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func openSSLIsValidSignature<S: ContiguousBytes, D: ContiguousBytes>(contiguousSignature signature: S, contiguousData data: D) -> Bool {
|
||||
func openSSLIsValidSignature<S: ContiguousBytes, D: ContiguousBytes>(
|
||||
contiguousSignature signature: S,
|
||||
contiguousData data: D
|
||||
) -> Bool {
|
||||
signature.withUnsafeBytes { signaturePointer in
|
||||
data.withUnsafeBytes { dataPointer in
|
||||
self.openSSLIsValidSignature(signaturePointer: signaturePointer, dataPointer: dataPointer)
|
||||
@@ -57,14 +77,19 @@ extension Curve25519.Signing.PublicKey {
|
||||
|
||||
// We need this factored out because self.keyBytes is not @usableFromInline, and so we can't see it.
|
||||
@usableFromInline
|
||||
func openSSLIsValidSignature(signaturePointer: UnsafeRawBufferPointer, dataPointer: UnsafeRawBufferPointer) -> Bool {
|
||||
func openSSLIsValidSignature(
|
||||
signaturePointer: UnsafeRawBufferPointer,
|
||||
dataPointer: UnsafeRawBufferPointer
|
||||
) -> Bool {
|
||||
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
|
||||
precondition(self.keyBytes.count == 32)
|
||||
let rc: CInt = self.keyBytes.withUnsafeBytes { keyBytesPtr in
|
||||
CCryptoBoringSSLShims_ED25519_verify(dataPointer.baseAddress,
|
||||
dataPointer.count,
|
||||
signaturePointer.baseAddress,
|
||||
keyBytesPtr.baseAddress)
|
||||
CCryptoBoringSSLShims_ED25519_verify(
|
||||
dataPointer.baseAddress,
|
||||
dataPointer.count,
|
||||
signaturePointer.baseAddress,
|
||||
keyBytesPtr.baseAddress
|
||||
)
|
||||
}
|
||||
|
||||
return rc == 1
|
||||
@@ -97,7 +122,12 @@ extension Curve25519.Signing.PrivateKey {
|
||||
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureByteCount)
|
||||
precondition(keyPointer.count == ED25519_PRIVATE_KEY_LEN)
|
||||
|
||||
return CCryptoBoringSSLShims_ED25519_sign(signaturePointer.baseAddress, dataPointer.baseAddress, dataPointer.count, keyPointer.baseAddress)
|
||||
return CCryptoBoringSSLShims_ED25519_sign(
|
||||
signaturePointer.baseAddress,
|
||||
dataPointer.baseAddress,
|
||||
dataPointer.count,
|
||||
keyPointer.baseAddress
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,4 +138,4 @@ extension Curve25519.Signing.PrivateKey {
|
||||
return signature
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -23,4 +23,4 @@ extension CryptoKitError {
|
||||
.underlyingCoreCryptoError(error: Int32(bitPattern: CCryptoBoringSSL_ERR_get_error()))
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -42,4 +42,4 @@ extension UnsafeMutableRawBufferPointer {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -16,7 +16,12 @@ import Foundation
|
||||
/// This function performs a safe comparison between two buffers of bytes. It exists as a temporary shim until we refactor
|
||||
/// some of the usage sites to pass better data structures to us.
|
||||
@inlinable
|
||||
internal func openSSLSafeCompare<LHS: ContiguousBytes, RHS: ContiguousBytes>(_ lhs: LHS, _ rhs: RHS) -> Bool {
|
||||
internal func openSSLSafeCompare<LHS: ContiguousBytes, RHS: ContiguousBytes>(
|
||||
_ lhs: LHS,
|
||||
_ rhs: RHS
|
||||
)
|
||||
-> Bool
|
||||
{
|
||||
lhs.withUnsafeBytes { lhsPtr in
|
||||
rhs.withUnsafeBytes { rhsPtr in
|
||||
constantTimeCompare(lhsPtr, rhsPtr)
|
||||
@@ -26,7 +31,8 @@ internal func openSSLSafeCompare<LHS: ContiguousBytes, RHS: ContiguousBytes>(_ l
|
||||
|
||||
/// A straightforward constant-time comparison function for any two collections of bytes.
|
||||
@inlinable
|
||||
internal func constantTimeCompare<LHS: Collection, RHS: Collection>(_ lhs: LHS, _ rhs: RHS) -> Bool where LHS.Element == UInt8, RHS.Element == UInt8 {
|
||||
internal func constantTimeCompare<LHS: Collection, RHS: Collection>(_ lhs: LHS, _ rhs: RHS) -> Bool
|
||||
where LHS.Element == UInt8, RHS.Element == UInt8 {
|
||||
guard lhs.count == rhs.count else {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -39,7 +39,14 @@ extension BoringSSLAEAD {
|
||||
let rc: CInt = key.withUnsafeBytes { keyPointer in
|
||||
withUnsafeMutablePointer(to: &self.context) { contextPointer in
|
||||
// Create the AEAD context with a default tag length using the given key.
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_init(contextPointer, cipher.boringSSLCipher, keyPointer.baseAddress, keyPointer.count, 0, nil)
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_init(
|
||||
contextPointer,
|
||||
cipher.boringSSLCipher,
|
||||
keyPointer.baseAddress,
|
||||
keyPointer.count,
|
||||
0,
|
||||
nil
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +67,17 @@ extension BoringSSLAEAD {
|
||||
|
||||
extension BoringSSLAEAD.AEADContext {
|
||||
/// The main entry point for sealing data. Covers the full gamut of types, including discontiguous data types. This must be inlinable.
|
||||
public func seal<Plaintext: DataProtocol, Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(message: Plaintext, nonce: Nonce, authenticatedData: AuthenticatedData) throws -> (ciphertext: Data, tag: Data) {
|
||||
public func seal<
|
||||
Plaintext: DataProtocol,
|
||||
Nonce: ContiguousBytes,
|
||||
AuthenticatedData: DataProtocol
|
||||
>(
|
||||
message: Plaintext,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> (
|
||||
ciphertext: Data, tag: Data
|
||||
) {
|
||||
// Seal is a somewhat awkward function. As it returns a Data, we are going to need to initialize a Data large enough to write into. Data does not provide us an
|
||||
// initializer that gives us access to its uninitialized memory, so the cost of creating this Data is the cost of allocating the data + the cost of initializing
|
||||
// it. For smaller plaintexts this isn't too big a deal, but for larger ones the initialization cost can really get hairy.
|
||||
@@ -70,27 +87,57 @@ extension BoringSSLAEAD.AEADContext {
|
||||
switch (message.regions.count, authenticatedData.regions.count) {
|
||||
case (1, 1):
|
||||
// We can use a nice fast-path here.
|
||||
return try self._sealContiguous(message: message.regions.first!, nonce: nonce, authenticatedData: authenticatedData.regions.first!)
|
||||
return try self._sealContiguous(
|
||||
message: message.regions.first!,
|
||||
nonce: nonce,
|
||||
authenticatedData: authenticatedData.regions.first!
|
||||
)
|
||||
case (1, _):
|
||||
let contiguousAD = Array(authenticatedData)
|
||||
return try self._sealContiguous(message: message.regions.first!, nonce: nonce, authenticatedData: contiguousAD)
|
||||
return try self._sealContiguous(
|
||||
message: message.regions.first!,
|
||||
nonce: nonce,
|
||||
authenticatedData: contiguousAD
|
||||
)
|
||||
case (_, 1):
|
||||
let contiguousMessage = Array(message)
|
||||
return try self._sealContiguous(message: contiguousMessage, nonce: nonce, authenticatedData: authenticatedData.regions.first!)
|
||||
return try self._sealContiguous(
|
||||
message: contiguousMessage,
|
||||
nonce: nonce,
|
||||
authenticatedData: authenticatedData.regions.first!
|
||||
)
|
||||
case (_, _):
|
||||
let contiguousMessage = Array(message)
|
||||
let contiguousAD = Array(authenticatedData)
|
||||
return try self._sealContiguous(message: contiguousMessage, nonce: nonce, authenticatedData: contiguousAD)
|
||||
return try self._sealContiguous(
|
||||
message: contiguousMessage,
|
||||
nonce: nonce,
|
||||
authenticatedData: contiguousAD
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A fast-path for sealing contiguous data. Also inlinable to gain specialization information.
|
||||
@inlinable
|
||||
func _sealContiguous<Plaintext: ContiguousBytes, Nonce: ContiguousBytes, AuthenticatedData: ContiguousBytes>(message: Plaintext, nonce: Nonce, authenticatedData: AuthenticatedData) throws -> (ciphertext: Data, tag: Data) {
|
||||
return try message.withUnsafeBytes { messagePointer in
|
||||
func _sealContiguous<
|
||||
Plaintext: ContiguousBytes,
|
||||
Nonce: ContiguousBytes,
|
||||
AuthenticatedData: ContiguousBytes
|
||||
>(
|
||||
message: Plaintext,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> (
|
||||
ciphertext: Data, tag: Data
|
||||
) {
|
||||
try message.withUnsafeBytes { messagePointer in
|
||||
try nonce.withUnsafeBytes { noncePointer in
|
||||
try authenticatedData.withUnsafeBytes { authenticatedDataPointer in
|
||||
try self._sealContiguous(plaintext: messagePointer, noncePointer: noncePointer, authenticatedData: authenticatedDataPointer)
|
||||
try self._sealContiguous(
|
||||
plaintext: messagePointer,
|
||||
noncePointer: noncePointer,
|
||||
authenticatedData: authenticatedDataPointer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,23 +145,38 @@ extension BoringSSLAEAD.AEADContext {
|
||||
|
||||
/// The unsafe base call: not inlinable so that it can touch private variables.
|
||||
@usableFromInline
|
||||
func _sealContiguous(plaintext: UnsafeRawBufferPointer, noncePointer: UnsafeRawBufferPointer, authenticatedData: UnsafeRawBufferPointer) throws -> (ciphertext: Data, tag: Data) {
|
||||
func _sealContiguous(
|
||||
plaintext: UnsafeRawBufferPointer,
|
||||
noncePointer: UnsafeRawBufferPointer,
|
||||
authenticatedData: UnsafeRawBufferPointer
|
||||
) throws -> (ciphertext: Data, tag: Data) {
|
||||
let tagByteCount = CCryptoBoringSSL_EVP_AEAD_max_overhead(self.context.aead)
|
||||
|
||||
// We use malloc here because we are going to call free later. We force unwrap to trigger crashes if the allocation
|
||||
// fails.
|
||||
let outputBuffer = UnsafeMutableRawBufferPointer(start: malloc(plaintext.count)!, count: plaintext.count)
|
||||
let outputBuffer = UnsafeMutableRawBufferPointer(
|
||||
start: malloc(plaintext.count)!,
|
||||
count: plaintext.count
|
||||
)
|
||||
let tagBuffer = UnsafeMutableRawBufferPointer(start: malloc(tagByteCount)!, count: tagByteCount)
|
||||
var actualTagSize = tagBuffer.count
|
||||
|
||||
let rc = withUnsafeMutablePointer(to: &self.context) { contextPointer in
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(contextPointer,
|
||||
outputBuffer.baseAddress,
|
||||
tagBuffer.baseAddress, &actualTagSize, tagBuffer.count,
|
||||
noncePointer.baseAddress, noncePointer.count,
|
||||
plaintext.baseAddress, plaintext.count,
|
||||
nil, 0,
|
||||
authenticatedData.baseAddress, authenticatedData.count)
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_seal_scatter(
|
||||
contextPointer,
|
||||
outputBuffer.baseAddress,
|
||||
tagBuffer.baseAddress,
|
||||
&actualTagSize,
|
||||
tagBuffer.count,
|
||||
noncePointer.baseAddress,
|
||||
noncePointer.count,
|
||||
plaintext.baseAddress,
|
||||
plaintext.count,
|
||||
nil,
|
||||
0,
|
||||
authenticatedData.baseAddress,
|
||||
authenticatedData.count
|
||||
)
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
@@ -124,7 +186,11 @@ extension BoringSSLAEAD.AEADContext {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
let output = Data(bytesNoCopy: outputBuffer.baseAddress!, count: outputBuffer.count, deallocator: .free)
|
||||
let output = Data(
|
||||
bytesNoCopy: outputBuffer.baseAddress!,
|
||||
count: outputBuffer.count,
|
||||
deallocator: .free
|
||||
)
|
||||
let tag = Data(bytesNoCopy: tagBuffer.baseAddress!, count: actualTagSize, deallocator: .free)
|
||||
return (ciphertext: output, tag: tag)
|
||||
}
|
||||
@@ -135,7 +201,12 @@ extension BoringSSLAEAD.AEADContext {
|
||||
extension BoringSSLAEAD.AEADContext {
|
||||
/// The main entry point for opening data. Covers the full gamut of types, including discontiguous data types. This must be inlinable.
|
||||
@inlinable
|
||||
public func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(ciphertext: Data, nonce: Nonce, tag: Data, authenticatedData: AuthenticatedData) throws -> Data {
|
||||
public func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||
ciphertext: Data,
|
||||
nonce: Nonce,
|
||||
tag: Data,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> Data {
|
||||
// Open is a somewhat awkward function. As it returns a Data, we are going to need to initialize a Data large enough to write into. Data does not provide us an
|
||||
// initializer that gives us access to its uninitialized memory, so the cost of creating this Data is the cost of allocating the data + the cost of initializing
|
||||
// it. For smaller plaintexts this isn't too big a deal, but for larger ones the initialization cost can really get hairy.
|
||||
@@ -144,21 +215,41 @@ extension BoringSSLAEAD.AEADContext {
|
||||
// type, but it's honestly not worth it enough to justify the code complexity.
|
||||
if authenticatedData.regions.count == 1 {
|
||||
// We can use a nice fast-path here.
|
||||
return try self._openContiguous(ciphertext: ciphertext, nonce: nonce, tag: tag, authenticatedData: authenticatedData.regions.first!)
|
||||
return try self._openContiguous(
|
||||
ciphertext: ciphertext,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: authenticatedData.regions.first!
|
||||
)
|
||||
} else {
|
||||
let contiguousAD = Array(authenticatedData)
|
||||
return try self._openContiguous(ciphertext: ciphertext, nonce: nonce, tag: tag, authenticatedData: contiguousAD)
|
||||
return try self._openContiguous(
|
||||
ciphertext: ciphertext,
|
||||
nonce: nonce,
|
||||
tag: tag,
|
||||
authenticatedData: contiguousAD
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A fast-path for opening contiguous data. Also inlinable to gain specialization information.
|
||||
@inlinable
|
||||
func _openContiguous<Nonce: ContiguousBytes, AuthenticatedData: ContiguousBytes>(ciphertext: Data, nonce: Nonce, tag: Data, authenticatedData: AuthenticatedData) throws -> Data {
|
||||
func _openContiguous<Nonce: ContiguousBytes, AuthenticatedData: ContiguousBytes>(
|
||||
ciphertext: Data,
|
||||
nonce: Nonce,
|
||||
tag: Data,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> Data {
|
||||
try ciphertext.withUnsafeBytes { ciphertextPointer in
|
||||
try nonce.withUnsafeBytes { nonceBytes in
|
||||
try tag.withUnsafeBytes { tagBytes in
|
||||
try authenticatedData.withUnsafeBytes { authenticatedDataBytes in
|
||||
try self._openContiguous(ciphertext: ciphertextPointer, nonceBytes: nonceBytes, tagBytes: tagBytes, authenticatedData: authenticatedDataBytes)
|
||||
try self._openContiguous(
|
||||
ciphertext: ciphertextPointer,
|
||||
nonceBytes: nonceBytes,
|
||||
tagBytes: tagBytes,
|
||||
authenticatedData: authenticatedDataBytes
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,18 +258,32 @@ extension BoringSSLAEAD.AEADContext {
|
||||
|
||||
/// The unsafe base call: not inlinable so that it can touch private variables.
|
||||
@usableFromInline
|
||||
func _openContiguous(ciphertext: UnsafeRawBufferPointer, nonceBytes: UnsafeRawBufferPointer, tagBytes: UnsafeRawBufferPointer, authenticatedData: UnsafeRawBufferPointer) throws -> Data {
|
||||
func _openContiguous(
|
||||
ciphertext: UnsafeRawBufferPointer,
|
||||
nonceBytes: UnsafeRawBufferPointer,
|
||||
tagBytes: UnsafeRawBufferPointer,
|
||||
authenticatedData: UnsafeRawBufferPointer
|
||||
) throws -> Data {
|
||||
// We use malloc here because we are going to call free later. We force unwrap to trigger crashes if the allocation
|
||||
// fails.
|
||||
let outputBuffer = UnsafeMutableRawBufferPointer(start: malloc(ciphertext.count)!, count: ciphertext.count)
|
||||
let outputBuffer = UnsafeMutableRawBufferPointer(
|
||||
start: malloc(ciphertext.count)!,
|
||||
count: ciphertext.count
|
||||
)
|
||||
|
||||
let rc = withUnsafePointer(to: &self.context) { contextPointer in
|
||||
return CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(contextPointer,
|
||||
outputBuffer.baseAddress,
|
||||
nonceBytes.baseAddress, nonceBytes.count,
|
||||
ciphertext.baseAddress, ciphertext.count,
|
||||
tagBytes.baseAddress, tagBytes.count,
|
||||
authenticatedData.baseAddress, authenticatedData.count)
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(
|
||||
contextPointer,
|
||||
outputBuffer.baseAddress,
|
||||
nonceBytes.baseAddress,
|
||||
nonceBytes.count,
|
||||
ciphertext.baseAddress,
|
||||
ciphertext.count,
|
||||
tagBytes.baseAddress,
|
||||
tagBytes.count,
|
||||
authenticatedData.baseAddress,
|
||||
authenticatedData.count
|
||||
)
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
@@ -187,13 +292,21 @@ extension BoringSSLAEAD.AEADContext {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
let output = Data(bytesNoCopy: outputBuffer.baseAddress!, count: outputBuffer.count, deallocator: .free)
|
||||
let output = Data(
|
||||
bytesNoCopy: outputBuffer.baseAddress!,
|
||||
count: outputBuffer.count,
|
||||
deallocator: .free
|
||||
)
|
||||
return output
|
||||
}
|
||||
|
||||
/// An additional entry point for opening data where the ciphertext and the tag can be provided as one combined data . Covers the full gamut of types, including discontiguous data types. This must be inlinable.
|
||||
@inlinable
|
||||
public func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(combinedCiphertextAndTag: Data, nonce: Nonce, authenticatedData: AuthenticatedData) throws -> Data {
|
||||
public func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||
combinedCiphertextAndTag: Data,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> Data {
|
||||
// Open is a somewhat awkward function. As it returns a Data, we are going to need to initialize a Data large enough to write into. Data does not provide us an
|
||||
// initializer that gives us access to its uninitialized memory, so the cost of creating this Data is the cost of allocating the data + the cost of initializing
|
||||
// it. For smaller plaintexts this isn't too big a deal, but for larger ones the initialization cost can really get hairy.
|
||||
@@ -202,20 +315,36 @@ extension BoringSSLAEAD.AEADContext {
|
||||
// type, but it's honestly not worth it enough to justify the code complexity.
|
||||
if authenticatedData.regions.count == 1 {
|
||||
// We can use a nice fast-path here.
|
||||
return try self._openContiguous(combinedCiphertextAndTag: combinedCiphertextAndTag, nonce: nonce, authenticatedData: authenticatedData.regions.first!)
|
||||
return try self._openContiguous(
|
||||
combinedCiphertextAndTag: combinedCiphertextAndTag,
|
||||
nonce: nonce,
|
||||
authenticatedData: authenticatedData.regions.first!
|
||||
)
|
||||
} else {
|
||||
let contiguousAD = Array(authenticatedData)
|
||||
return try self._openContiguous(combinedCiphertextAndTag: combinedCiphertextAndTag, nonce: nonce, authenticatedData: contiguousAD)
|
||||
return try self._openContiguous(
|
||||
combinedCiphertextAndTag: combinedCiphertextAndTag,
|
||||
nonce: nonce,
|
||||
authenticatedData: contiguousAD
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A fast-path for opening contiguous data. Also inlinable to gain specialization information.
|
||||
@inlinable
|
||||
func _openContiguous<Nonce: ContiguousBytes, AuthenticatedData: ContiguousBytes>(combinedCiphertextAndTag: Data, nonce: Nonce, authenticatedData: AuthenticatedData) throws -> Data {
|
||||
func _openContiguous<Nonce: ContiguousBytes, AuthenticatedData: ContiguousBytes>(
|
||||
combinedCiphertextAndTag: Data,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> Data {
|
||||
try combinedCiphertextAndTag.withUnsafeBytes { combinedCiphertextAndTagPointer in
|
||||
try nonce.withUnsafeBytes { nonceBytes in
|
||||
try authenticatedData.withUnsafeBytes { authenticatedDataBytes in
|
||||
try self._openContiguous(combinedCiphertextAndTag: combinedCiphertextAndTagPointer, nonceBytes: nonceBytes, authenticatedData: authenticatedDataBytes)
|
||||
try self._openContiguous(
|
||||
combinedCiphertextAndTag: combinedCiphertextAndTagPointer,
|
||||
nonceBytes: nonceBytes,
|
||||
authenticatedData: authenticatedDataBytes
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -223,18 +352,32 @@ extension BoringSSLAEAD.AEADContext {
|
||||
|
||||
/// The unsafe base call: not inlinable so that it can touch private variables.
|
||||
@usableFromInline
|
||||
func _openContiguous(combinedCiphertextAndTag: UnsafeRawBufferPointer, nonceBytes: UnsafeRawBufferPointer, authenticatedData: UnsafeRawBufferPointer) throws -> Data {
|
||||
func _openContiguous(
|
||||
combinedCiphertextAndTag: UnsafeRawBufferPointer,
|
||||
nonceBytes: UnsafeRawBufferPointer,
|
||||
authenticatedData: UnsafeRawBufferPointer
|
||||
) throws -> Data {
|
||||
// We use malloc here because we are going to call free later. We force unwrap to trigger crashes if the allocation
|
||||
// fails.
|
||||
let outputBuffer = UnsafeMutableRawBufferPointer(start: malloc(combinedCiphertextAndTag.count)!, count: combinedCiphertextAndTag.count)
|
||||
let outputBuffer = UnsafeMutableRawBufferPointer(
|
||||
start: malloc(combinedCiphertextAndTag.count)!,
|
||||
count: combinedCiphertextAndTag.count
|
||||
)
|
||||
|
||||
var writtenBytes = 0
|
||||
let rc = withUnsafePointer(to: &self.context) { contextPointer in
|
||||
return CCryptoBoringSSLShims_EVP_AEAD_CTX_open(contextPointer,
|
||||
outputBuffer.baseAddress, &writtenBytes, outputBuffer.count,
|
||||
nonceBytes.baseAddress, nonceBytes.count,
|
||||
combinedCiphertextAndTag.baseAddress, combinedCiphertextAndTag.count,
|
||||
authenticatedData.baseAddress, authenticatedData.count)
|
||||
CCryptoBoringSSLShims_EVP_AEAD_CTX_open(
|
||||
contextPointer,
|
||||
outputBuffer.baseAddress,
|
||||
&writtenBytes,
|
||||
outputBuffer.count,
|
||||
nonceBytes.baseAddress,
|
||||
nonceBytes.count,
|
||||
combinedCiphertextAndTag.baseAddress,
|
||||
combinedCiphertextAndTag.count,
|
||||
authenticatedData.baseAddress,
|
||||
authenticatedData.count
|
||||
)
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
@@ -243,7 +386,11 @@ extension BoringSSLAEAD.AEADContext {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
let output = Data(bytesNoCopy: outputBuffer.baseAddress!, count: outputBuffer.count, deallocator: .free).prefix(writtenBytes)
|
||||
let output = Data(
|
||||
bytesNoCopy: outputBuffer.baseAddress!,
|
||||
count: outputBuffer.count,
|
||||
deallocator: .free
|
||||
).prefix(writtenBytes)
|
||||
return output
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,6 @@ extension CryptoBoringWrapperError {
|
||||
/// A helper function that packs the value of `ERR_get_error` into the internal error field.
|
||||
@usableFromInline
|
||||
package static func internalBoringSSLError() -> CryptoBoringWrapperError {
|
||||
return .underlyingCoreCryptoError(error: Int32(bitPattern: CCryptoBoringSSL_ERR_get_error()))
|
||||
.underlyingCoreCryptoError(error: Int32(bitPattern: CCryptoBoringSSL_ERR_get_error()))
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
/// liveness.
|
||||
@usableFromInline
|
||||
package final class BoringSSLEllipticCurveGroup {
|
||||
/* private but usableFromInline */ @usableFromInline var _group: OpaquePointer
|
||||
@usableFromInline var _group: OpaquePointer
|
||||
|
||||
@usableFromInline
|
||||
package init(_ curve: CurveName) throws {
|
||||
@@ -44,7 +44,8 @@ extension BoringSSLEllipticCurveGroup {
|
||||
@usableFromInline
|
||||
package func makeUnsafeOwnedECKey() throws -> OpaquePointer {
|
||||
guard let key = CCryptoBoringSSL_EC_KEY_new(),
|
||||
CCryptoBoringSSL_EC_KEY_set_group(key, self._group) == 1 else {
|
||||
CCryptoBoringSSL_EC_KEY_set_group(key, self._group) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
@@ -85,7 +86,9 @@ extension BoringSSLEllipticCurveGroup {
|
||||
/// An elliptic curve can be represented in a Weierstrass form: `y² = x³ + ax + b`. This
|
||||
/// property provides the values of a and b on the curve.
|
||||
@usableFromInline
|
||||
package var weierstrassCoefficients: (field: ArbitraryPrecisionInteger, a: ArbitraryPrecisionInteger, b: ArbitraryPrecisionInteger) {
|
||||
package var weierstrassCoefficients:
|
||||
(field: ArbitraryPrecisionInteger, a: ArbitraryPrecisionInteger, b: ArbitraryPrecisionInteger)
|
||||
{
|
||||
var field = ArbitraryPrecisionInteger()
|
||||
var a = ArbitraryPrecisionInteger()
|
||||
var b = ArbitraryPrecisionInteger()
|
||||
|
||||
@@ -13,13 +13,14 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
import struct Foundation.Data
|
||||
|
||||
import protocol Foundation.ContiguousBytes
|
||||
import struct Foundation.Data
|
||||
|
||||
/// A wrapper around BoringSSL's EC_POINT with some lifetime management.
|
||||
@usableFromInline
|
||||
package final class EllipticCurvePoint {
|
||||
/* private but @usableFromInline */ @usableFromInline var _basePoint: OpaquePointer
|
||||
@usableFromInline var _basePoint: OpaquePointer
|
||||
|
||||
@usableFromInline
|
||||
package init(copying pointer: OpaquePointer, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
@@ -32,7 +33,12 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(copying other: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package convenience init(
|
||||
copying other: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws
|
||||
{
|
||||
try self.init(copying: other._basePoint, on: group)
|
||||
}
|
||||
|
||||
@@ -47,11 +53,16 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(multiplying scalar: ArbitraryPrecisionInteger, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package convenience init(
|
||||
multiplying scalar: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws {
|
||||
try self.init(_pointAtInfinityOn: group)
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
try scalar.withUnsafeBignumPointer { scalarPtr in
|
||||
guard CCryptoBoringSSL_EC_POINT_mul(groupPtr, self._basePoint, scalarPtr, nil, nil, nil) == 1 else {
|
||||
guard
|
||||
CCryptoBoringSSL_EC_POINT_mul(groupPtr, self._basePoint, scalarPtr, nil, nil, nil) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
@@ -63,11 +74,17 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func multiply(by rhs: ArbitraryPrecisionInteger, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package func multiply(
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws
|
||||
{
|
||||
try self.withPointPointer { selfPtr in
|
||||
try rhs.withUnsafeBignumPointer { rhsPtr in
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
guard CCryptoBoringSSL_EC_POINT_mul(groupPtr, selfPtr, nil, selfPtr, rhsPtr, nil) != 0 else {
|
||||
guard CCryptoBoringSSL_EC_POINT_mul(groupPtr, selfPtr, nil, selfPtr, rhsPtr, nil) != 0
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
@@ -76,18 +93,31 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(multiplying lhs: EllipticCurvePoint, by rhs: ArbitraryPrecisionInteger, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package convenience init(
|
||||
multiplying lhs: EllipticCurvePoint,
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws {
|
||||
try self.init(copying: lhs, on: group)
|
||||
try self.multiply(by: rhs, on: group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func multiplying(by rhs: ArbitraryPrecisionInteger, on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
package func multiplying(
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws -> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(multiplying: self, by: rhs, on: group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func multiplying(_ lhs: EllipticCurvePoint, by rhs: ArbitraryPrecisionInteger, on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
package static func multiplying(
|
||||
_ lhs: EllipticCurvePoint,
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(multiplying: lhs, by: rhs, on: group)
|
||||
}
|
||||
|
||||
@@ -105,18 +135,31 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(adding lhs: EllipticCurvePoint, _ rhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup ) throws {
|
||||
package convenience init(
|
||||
adding lhs: EllipticCurvePoint,
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws {
|
||||
try self.init(copying: lhs, on: group)
|
||||
try self.add(rhs, on: group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func adding(_ rhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
package func adding(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws
|
||||
-> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(adding: self, rhs, on: group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func adding(_ lhs: EllipticCurvePoint, _ rhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
package static func adding(
|
||||
_ lhs: EllipticCurvePoint,
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(adding: lhs, rhs, on: group)
|
||||
}
|
||||
|
||||
@@ -132,7 +175,10 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(inverting point: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package convenience init(
|
||||
inverting point: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws {
|
||||
try self.init(copying: point, on: group)
|
||||
try self.invert(on: group)
|
||||
}
|
||||
@@ -143,7 +189,12 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func inverting(_ point: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
package static func inverting(
|
||||
_ point: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws -> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(inverting: point, on: group)
|
||||
}
|
||||
|
||||
@@ -153,42 +204,62 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init(subtracting rhs: EllipticCurvePoint, from lhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package convenience init(
|
||||
subtracting rhs: EllipticCurvePoint,
|
||||
from lhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws {
|
||||
try self.init(copying: lhs, on: group)
|
||||
try self.subtract(rhs, on: group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func subtracting(_ rhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
package func subtracting(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws
|
||||
-> EllipticCurvePoint
|
||||
{
|
||||
try EllipticCurvePoint(subtracting: rhs, from: self, on: group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func subtracting(_ rhs: EllipticCurvePoint, from lhs: EllipticCurvePoint, on group: BoringSSLEllipticCurveGroup) throws -> EllipticCurvePoint {
|
||||
package static func subtracting(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
from lhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws -> EllipticCurvePoint {
|
||||
try EllipticCurvePoint(subtracting: rhs, from: lhs, on: group)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init<MessageBytes: ContiguousBytes, DSTBytes: ContiguousBytes>(hashing msg: MessageBytes, to group: BoringSSLEllipticCurveGroup, domainSeparationTag: DSTBytes) throws {
|
||||
let hashToCurveFunction = switch group.curveName {
|
||||
case .p256: CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu
|
||||
case .p384: CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu
|
||||
case .p521: throw CryptoBoringWrapperError.invalidParameter // BoringSSL doesn't have a hash_to_curve API for P521.
|
||||
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
package convenience init<MessageBytes: ContiguousBytes, DSTBytes: ContiguousBytes>(
|
||||
hashing msg: MessageBytes,
|
||||
to group: BoringSSLEllipticCurveGroup,
|
||||
domainSeparationTag: DSTBytes
|
||||
) throws {
|
||||
let hashToCurveFunction =
|
||||
switch group.curveName {
|
||||
case .p256: CCryptoBoringSSLShims_EC_hash_to_curve_p256_xmd_sha256_sswu
|
||||
case .p384: CCryptoBoringSSLShims_EC_hash_to_curve_p384_xmd_sha384_sswu
|
||||
case .p521: throw CryptoBoringWrapperError.invalidParameter // BoringSSL has no P521 hash_to_curve API.
|
||||
case .none: throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
try self.init(_pointAtInfinityOn: group)
|
||||
try msg.withUnsafeBytes { msgPtr in
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
try domainSeparationTag.withUnsafeBytes { dstPtr in
|
||||
guard hashToCurveFunction(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
dstPtr.baseAddress,
|
||||
dstPtr.count,
|
||||
msgPtr.baseAddress,
|
||||
msgPtr.count
|
||||
) == 1 else { throw CryptoBoringWrapperError.internalBoringSSLError() }
|
||||
guard
|
||||
hashToCurveFunction(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
dstPtr.baseAddress,
|
||||
dstPtr.count,
|
||||
msgPtr.baseAddress,
|
||||
msgPtr.count
|
||||
) == 1
|
||||
else { throw CryptoBoringWrapperError.internalBoringSSLError() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,25 +285,35 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package convenience init<Bytes: ContiguousBytes>(x962Representation bytes: Bytes, on group: BoringSSLEllipticCurveGroup) throws {
|
||||
package convenience init<Bytes: ContiguousBytes>(
|
||||
x962Representation bytes: Bytes,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws {
|
||||
try self.init(_pointAtInfinityOn: group)
|
||||
guard group.withUnsafeGroupPointer({ groupPtr in
|
||||
bytes.withUnsafeBytes { dataPtr in
|
||||
CCryptoBoringSSL_EC_POINT_oct2point(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
dataPtr.baseAddress,
|
||||
dataPtr.count,
|
||||
nil
|
||||
)
|
||||
}
|
||||
}) == 1 else {
|
||||
guard
|
||||
group.withUnsafeGroupPointer({ groupPtr in
|
||||
bytes.withUnsafeBytes { dataPtr in
|
||||
CCryptoBoringSSL_EC_POINT_oct2point(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
dataPtr.baseAddress,
|
||||
dataPtr.count,
|
||||
nil
|
||||
)
|
||||
}
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.invalidParameter
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func x962RepresentationByteCount(compressed: Bool, on group: BoringSSLEllipticCurveGroup) throws -> Int {
|
||||
package func x962RepresentationByteCount(
|
||||
compressed: Bool,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
)
|
||||
throws -> Int
|
||||
{
|
||||
let numBytesNeeded = group.withUnsafeGroupPointer { groupPtr in
|
||||
CCryptoBoringSSL_EC_POINT_point2oct(
|
||||
groupPtr,
|
||||
@@ -250,7 +331,12 @@ package final class EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func x962Representation(compressed: Bool, on group: BoringSSLEllipticCurveGroup) throws -> Data {
|
||||
package func x962Representation(
|
||||
compressed: Bool,
|
||||
on group: BoringSSLEllipticCurveGroup
|
||||
) throws
|
||||
-> Data
|
||||
{
|
||||
let numBytesNeeded = try self.x962RepresentationByteCount(compressed: compressed, on: group)
|
||||
|
||||
var buf = Data(repeating: 0, count: numBytesNeeded)
|
||||
@@ -284,14 +370,26 @@ extension EllipticCurvePoint {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func affineCoordinates(group: BoringSSLEllipticCurveGroup) throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger) {
|
||||
package func affineCoordinates(
|
||||
group: BoringSSLEllipticCurveGroup
|
||||
) throws -> (
|
||||
x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger
|
||||
) {
|
||||
var x = ArbitraryPrecisionInteger()
|
||||
var y = ArbitraryPrecisionInteger()
|
||||
|
||||
try x.withUnsafeMutableBignumPointer { xPtr in
|
||||
try y.withUnsafeMutableBignumPointer { yPtr in
|
||||
try group.withUnsafeGroupPointer { groupPtr in
|
||||
guard CCryptoBoringSSL_EC_POINT_get_affine_coordinates_GFp(groupPtr, self._basePoint, xPtr, yPtr, nil) != 0 else {
|
||||
guard
|
||||
CCryptoBoringSSL_EC_POINT_get_affine_coordinates_GFp(
|
||||
groupPtr,
|
||||
self._basePoint,
|
||||
xPtr,
|
||||
yPtr,
|
||||
nil
|
||||
) != 0
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +110,11 @@ extension ArbitraryPrecisionInteger.BackingStorage {
|
||||
self.init()
|
||||
|
||||
let rc: UnsafeMutablePointer<BIGNUM>? = bytes.withUnsafeBytes { bytesPointer in
|
||||
CCryptoBoringSSLShims_BN_bin2bn(bytesPointer.baseAddress, bytesPointer.count, &self._backing)
|
||||
CCryptoBoringSSLShims_BN_bin2bn(
|
||||
bytesPointer.baseAddress,
|
||||
bytesPointer.count,
|
||||
&self._backing
|
||||
)
|
||||
}
|
||||
guard rc != nil else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
@@ -138,11 +142,17 @@ extension ArbitraryPrecisionInteger.BackingStorage {
|
||||
// MARK: - Pointer helpers
|
||||
|
||||
extension ArbitraryPrecisionInteger {
|
||||
package func withUnsafeBignumPointer<T>(_ body: (UnsafePointer<BIGNUM>) throws -> T) rethrows -> T {
|
||||
package func withUnsafeBignumPointer<T>(
|
||||
_ body: (UnsafePointer<BIGNUM>) throws -> T
|
||||
) rethrows
|
||||
-> T
|
||||
{
|
||||
try self._backing.withUnsafeBignumPointer(body)
|
||||
}
|
||||
|
||||
package mutating func withUnsafeMutableBignumPointer<T>(_ body: (UnsafeMutablePointer<BIGNUM>) throws -> T) rethrows -> T {
|
||||
package mutating func withUnsafeMutableBignumPointer<T>(
|
||||
_ body: (UnsafeMutablePointer<BIGNUM>) throws -> T
|
||||
) rethrows -> T {
|
||||
if !isKnownUniquelyReferenced(&self._backing) {
|
||||
// Failing to CoW is a fatal error here.
|
||||
self._backing = try! BackingStorage(copying: self._backing)
|
||||
@@ -157,7 +167,11 @@ extension ArbitraryPrecisionInteger.BackingStorage {
|
||||
try body(&self._backing)
|
||||
}
|
||||
|
||||
func withUnsafeMutableBignumPointer<T>(_ body: (UnsafeMutablePointer<BIGNUM>) throws -> T) rethrows -> T {
|
||||
func withUnsafeMutableBignumPointer<T>(
|
||||
_ body: (UnsafeMutablePointer<BIGNUM>) throws -> T
|
||||
)
|
||||
rethrows -> T
|
||||
{
|
||||
try body(&self._backing)
|
||||
}
|
||||
}
|
||||
@@ -165,7 +179,10 @@ extension ArbitraryPrecisionInteger.BackingStorage {
|
||||
// MARK: - Other helpers
|
||||
|
||||
extension ArbitraryPrecisionInteger {
|
||||
/* private but @usableFromInline */ @usableFromInline static func _compare(lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> CInt {
|
||||
@usableFromInline static func _compare(
|
||||
lhs: ArbitraryPrecisionInteger,
|
||||
rhs: ArbitraryPrecisionInteger
|
||||
) -> CInt {
|
||||
lhs.withUnsafeBignumPointer { lhsPtr in
|
||||
rhs.withUnsafeBignumPointer { rhsPtr in
|
||||
CCryptoBoringSSL_BN_cmp(lhsPtr, rhsPtr)
|
||||
@@ -174,7 +191,7 @@ extension ArbitraryPrecisionInteger {
|
||||
}
|
||||
|
||||
// This lets us check the sign of an ArbitraryPrecisionInteger.
|
||||
/* private but @usableFromInline */ @usableFromInline var _positive: Bool {
|
||||
@usableFromInline var _positive: Bool {
|
||||
self.withUnsafeBignumPointer {
|
||||
CCryptoBoringSSL_BN_is_negative($0) == 0
|
||||
}
|
||||
@@ -277,7 +294,12 @@ extension ArbitraryPrecisionInteger: AdditiveArithmetic {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func + (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> ArbitraryPrecisionInteger {
|
||||
package static func + (
|
||||
lhs: ArbitraryPrecisionInteger,
|
||||
rhs: ArbitraryPrecisionInteger
|
||||
)
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
@@ -303,7 +325,12 @@ extension ArbitraryPrecisionInteger: AdditiveArithmetic {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func - (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> ArbitraryPrecisionInteger {
|
||||
package static func - (
|
||||
lhs: ArbitraryPrecisionInteger,
|
||||
rhs: ArbitraryPrecisionInteger
|
||||
)
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
@@ -351,7 +378,12 @@ extension ArbitraryPrecisionInteger: Numeric {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func * (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> ArbitraryPrecisionInteger {
|
||||
package static func * (
|
||||
lhs: ArbitraryPrecisionInteger,
|
||||
rhs: ArbitraryPrecisionInteger
|
||||
)
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
@@ -390,7 +422,12 @@ extension ArbitraryPrecisionInteger: Numeric {
|
||||
|
||||
extension ArbitraryPrecisionInteger {
|
||||
@usableFromInline
|
||||
package func modulo(_ mod: ArbitraryPrecisionInteger, nonNegative: Bool = false) throws -> ArbitraryPrecisionInteger {
|
||||
package func modulo(
|
||||
_ mod: ArbitraryPrecisionInteger,
|
||||
nonNegative: Bool = false
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
@@ -429,14 +466,19 @@ extension ArbitraryPrecisionInteger {
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
package static func inverse(lhs: ArbitraryPrecisionInteger, modulo mod: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package static func inverse(
|
||||
lhs: ArbitraryPrecisionInteger,
|
||||
modulo mod: ArbitraryPrecisionInteger
|
||||
) throws -> ArbitraryPrecisionInteger {
|
||||
try ArbitraryPrecisionInteger(lhs).inverse(modulo: mod)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func add(_ rhs: ArbitraryPrecisionInteger, modulo modulus: ArbitraryPrecisionInteger? = nil) throws -> ArbitraryPrecisionInteger {
|
||||
package func add(
|
||||
_ rhs: ArbitraryPrecisionInteger,
|
||||
modulo modulus: ArbitraryPrecisionInteger? = nil
|
||||
) throws -> ArbitraryPrecisionInteger {
|
||||
guard let modulus else { return self + rhs }
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
@@ -445,7 +487,7 @@ extension ArbitraryPrecisionInteger {
|
||||
rhs.withUnsafeBignumPointer { rhsPtr in
|
||||
modulus.withUnsafeBignumPointer { modulusPtr in
|
||||
ArbitraryPrecisionInteger.withUnsafeBN_CTX { bnCtx in
|
||||
return CCryptoBoringSSL_BN_mod_add(resultPtr, selfPtr, rhsPtr, modulusPtr, bnCtx)
|
||||
CCryptoBoringSSL_BN_mod_add(resultPtr, selfPtr, rhsPtr, modulusPtr, bnCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -457,7 +499,10 @@ extension ArbitraryPrecisionInteger {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func sub(_ rhs: ArbitraryPrecisionInteger, modulo modulus: ArbitraryPrecisionInteger? = nil) throws -> ArbitraryPrecisionInteger {
|
||||
package func sub(
|
||||
_ rhs: ArbitraryPrecisionInteger,
|
||||
modulo modulus: ArbitraryPrecisionInteger? = nil
|
||||
) throws -> ArbitraryPrecisionInteger {
|
||||
guard let modulus else { return self - rhs }
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
@@ -478,7 +523,10 @@ extension ArbitraryPrecisionInteger {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func mul(_ rhs: ArbitraryPrecisionInteger, modulo modulus: ArbitraryPrecisionInteger? = nil) throws -> ArbitraryPrecisionInteger {
|
||||
package func mul(
|
||||
_ rhs: ArbitraryPrecisionInteger,
|
||||
modulo modulus: ArbitraryPrecisionInteger? = nil
|
||||
) throws -> ArbitraryPrecisionInteger {
|
||||
guard let modulus else { return self * rhs }
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
@@ -487,7 +535,7 @@ extension ArbitraryPrecisionInteger {
|
||||
rhs.withUnsafeBignumPointer { rhsPtr in
|
||||
modulus.withUnsafeBignumPointer { modulusPtr in
|
||||
ArbitraryPrecisionInteger.withUnsafeBN_CTX { bnCtx in
|
||||
return CCryptoBoringSSL_BN_mod_mul(resultPtr, selfPtr, rhsPtr, modulusPtr, bnCtx)
|
||||
CCryptoBoringSSL_BN_mod_mul(resultPtr, selfPtr, rhsPtr, modulusPtr, bnCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -523,18 +571,25 @@ extension ArbitraryPrecisionInteger {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func gcd(_ a: ArbitraryPrecisionInteger, _ b: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package static func gcd(
|
||||
_ a: ArbitraryPrecisionInteger,
|
||||
_ b: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
guard result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
a.withUnsafeBignumPointer { aPtr in
|
||||
b.withUnsafeBignumPointer { bPtr in
|
||||
ArbitraryPrecisionInteger.withUnsafeBN_CTX { bnCtx in
|
||||
CCryptoBoringSSL_BN_gcd(resultPtr, aPtr, bPtr, bnCtx)
|
||||
guard
|
||||
result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
a.withUnsafeBignumPointer { aPtr in
|
||||
b.withUnsafeBignumPointer { bPtr in
|
||||
ArbitraryPrecisionInteger.withUnsafeBN_CTX { bnCtx in
|
||||
CCryptoBoringSSL_BN_gcd(resultPtr, aPtr, bPtr, bnCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}) == 1 else {
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
@@ -547,14 +602,21 @@ extension ArbitraryPrecisionInteger {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func random(inclusiveMin: UInt, exclusiveMax: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package static func random(
|
||||
inclusiveMin: UInt,
|
||||
exclusiveMax: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
guard result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
exclusiveMax.withUnsafeBignumPointer { exclusiveMaxPtr in
|
||||
CCryptoBoringSSL_BN_rand_range_ex(resultPtr, BN_ULONG(inclusiveMin), exclusiveMaxPtr)
|
||||
}
|
||||
}) == 1 else {
|
||||
guard
|
||||
result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
exclusiveMax.withUnsafeBignumPointer { exclusiveMaxPtr in
|
||||
CCryptoBoringSSL_BN_rand_range_ex(resultPtr, BN_ULONG(inclusiveMin), exclusiveMaxPtr)
|
||||
}
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
@@ -577,7 +639,12 @@ extension ArbitraryPrecisionInteger {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package static func / (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> ArbitraryPrecisionInteger {
|
||||
package static func / (
|
||||
lhs: ArbitraryPrecisionInteger,
|
||||
rhs: ArbitraryPrecisionInteger
|
||||
)
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
@@ -607,7 +674,10 @@ extension ArbitraryPrecisionInteger {
|
||||
extension Data {
|
||||
/// Serializes an ArbitraryPrecisionInteger padded out to a certain minimum size.
|
||||
@usableFromInline
|
||||
package mutating func append(bytesOf integer: ArbitraryPrecisionInteger, paddedToSize paddingSize: Int) throws {
|
||||
package mutating func append(
|
||||
bytesOf integer: ArbitraryPrecisionInteger,
|
||||
paddedToSize paddingSize: Int
|
||||
) throws {
|
||||
let byteCount = integer.byteCount
|
||||
|
||||
guard paddingSize >= byteCount else {
|
||||
@@ -673,7 +743,10 @@ extension ArbitraryPrecisionInteger: CustomDebugStringConvertible {
|
||||
// call above actually executes, which will be only after this String has been constructed.
|
||||
//
|
||||
// I know it looks gross, but it's basically right.
|
||||
return String(decoding: UnsafeBufferPointer(start: stringPointer, count: length), as: Unicode.UTF8.self)
|
||||
return String(
|
||||
decoding: UnsafeBufferPointer(start: stringPointer, count: length),
|
||||
as: Unicode.UTF8.self
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -56,13 +56,15 @@ extension FiniteFieldArithmeticContext {
|
||||
package func residue(_ x: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
guard x.withUnsafeBignumPointer({ xPtr in
|
||||
self.fieldSize.withUnsafeBignumPointer { modPtr in
|
||||
result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
CCryptoBoringSSL_BN_nnmod(resultPtr, xPtr, modPtr, self.bnCtx)
|
||||
guard
|
||||
x.withUnsafeBignumPointer({ xPtr in
|
||||
self.fieldSize.withUnsafeBignumPointer { modPtr in
|
||||
result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
CCryptoBoringSSL_BN_nnmod(resultPtr, xPtr, modPtr, self.bnCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}) == 1 else {
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
@@ -89,14 +91,25 @@ extension FiniteFieldArithmeticContext {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func multiply(_ x: ArbitraryPrecisionInteger, _ y: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package func multiply(
|
||||
_ x: ArbitraryPrecisionInteger,
|
||||
_ y: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var output = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = x.withUnsafeBignumPointer { xPointer in
|
||||
y.withUnsafeBignumPointer { yPointer in
|
||||
self.fieldSize.withUnsafeBignumPointer { fieldSizePointer in
|
||||
output.withUnsafeMutableBignumPointer { outputPointer in
|
||||
CCryptoBoringSSL_BN_mod_mul(outputPointer, xPointer, yPointer, fieldSizePointer, self.bnCtx)
|
||||
CCryptoBoringSSL_BN_mod_mul(
|
||||
outputPointer,
|
||||
xPointer,
|
||||
yPointer,
|
||||
fieldSizePointer,
|
||||
self.bnCtx
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,14 +123,25 @@ extension FiniteFieldArithmeticContext {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func add(_ x: ArbitraryPrecisionInteger, _ y: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package func add(
|
||||
_ x: ArbitraryPrecisionInteger,
|
||||
_ y: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var output = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = x.withUnsafeBignumPointer { xPointer in
|
||||
y.withUnsafeBignumPointer { yPointer in
|
||||
self.fieldSize.withUnsafeBignumPointer { fieldSizePointer in
|
||||
output.withUnsafeMutableBignumPointer { outputPointer in
|
||||
CCryptoBoringSSL_BN_mod_add(outputPointer, xPointer, yPointer, fieldSizePointer, self.bnCtx)
|
||||
CCryptoBoringSSL_BN_mod_add(
|
||||
outputPointer,
|
||||
xPointer,
|
||||
yPointer,
|
||||
fieldSizePointer,
|
||||
self.bnCtx
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,7 +155,12 @@ extension FiniteFieldArithmeticContext {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func subtract(_ x: ArbitraryPrecisionInteger, from y: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package func subtract(
|
||||
_ x: ArbitraryPrecisionInteger,
|
||||
from y: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
var output = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = x.withUnsafeBignumPointer { xPointer in
|
||||
@@ -139,7 +168,13 @@ extension FiniteFieldArithmeticContext {
|
||||
self.fieldSize.withUnsafeBignumPointer { fieldSizePointer in
|
||||
output.withUnsafeMutableBignumPointer { outputPointer in
|
||||
// Note the order of y and x.
|
||||
CCryptoBoringSSL_BN_mod_sub(outputPointer, yPointer, xPointer, fieldSizePointer, self.bnCtx)
|
||||
CCryptoBoringSSL_BN_mod_sub(
|
||||
outputPointer,
|
||||
yPointer,
|
||||
xPointer,
|
||||
fieldSizePointer,
|
||||
self.bnCtx
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,7 +188,11 @@ extension FiniteFieldArithmeticContext {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func positiveSquareRoot(_ x: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package func positiveSquareRoot(
|
||||
_ x: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
let outputPointer = x.withUnsafeBignumPointer { xPointer in
|
||||
self.fieldSize.withUnsafeBignumPointer { fieldSizePointer in
|
||||
// We can't pass a pointer in as BN_mod_sqrt may attempt to free it.
|
||||
@@ -177,30 +216,47 @@ extension FiniteFieldArithmeticContext {
|
||||
package func inverse(_ x: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger? {
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
guard result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
x.withUnsafeBignumPointer { xPtr in
|
||||
self.fieldSize.withUnsafeBignumPointer { modPtr in
|
||||
CCryptoBoringSSL_BN_mod_inverse(resultPtr, xPtr, modPtr, self.bnCtx)
|
||||
guard
|
||||
result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
x.withUnsafeBignumPointer { xPtr in
|
||||
self.fieldSize.withUnsafeBignumPointer { modPtr in
|
||||
CCryptoBoringSSL_BN_mod_inverse(resultPtr, xPtr, modPtr, self.bnCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}) != nil else { return nil }
|
||||
}) != nil
|
||||
else { return nil }
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func pow(_ x: ArbitraryPrecisionInteger, _ p: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package func pow(
|
||||
_ x: ArbitraryPrecisionInteger,
|
||||
_ p: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
try self.pow(x, p) { r, x, p, m, ctx, _ in CCryptoBoringSSL_BN_mod_exp(r, x, p, m, ctx) }
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func pow(secret x: ArbitraryPrecisionInteger, _ p: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package func pow(
|
||||
secret x: ArbitraryPrecisionInteger,
|
||||
_ p: ArbitraryPrecisionInteger
|
||||
) throws
|
||||
-> ArbitraryPrecisionInteger
|
||||
{
|
||||
guard x < self.fieldSize else { throw CryptoBoringWrapperError.incorrectParameterSize }
|
||||
return try self.pow(x, p, using: CCryptoBoringSSL_BN_mod_exp_mont)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
package func pow(secret x: ArbitraryPrecisionInteger, secret p: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
package func pow(
|
||||
secret x: ArbitraryPrecisionInteger,
|
||||
secret p: ArbitraryPrecisionInteger
|
||||
)
|
||||
throws -> ArbitraryPrecisionInteger
|
||||
{
|
||||
guard x < self.fieldSize else { throw CryptoBoringWrapperError.incorrectParameterSize }
|
||||
return try self.pow(x, p, using: CCryptoBoringSSL_BN_mod_exp_mont_consttime)
|
||||
}
|
||||
@@ -219,17 +275,19 @@ extension FiniteFieldArithmeticContext {
|
||||
) throws -> ArbitraryPrecisionInteger {
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
guard result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
a.withUnsafeBignumPointer { aPtr in
|
||||
b.withUnsafeBignumPointer { bPtr in
|
||||
self.fieldSize.withUnsafeBignumPointer { modPtr in
|
||||
self.withUnsafeBN_MONT_CTX { montCtxPtr in
|
||||
method(resultPtr, aPtr, bPtr, modPtr, self.bnCtx, montCtxPtr)
|
||||
guard
|
||||
result.withUnsafeMutableBignumPointer({ resultPtr in
|
||||
a.withUnsafeBignumPointer { aPtr in
|
||||
b.withUnsafeBignumPointer { bPtr in
|
||||
self.fieldSize.withUnsafeBignumPointer { modPtr in
|
||||
self.withUnsafeBN_MONT_CTX { montCtxPtr in
|
||||
method(resultPtr, aPtr, bPtr, modPtr, self.bnCtx, montCtxPtr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}) == 1 else {
|
||||
}) == 1
|
||||
else {
|
||||
throw CryptoBoringWrapperError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
@@ -237,7 +295,11 @@ extension FiniteFieldArithmeticContext {
|
||||
}
|
||||
|
||||
/// Some functions require a `BN_MONT_CTX` parameter: this obtains one for the field modulus with a scoped lifetime.
|
||||
fileprivate func withUnsafeBN_MONT_CTX<T>(_ body: (UnsafePointer<BN_MONT_CTX>) throws -> T) rethrows -> T {
|
||||
fileprivate func withUnsafeBN_MONT_CTX<T>(
|
||||
_ body: (UnsafePointer<BN_MONT_CTX>) throws -> T
|
||||
)
|
||||
rethrows -> T
|
||||
{
|
||||
try self.fieldSize.withUnsafeBignumPointer { modPtr in
|
||||
// We force unwrap here because this call can only fail if the allocator is broken, and if
|
||||
// the allocator fails we don't have long to live anyway.
|
||||
@@ -247,4 +309,4 @@ extension FiniteFieldArithmeticContext {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@@ -48,7 +48,8 @@ extension SystemRandomNumberGenerator {
|
||||
@inlinable
|
||||
package static func randomBytes(count: Int) -> [UInt8] {
|
||||
Array(unsafeUninitializedCapacity: count) { buffer, initializedCount in
|
||||
UnsafeMutableRawBufferPointer(start: buffer.baseAddress, count: buffer.count).initializeWithRandomBytes(count: count)
|
||||
UnsafeMutableRawBufferPointer(start: buffer.baseAddress, count: buffer.count)
|
||||
.initializeWithRandomBytes(count: count)
|
||||
initializedCount = count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,13 @@ enum OpenSSLAESCFBImpl {
|
||||
key.withUnsafeBytes { keyBufferPtr in
|
||||
iv.withUnsafeMutableBytes { ivBufferPtr in
|
||||
var key = AES_KEY()
|
||||
precondition(CCryptoBoringSSL_AES_set_encrypt_key(keyBufferPtr.baseAddress, UInt32(keyBufferPtr.count * 8), &key) == 0)
|
||||
precondition(
|
||||
CCryptoBoringSSL_AES_set_encrypt_key(
|
||||
keyBufferPtr.baseAddress,
|
||||
UInt32(keyBufferPtr.count * 8),
|
||||
&key
|
||||
) == 0
|
||||
)
|
||||
CCryptoBoringSSL_AES_cfb128_encrypt(
|
||||
plaintextBufferPtr.baseAddress,
|
||||
ciphertextBufferPtr.baseAddress,
|
||||
|
||||
@@ -47,7 +47,13 @@ enum OpenSSLAESCTRImpl {
|
||||
nonce.withUnsafeMutableBytes { nonceBufferPtr in
|
||||
withUnsafeMutableBytes(of: &ecountBytes) { ecountBufferPtr in
|
||||
var key = AES_KEY()
|
||||
precondition(CCryptoBoringSSL_AES_set_encrypt_key(keyBufferPtr.baseAddress, UInt32(keyBufferPtr.count * 8), &key) == 0)
|
||||
precondition(
|
||||
CCryptoBoringSSL_AES_set_encrypt_key(
|
||||
keyBufferPtr.baseAddress,
|
||||
UInt32(keyBufferPtr.count * 8),
|
||||
&key
|
||||
) == 0
|
||||
)
|
||||
CCryptoBoringSSL_AES_ctr128_encrypt(
|
||||
plaintextBufferPtr.baseAddress,
|
||||
ciphertextBufferPtr.baseAddress,
|
||||
|
||||
@@ -22,7 +22,12 @@ import Foundation
|
||||
|
||||
extension BoringSSLAEAD {
|
||||
/// Seal a given message.
|
||||
func seal<Plaintext: DataProtocol, Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(message: Plaintext, key: SymmetricKey, nonce: Nonce, authenticatedData: AuthenticatedData) throws -> (ciphertext: Data, tag: Data) {
|
||||
func seal<Plaintext: DataProtocol, Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||
message: Plaintext,
|
||||
key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> (ciphertext: Data, tag: Data) {
|
||||
do {
|
||||
let context = try AEADContext(cipher: self, key: key)
|
||||
return try context.seal(message: message, nonce: nonce, authenticatedData: authenticatedData)
|
||||
@@ -32,10 +37,19 @@ extension BoringSSLAEAD {
|
||||
}
|
||||
|
||||
/// Open a given message.
|
||||
func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(combinedCiphertextAndTag: Data, key: SymmetricKey, nonce: Nonce, authenticatedData: AuthenticatedData) throws -> Data {
|
||||
func open<Nonce: ContiguousBytes, AuthenticatedData: DataProtocol>(
|
||||
combinedCiphertextAndTag: Data,
|
||||
key: SymmetricKey,
|
||||
nonce: Nonce,
|
||||
authenticatedData: AuthenticatedData
|
||||
) throws -> Data {
|
||||
do {
|
||||
let context = try AEADContext(cipher: self, key: key)
|
||||
return try context.open(combinedCiphertextAndTag: combinedCiphertextAndTag, nonce: nonce, authenticatedData: authenticatedData)
|
||||
return try context.open(
|
||||
combinedCiphertextAndTag: combinedCiphertextAndTag,
|
||||
nonce: nonce,
|
||||
authenticatedData: authenticatedData
|
||||
)
|
||||
} catch CryptoBoringWrapperError.underlyingCoreCryptoError(let errorCode) {
|
||||
throw CryptoKitError.underlyingCoreCryptoError(error: errorCode)
|
||||
}
|
||||
@@ -44,8 +58,12 @@ extension BoringSSLAEAD {
|
||||
|
||||
enum OpenSSLAESGCMSIVImpl {
|
||||
@inlinable
|
||||
static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>
|
||||
(key: SymmetricKey, message: Plaintext, nonce: AES.GCM._SIV.Nonce?, authenticatedData: AuthenticatedData? = nil) throws -> AES.GCM._SIV.SealedBox {
|
||||
static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>(
|
||||
key: SymmetricKey,
|
||||
message: Plaintext,
|
||||
nonce: AES.GCM._SIV.Nonce?,
|
||||
authenticatedData: AuthenticatedData? = nil
|
||||
) throws -> AES.GCM._SIV.SealedBox {
|
||||
let nonce = nonce ?? AES.GCM._SIV.Nonce()
|
||||
|
||||
let aead = try Self._backingAEAD(key: key)
|
||||
@@ -53,23 +71,46 @@ enum OpenSSLAESGCMSIVImpl {
|
||||
let ciphertext: Data
|
||||
let tag: Data
|
||||
if let ad = authenticatedData {
|
||||
(ciphertext, tag) = try aead.seal(message: message, key: key, nonce: nonce, authenticatedData: ad)
|
||||
(ciphertext, tag) = try aead.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
(ciphertext, tag) = try aead.seal(message: message, key: key, nonce: nonce, authenticatedData: [])
|
||||
(ciphertext, tag) = try aead.seal(
|
||||
message: message,
|
||||
key: key,
|
||||
nonce: nonce,
|
||||
authenticatedData: []
|
||||
)
|
||||
}
|
||||
|
||||
return try AES.GCM._SIV.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func open<AuthenticatedData: DataProtocol>
|
||||
(key: SymmetricKey, sealedBox: AES.GCM._SIV.SealedBox, authenticatedData: AuthenticatedData? = nil) throws -> Data {
|
||||
static func open<AuthenticatedData: DataProtocol>(
|
||||
key: SymmetricKey,
|
||||
sealedBox: AES.GCM._SIV.SealedBox,
|
||||
authenticatedData: AuthenticatedData? = nil
|
||||
) throws -> Data {
|
||||
let aead = try Self._backingAEAD(key: key)
|
||||
|
||||
if let ad = authenticatedData {
|
||||
return try aead.open(combinedCiphertextAndTag: sealedBox.combined.dropFirst(AES.GCM._SIV.nonceByteCount), key: key, nonce: sealedBox.nonce, authenticatedData: ad)
|
||||
return try aead.open(
|
||||
combinedCiphertextAndTag: sealedBox.combined.dropFirst(AES.GCM._SIV.nonceByteCount),
|
||||
key: key,
|
||||
nonce: sealedBox.nonce,
|
||||
authenticatedData: ad
|
||||
)
|
||||
} else {
|
||||
return try aead.open(combinedCiphertextAndTag: sealedBox.combined.dropFirst(AES.GCM._SIV.nonceByteCount), key: key, nonce: sealedBox.nonce, authenticatedData: [])
|
||||
return try aead.open(
|
||||
combinedCiphertextAndTag: sealedBox.combined.dropFirst(AES.GCM._SIV.nonceByteCount),
|
||||
key: key,
|
||||
nonce: sealedBox.nonce,
|
||||
authenticatedData: []
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,24 +19,44 @@ import CryptoBoringWrapper
|
||||
import Foundation
|
||||
|
||||
enum OpenSSLChaCha20CTRImpl {
|
||||
static func encrypt<M: DataProtocol, N: ContiguousBytes>(key: SymmetricKey, message: M, counter: UInt32, nonce: N) throws -> Data {
|
||||
static func encrypt<M: DataProtocol, N: ContiguousBytes>(
|
||||
key: SymmetricKey,
|
||||
message: M,
|
||||
counter: UInt32,
|
||||
nonce: N
|
||||
) throws -> Data {
|
||||
guard key.bitCount == Insecure.ChaCha20CTR.keyBitsCount else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
// If our message, conforming to DataProtocol, happens to be allocated contiguously in memory, then we can grab the first, and only, contiguous region and operate on it
|
||||
if message.regions.count == 1 {
|
||||
return self._encryptContiguous(key: key, message: message.regions.first!, counter: counter, nonce: nonce)
|
||||
return self._encryptContiguous(
|
||||
key: key,
|
||||
message: message.regions.first!,
|
||||
counter: counter,
|
||||
nonce: nonce
|
||||
)
|
||||
} else {
|
||||
// Otherwise we need to consolidate the noncontiguous bytes by instantiating an Array<UInt8>
|
||||
let contiguousMessage = Array(message)
|
||||
return self._encryptContiguous(key: key, message: contiguousMessage, counter: counter, nonce: nonce)
|
||||
return self._encryptContiguous(
|
||||
key: key,
|
||||
message: contiguousMessage,
|
||||
counter: counter,
|
||||
nonce: nonce
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A fast-path for encrypting contiguous data. Also inlinable to gain specialization information.
|
||||
@inlinable
|
||||
static func _encryptContiguous<Plaintext: ContiguousBytes, Nonce: ContiguousBytes>(key: SymmetricKey, message: Plaintext, counter: UInt32, nonce: Nonce) -> Data {
|
||||
static func _encryptContiguous<Plaintext: ContiguousBytes, Nonce: ContiguousBytes>(
|
||||
key: SymmetricKey,
|
||||
message: Plaintext,
|
||||
counter: UInt32,
|
||||
nonce: Nonce
|
||||
) -> Data {
|
||||
key.withUnsafeBytes { keyPtr in
|
||||
nonce.withUnsafeBytes { noncePtr in
|
||||
message.withUnsafeBytes { plaintextPtr in
|
||||
|
||||
@@ -117,7 +117,9 @@ struct OpenSSLGroupScalar<C: OpenSSLSupportedNISTCurve>: GroupScalar, CustomStri
|
||||
/// - Returns: The deserialized scalar
|
||||
init(bytes: Data, reductionIsModOrder: Bool = false) throws {
|
||||
if reductionIsModOrder {
|
||||
self.init(try ArbitraryPrecisionInteger(bytes: bytes).modulo(C.group.weierstrassCoefficients.field))
|
||||
self.init(
|
||||
try ArbitraryPrecisionInteger(bytes: bytes).modulo(C.group.weierstrassCoefficients.field)
|
||||
)
|
||||
} else {
|
||||
self.init(try ArbitraryPrecisionInteger(bytes: bytes).modulo(C.group.order))
|
||||
}
|
||||
@@ -247,7 +249,7 @@ struct OpenSSLHashToCurve<C: OpenSSLSupportedNISTCurve>: HashToGroup {
|
||||
|
||||
static func hashToScalar(_ data: Data, domainSeparationString: Data) throws -> GE.Scalar {
|
||||
// Force-unwrap: HashToField is guaranteed to produce one or more elements, so .first is always non-nil.
|
||||
return try HashToField<C>.hashToField(
|
||||
try HashToField<C>.hashToField(
|
||||
data,
|
||||
outputElementCount: 1,
|
||||
dst: Data("HashToScalar-".utf8) + domainSeparationString,
|
||||
@@ -261,10 +263,18 @@ struct OpenSSLHashToCurve<C: OpenSSLSupportedNISTCurve>: HashToGroup {
|
||||
precondition(!domainSeparationString.isEmpty, "DST must be non-empty.")
|
||||
switch C.self {
|
||||
case is P256.Type:
|
||||
let point = try! EllipticCurvePoint(hashing: data, to: P256.group, domainSeparationTag: domainSeparationString)
|
||||
let point = try! EllipticCurvePoint(
|
||||
hashing: data,
|
||||
to: P256.group,
|
||||
domainSeparationTag: domainSeparationString
|
||||
)
|
||||
return OpenSSLCurvePoint(ecPoint: point)
|
||||
case is P384.Type:
|
||||
let point = try! EllipticCurvePoint(hashing: data, to: P384.group, domainSeparationTag: domainSeparationString)
|
||||
let point = try! EllipticCurvePoint(
|
||||
hashing: data,
|
||||
to: P384.group,
|
||||
domainSeparationTag: domainSeparationString
|
||||
)
|
||||
return OpenSSLCurvePoint(ecPoint: point)
|
||||
case is P521.Type:
|
||||
// BoringSSL doesn't have implementation of P521_XMD:SHA-512_SSWU_RO_.
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Crypto
|
||||
|
||||
#if canImport(Darwin) || swift(>=5.9.1)
|
||||
import Foundation
|
||||
#else
|
||||
@@ -31,23 +32,36 @@ internal struct BoringSSLPBKDF2 {
|
||||
/// - outputByteCount: The length in bytes of resulting symmetric key.
|
||||
/// - rounds: The number of rounds which should be used to perform key derivation.
|
||||
/// - Returns: The derived symmetric key.
|
||||
static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(from password: Passphrase, salt: Salt, using hashFunction: KDF.Insecure.PBKDF2.HashFunction, outputByteCount: Int, rounds: Int) throws -> SymmetricKey {
|
||||
static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(
|
||||
from password: Passphrase,
|
||||
salt: Salt,
|
||||
using hashFunction: KDF.Insecure.PBKDF2.HashFunction,
|
||||
outputByteCount: Int,
|
||||
rounds: Int
|
||||
) throws -> SymmetricKey {
|
||||
// This should be SecureBytes, but we can't use that here.
|
||||
var derivedKeyData = Data(count: outputByteCount)
|
||||
|
||||
|
||||
let rc = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
|
||||
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
|
||||
return saltBytes.withUnsafeBytes { saltBytes -> Int32 in
|
||||
let passwordBytes: ContiguousBytes = password.regions.count == 1 ? password.regions.first! : Array(password)
|
||||
let passwordBytes: ContiguousBytes =
|
||||
password.regions.count == 1 ? password.regions.first! : Array(password)
|
||||
return passwordBytes.withUnsafeBytes { passwordBytes -> Int32 in
|
||||
return CCryptoBoringSSL_PKCS5_PBKDF2_HMAC(passwordBytes.baseAddress!, passwordBytes.count,
|
||||
saltBytes.baseAddress!, saltBytes.count,
|
||||
UInt32(rounds), hashFunction.digest,
|
||||
derivedKeyBytes.count, derivedKeyBytes.baseAddress!)
|
||||
CCryptoBoringSSL_PKCS5_PBKDF2_HMAC(
|
||||
passwordBytes.baseAddress!,
|
||||
passwordBytes.count,
|
||||
saltBytes.baseAddress!,
|
||||
saltBytes.count,
|
||||
UInt32(rounds),
|
||||
hashFunction.digest,
|
||||
derivedKeyBytes.count,
|
||||
derivedKeyBytes.baseAddress!
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Crypto
|
||||
|
||||
#if canImport(Darwin) || swift(>=5.9.1)
|
||||
import Foundation
|
||||
#else
|
||||
@@ -30,16 +31,23 @@ internal struct CommonCryptoPBKDF2 {
|
||||
/// - outputByteCount: The length in bytes of resulting symmetric key.
|
||||
/// - rounds: The number of rounds which should be used to perform key derivation.
|
||||
/// - Returns: The derived symmetric key.
|
||||
static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(from password: Passphrase, salt: Salt, using hashFunction: KDF.Insecure.PBKDF2.HashFunction, outputByteCount: Int, rounds: Int) throws -> SymmetricKey {
|
||||
static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(
|
||||
from password: Passphrase,
|
||||
salt: Salt,
|
||||
using hashFunction: KDF.Insecure.PBKDF2.HashFunction,
|
||||
outputByteCount: Int,
|
||||
rounds: Int
|
||||
) throws -> SymmetricKey {
|
||||
// This should be SecureBytes, but we can't use that here.
|
||||
var derivedKeyData = Data(count: outputByteCount)
|
||||
|
||||
|
||||
let derivationStatus = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
|
||||
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
|
||||
return saltBytes.withUnsafeBytes { saltBytes -> Int32 in
|
||||
let passwordBytes: ContiguousBytes = password.regions.count == 1 ? password.regions.first! : Array(password)
|
||||
let passwordBytes: ContiguousBytes =
|
||||
password.regions.count == 1 ? password.regions.first! : Array(password)
|
||||
return passwordBytes.withUnsafeBytes { passwordBytes -> Int32 in
|
||||
return CCKeyDerivationPBKDF(
|
||||
CCKeyDerivationPBKDF(
|
||||
CCPBKDFAlgorithm(kCCPBKDF2),
|
||||
passwordBytes.baseAddress!,
|
||||
passwordBytes.count,
|
||||
@@ -48,15 +56,16 @@ internal struct CommonCryptoPBKDF2 {
|
||||
hashFunction.ccHash,
|
||||
UInt32(rounds),
|
||||
derivedKeyBytes.baseAddress!,
|
||||
derivedKeyBytes.count)
|
||||
derivedKeyBytes.count
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if derivationStatus != kCCSuccess {
|
||||
throw CryptoKitError.underlyingCoreCryptoError(error: derivationStatus)
|
||||
}
|
||||
|
||||
|
||||
return SymmetricKey(data: derivedKeyData)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,14 +12,15 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
import Crypto
|
||||
|
||||
#if canImport(Darwin) || swift(>=5.9.1)
|
||||
import Foundation
|
||||
#else
|
||||
@preconcurrency import Foundation
|
||||
#endif
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
|
||||
#if canImport(Android)
|
||||
import Android
|
||||
@@ -35,7 +36,7 @@ private func getPageSize() -> Int {
|
||||
}
|
||||
#else
|
||||
private func getPageSize() -> Int {
|
||||
return Int(sysconf(Int32(_SC_PAGESIZE)))
|
||||
Int(sysconf(Int32(_SC_PAGESIZE)))
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -50,33 +51,48 @@ internal struct BoringSSLScrypt {
|
||||
/// - blockSize: The block size to be used by the algorithm.
|
||||
/// - parallelism: The parallelism factor indicating how many threads should be run in parallel.
|
||||
/// - Returns: The derived symmetric key.
|
||||
static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(from password: Passphrase, salt: Salt, outputByteCount: Int, rounds: Int, blockSize: Int, parallelism: Int, maxMemory: Int? = nil) throws -> SymmetricKey {
|
||||
static func deriveKey<Passphrase: DataProtocol, Salt: DataProtocol>(
|
||||
from password: Passphrase,
|
||||
salt: Salt,
|
||||
outputByteCount: Int,
|
||||
rounds: Int,
|
||||
blockSize: Int,
|
||||
parallelism: Int,
|
||||
maxMemory: Int? = nil
|
||||
) throws -> SymmetricKey {
|
||||
// This should be SecureBytes, but we can't use that here.
|
||||
var derivedKeyData = Data(count: outputByteCount)
|
||||
|
||||
|
||||
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm.
|
||||
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm.
|
||||
// An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight.
|
||||
let maxMemory = maxMemory ?? (128 * rounds * blockSize * parallelism + getPageSize())
|
||||
|
||||
|
||||
let result = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
|
||||
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
|
||||
return saltBytes.withUnsafeBytes { saltBytes -> Int32 in
|
||||
let passwordBytes: ContiguousBytes = password.regions.count == 1 ? password.regions.first! : Array(password)
|
||||
let passwordBytes: ContiguousBytes =
|
||||
password.regions.count == 1 ? password.regions.first! : Array(password)
|
||||
return passwordBytes.withUnsafeBytes { passwordBytes -> Int32 in
|
||||
return CCryptoBoringSSL_EVP_PBE_scrypt(passwordBytes.baseAddress!, passwordBytes.count,
|
||||
saltBytes.baseAddress!, saltBytes.count,
|
||||
UInt64(rounds), UInt64(blockSize),
|
||||
UInt64(parallelism), maxMemory,
|
||||
derivedKeyBytes.baseAddress!, derivedKeyBytes.count)
|
||||
CCryptoBoringSSL_EVP_PBE_scrypt(
|
||||
passwordBytes.baseAddress!,
|
||||
passwordBytes.count,
|
||||
saltBytes.baseAddress!,
|
||||
saltBytes.count,
|
||||
UInt64(rounds),
|
||||
UInt64(blockSize),
|
||||
UInt64(parallelism),
|
||||
maxMemory,
|
||||
derivedKeyBytes.baseAddress!,
|
||||
derivedKeyBytes.count
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
guard result == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
|
||||
return SymmetricKey(data: derivedKeyData)
|
||||
}
|
||||
}
|
||||
@@ -11,13 +11,13 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
import Crypto
|
||||
|
||||
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
|
||||
import CryptoBoringWrapper
|
||||
@_implementationOnly import CCryptoBoringSSL
|
||||
@_implementationOnly import CCryptoBoringSSLShims
|
||||
import Crypto
|
||||
import CryptoBoringWrapper
|
||||
import Foundation
|
||||
|
||||
internal struct BoringSSLRSAPublicKey: Sendable {
|
||||
private var backing: Backing
|
||||
@@ -67,7 +67,6 @@ internal struct BoringSSLRSAPublicKey: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal struct BoringSSLRSAPrivateKey: Sendable {
|
||||
private var backing: Backing
|
||||
|
||||
@@ -79,7 +78,13 @@ internal struct BoringSSLRSAPrivateKey: Sendable {
|
||||
self.backing = try Backing(derRepresentation: derRepresentation)
|
||||
}
|
||||
|
||||
init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
|
||||
init(
|
||||
n: some ContiguousBytes,
|
||||
e: some ContiguousBytes,
|
||||
d: some ContiguousBytes,
|
||||
p: some ContiguousBytes,
|
||||
q: some ContiguousBytes
|
||||
) throws {
|
||||
self.backing = try Backing(n: n, e: e, d: d, p: p, q: q)
|
||||
}
|
||||
|
||||
@@ -113,42 +118,60 @@ internal struct BoringSSLRSAPrivateKey: Sendable {
|
||||
}
|
||||
|
||||
extension BoringSSLRSAPrivateKey {
|
||||
internal func signature<D: Digest>(for digest: D, padding: _RSA.Signing.Padding) throws -> _RSA.Signing.RSASignature {
|
||||
return try self.backing.signature(for: digest, padding: padding)
|
||||
}
|
||||
|
||||
internal func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
|
||||
return try self.backing.decrypt(data, padding: padding)
|
||||
internal func signature<D: Digest>(
|
||||
for digest: D,
|
||||
padding: _RSA.Signing.Padding
|
||||
) throws
|
||||
-> _RSA.Signing.RSASignature
|
||||
{
|
||||
try self.backing.signature(for: digest, padding: padding)
|
||||
}
|
||||
|
||||
internal func blindSignature<D: DataProtocol>(for message: D) throws -> _RSA.BlindSigning.BlindSignature {
|
||||
return try self.backing.blindSignature(for: message)
|
||||
internal func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
|
||||
try self.backing.decrypt(data, padding: padding)
|
||||
}
|
||||
}
|
||||
|
||||
internal func blindSignature<D: DataProtocol>(
|
||||
for message: D
|
||||
) throws
|
||||
-> _RSA.BlindSigning.BlindSignature
|
||||
{
|
||||
try self.backing.blindSignature(for: message)
|
||||
}
|
||||
}
|
||||
|
||||
extension BoringSSLRSAPublicKey {
|
||||
func isValidSignature<D: Digest>(_ signature: _RSA.Signing.RSASignature, for digest: D, padding: _RSA.Signing.Padding) -> Bool {
|
||||
return self.backing.isValidSignature(signature, for: digest, padding: padding)
|
||||
func isValidSignature<D: Digest>(
|
||||
_ signature: _RSA.Signing.RSASignature,
|
||||
for digest: D,
|
||||
padding: _RSA.Signing.Padding
|
||||
) -> Bool {
|
||||
self.backing.isValidSignature(signature, for: digest, padding: padding)
|
||||
}
|
||||
|
||||
|
||||
internal func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
|
||||
return try self.backing.encrypt(data, padding: padding)
|
||||
try self.backing.encrypt(data, padding: padding)
|
||||
}
|
||||
|
||||
internal func blind<H: HashFunction>(
|
||||
_ message: _RSA.BlindSigning.PreparedMessage,
|
||||
parameters: _RSA.BlindSigning.Parameters<H>
|
||||
) throws -> _RSA.BlindSigning.BlindingResult {
|
||||
return try self.backing.blind(message, parameters: parameters)
|
||||
try self.backing.blind(message, parameters: parameters)
|
||||
}
|
||||
|
||||
internal func finalize<H: HashFunction>(
|
||||
_ signature: _RSA.BlindSigning.BlindSignature,
|
||||
for message: _RSA.BlindSigning.PreparedMessage,
|
||||
blindingInverse: _RSA.BlindSigning.BlindingInverse,
|
||||
parameters: _RSA.BlindSigning.Parameters<H>
|
||||
_ signature: _RSA.BlindSigning.BlindSignature,
|
||||
for message: _RSA.BlindSigning.PreparedMessage,
|
||||
blindingInverse: _RSA.BlindSigning.BlindingInverse,
|
||||
parameters: _RSA.BlindSigning.Parameters<H>
|
||||
) throws -> _RSA.Signing.RSASignature {
|
||||
return try self.backing.finalize(signature, for: message, blindingInverse: blindingInverse, parameters: parameters)
|
||||
try self.backing.finalize(
|
||||
signature,
|
||||
for: message,
|
||||
blindingInverse: blindingInverse,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +185,9 @@ extension BoringSSLRSAPublicKey {
|
||||
|
||||
fileprivate init(copying other: Backing) {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer))
|
||||
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
|
||||
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
|
||||
)
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPublicKey)
|
||||
}
|
||||
|
||||
@@ -175,7 +200,7 @@ extension BoringSSLRSAPublicKey {
|
||||
// fall back to the PKCS#1 form if that parse fails.
|
||||
do {
|
||||
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
|
||||
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
guard let key = CCryptoBoringSSL_PEM_read_bio_RSA_PUBKEY(bio, nil, nil, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
@@ -186,7 +211,7 @@ extension BoringSSLRSAPublicKey {
|
||||
} catch {
|
||||
do {
|
||||
let rsaPublicKey = try pemRepresentation.withUTF8 { utf8Ptr in
|
||||
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
@@ -217,7 +242,7 @@ extension BoringSSLRSAPublicKey {
|
||||
// fall back to the PKCS#1 form if that parse fails.
|
||||
do {
|
||||
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
|
||||
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
guard let key = CCryptoBoringSSL_d2i_RSA_PUBKEY_bio(bio, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
@@ -228,7 +253,7 @@ extension BoringSSLRSAPublicKey {
|
||||
} catch {
|
||||
do {
|
||||
let rsaPublicKey = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
|
||||
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
@@ -249,16 +274,18 @@ extension BoringSSLRSAPublicKey {
|
||||
let e = try ArbitraryPrecisionInteger(bytes: e)
|
||||
|
||||
// Create BoringSSL RSA key.
|
||||
guard let rsaPtr = n.withUnsafeBignumPointer({ n in
|
||||
e.withUnsafeBignumPointer { e in
|
||||
CCryptoBoringSSL_RSA_new_public_key(n, e)
|
||||
}
|
||||
}) else { throw CryptoKitError.internalBoringSSLError() }
|
||||
guard
|
||||
let rsaPtr = n.withUnsafeBignumPointer({ n in
|
||||
e.withUnsafeBignumPointer { e in
|
||||
CCryptoBoringSSL_RSA_new_public_key(n, e)
|
||||
}
|
||||
})
|
||||
else { throw CryptoKitError.internalBoringSSLError() }
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPtr)
|
||||
}
|
||||
|
||||
fileprivate var pkcs1DERRepresentation: Data {
|
||||
return BIOHelper.withWritableMemoryBIO { bio in
|
||||
BIOHelper.withWritableMemoryBIO { bio in
|
||||
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let rc = CCryptoBoringSSL_i2d_RSAPublicKey_bio(bio, rsaPublicKey)
|
||||
precondition(rc == 1)
|
||||
@@ -268,11 +295,12 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
|
||||
fileprivate var pkcs1PEMRepresentation: String {
|
||||
return ASN1.PEMDocument(type: _RSA.PKCS1PublicKeyType, derBytes: self.pkcs1DERRepresentation).pemString
|
||||
ASN1.PEMDocument(type: _RSA.PKCS1PublicKeyType, derBytes: self.pkcs1DERRepresentation)
|
||||
.pemString
|
||||
}
|
||||
|
||||
fileprivate var derRepresentation: Data {
|
||||
return BIOHelper.withWritableMemoryBIO { bio in
|
||||
BIOHelper.withWritableMemoryBIO { bio in
|
||||
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let rc = CCryptoBoringSSL_i2d_RSA_PUBKEY_bio(bio, rsaPublicKey)
|
||||
precondition(rc == 1)
|
||||
@@ -282,7 +310,8 @@ extension BoringSSLRSAPublicKey {
|
||||
}
|
||||
|
||||
fileprivate var pemRepresentation: String {
|
||||
return ASN1.PEMDocument(type: _RSA.SPKIPublicKeyType, derBytes: self.derRepresentation).pemString
|
||||
ASN1.PEMDocument(type: _RSA.SPKIPublicKeyType, derBytes: self.derRepresentation)
|
||||
.pemString
|
||||
}
|
||||
|
||||
fileprivate var keySizeInBits: Int {
|
||||
@@ -290,7 +319,11 @@ extension BoringSSLRSAPublicKey {
|
||||
return Int(CCryptoBoringSSL_RSA_size(rsaPublicKey)) * 8
|
||||
}
|
||||
|
||||
fileprivate func isValidSignature<D: Digest>(_ signature: _RSA.Signing.RSASignature, for digest: D, padding: _RSA.Signing.Padding) -> Bool {
|
||||
fileprivate func isValidSignature<D: Digest>(
|
||||
_ signature: _RSA.Signing.RSASignature,
|
||||
for digest: D,
|
||||
padding: _RSA.Signing.Padding
|
||||
) -> Bool {
|
||||
let hashDigestType = try! DigestType(forDigestType: D.self)
|
||||
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
|
||||
@@ -333,13 +366,19 @@ extension BoringSSLRSAPublicKey {
|
||||
return rc == 1
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
|
||||
|
||||
fileprivate func encrypt<D: DataProtocol>(
|
||||
_ data: D,
|
||||
padding: _RSA.Encryption.Padding
|
||||
) throws
|
||||
-> Data
|
||||
{
|
||||
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let outputSize = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
|
||||
var output = Data(count: outputSize)
|
||||
|
||||
let contiguousData: ContiguousBytes = data.regions.count == 1 ? data.regions.first! : Array(data)
|
||||
let contiguousData: ContiguousBytes =
|
||||
data.regions.count == 1 ? data.regions.first! : Array(data)
|
||||
try output.withUnsafeMutableBytes { bufferPtr in
|
||||
try contiguousData.withUnsafeBytes { dataPtr in
|
||||
// `nil` 'engine' defaults to the standard implementation with no hooks
|
||||
@@ -355,7 +394,7 @@ extension BoringSSLRSAPublicKey {
|
||||
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING)
|
||||
switch digest {
|
||||
case .sha1:
|
||||
break // default case, nothing to set
|
||||
break // default case, nothing to set
|
||||
case .sha256:
|
||||
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_oaep_md(ctx, CCryptoBoringSSL_EVP_sha256())
|
||||
}
|
||||
@@ -369,7 +408,10 @@ extension BoringSSLRSAPublicKey {
|
||||
dataPtr.baseAddress,
|
||||
dataPtr.count
|
||||
)
|
||||
precondition(writtenLength == bufferPtr.count, "PKEY encrypt actual written length should match RSA key size.")
|
||||
precondition(
|
||||
writtenLength == bufferPtr.count,
|
||||
"PKEY encrypt actual written length should match RSA key size."
|
||||
)
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
@@ -426,8 +468,13 @@ extension BoringSSLRSAPublicKey {
|
||||
let blindedMessage = try Data(bytesOf: z, paddedToSize: modulusByteCount)
|
||||
|
||||
// 12. output blinded_msg, inv
|
||||
let blindingInverse = _RSA.BlindSigning.BlindingInverse(rawRepresentation: try Data(bytesOf: inv, paddedToSize: modulusByteCount))
|
||||
return _RSA.BlindSigning.BlindingResult(blindedMessage: blindedMessage, inverse: blindingInverse)
|
||||
let blindingInverse = _RSA.BlindSigning.BlindingInverse(
|
||||
rawRepresentation: try Data(bytesOf: inv, paddedToSize: modulusByteCount)
|
||||
)
|
||||
return _RSA.BlindSigning.BlindingResult(
|
||||
blindedMessage: blindedMessage,
|
||||
inverse: blindingInverse
|
||||
)
|
||||
}
|
||||
|
||||
fileprivate func finalize<H: HashFunction>(
|
||||
@@ -454,10 +501,18 @@ extension BoringSSLRSAPublicKey {
|
||||
let s = try finiteField.multiply(z, inv)
|
||||
|
||||
// 4. sig = int_to_bytes(s, modulus_len)
|
||||
let sig = _RSA.Signing.RSASignature(rawRepresentation: try Data(bytesOf: s, paddedToSize: modulusByteCount))
|
||||
let sig = _RSA.Signing.RSASignature(
|
||||
rawRepresentation: try Data(bytesOf: s, paddedToSize: modulusByteCount)
|
||||
)
|
||||
|
||||
// 5. result = RSASSA-PSS-VERIFY(pk, msg, sig) with Hash, MGF, and salt_len as defined in the parameters
|
||||
let result = try BlindSigningHelpers.RSASSAPSSVerify(rsaPublicKey: rsaPublicKey, modulusByteCount: modulusByteCount, message: message, signature: sig, parameters: parameters)
|
||||
let result = try BlindSigningHelpers.RSASSAPSSVerify(
|
||||
rsaPublicKey: rsaPublicKey,
|
||||
modulusByteCount: modulusByteCount,
|
||||
message: message,
|
||||
signature: sig,
|
||||
parameters: parameters
|
||||
)
|
||||
|
||||
// 6. If result = "valid signature", output sig, else raise an "invalid signature" error and stop
|
||||
if result {
|
||||
@@ -495,7 +550,9 @@ extension BoringSSLRSAPrivateKey {
|
||||
|
||||
fileprivate init(copying other: Backing) {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
let rsaPrivateKey = CCryptoBoringSSL_RSAPrivateKey_dup(CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer))
|
||||
let rsaPrivateKey = CCryptoBoringSSL_RSAPrivateKey_dup(
|
||||
CCryptoBoringSSL_EVP_PKEY_get0_RSA(other.pointer)
|
||||
)
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPrivateKey)
|
||||
}
|
||||
|
||||
@@ -504,7 +561,7 @@ extension BoringSSLRSAPrivateKey {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
|
||||
let rsaPrivateKey = try pemRepresentation.withUTF8 { utf8Ptr in
|
||||
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
|
||||
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPrivateKey(bio, nil, nil, nil) else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
@@ -537,8 +594,13 @@ extension BoringSSLRSAPrivateKey {
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPrivateKey)
|
||||
}
|
||||
|
||||
|
||||
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
|
||||
fileprivate init(
|
||||
n: some ContiguousBytes,
|
||||
e: some ContiguousBytes,
|
||||
d: some ContiguousBytes,
|
||||
p: some ContiguousBytes,
|
||||
q: some ContiguousBytes
|
||||
) throws {
|
||||
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
let n = try ArbitraryPrecisionInteger(bytes: n)
|
||||
let e = try ArbitraryPrecisionInteger(bytes: e)
|
||||
@@ -554,29 +616,35 @@ extension BoringSSLRSAPrivateKey {
|
||||
}
|
||||
|
||||
// Create BoringSSL RSA key.
|
||||
guard let rsaPtr = n.withUnsafeBignumPointer({ n in
|
||||
e.withUnsafeBignumPointer { e in
|
||||
d.withUnsafeBignumPointer { d in
|
||||
p.withUnsafeBignumPointer { p in
|
||||
q.withUnsafeBignumPointer { q in
|
||||
dp.withUnsafeBignumPointer { dp in
|
||||
dq.withUnsafeBignumPointer { dq in
|
||||
qi.withUnsafeBignumPointer { qi in
|
||||
CCryptoBoringSSL_RSA_new_private_key(n, e, d, p, q, dp, dq, qi)
|
||||
guard
|
||||
let rsaPtr = n.withUnsafeBignumPointer({ n in
|
||||
e.withUnsafeBignumPointer { e in
|
||||
d.withUnsafeBignumPointer { d in
|
||||
p.withUnsafeBignumPointer { p in
|
||||
q.withUnsafeBignumPointer { q in
|
||||
dp.withUnsafeBignumPointer { dp in
|
||||
dq.withUnsafeBignumPointer { dq in
|
||||
qi.withUnsafeBignumPointer { qi in
|
||||
CCryptoBoringSSL_RSA_new_private_key(n, e, d, p, q, dp, dq, qi)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}) else { throw CryptoKitError.internalBoringSSLError() }
|
||||
})
|
||||
else { throw CryptoKitError.internalBoringSSLError() }
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPtr)
|
||||
}
|
||||
|
||||
private static func pkcs8DERPrivateKey<Bytes: ContiguousBytes>(_ derRepresentation: Bytes) -> OpaquePointer? {
|
||||
return derRepresentation.withUnsafeBytes { derPtr in
|
||||
return BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
private static func pkcs8DERPrivateKey<Bytes: ContiguousBytes>(
|
||||
_ derRepresentation: Bytes
|
||||
)
|
||||
-> OpaquePointer?
|
||||
{
|
||||
derRepresentation.withUnsafeBytes { derPtr in
|
||||
BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
guard let p8 = CCryptoBoringSSL_d2i_PKCS8_PRIV_KEY_INFO_bio(bio, nil) else {
|
||||
return nil
|
||||
}
|
||||
@@ -595,10 +663,14 @@ extension BoringSSLRSAPrivateKey {
|
||||
}
|
||||
}
|
||||
|
||||
private static func pkcs1DERPrivateKey<Bytes: ContiguousBytes>(_ derRepresentation: Bytes) -> OpaquePointer? {
|
||||
return derRepresentation.withUnsafeBytes { derPtr in
|
||||
return BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
return CCryptoBoringSSL_d2i_RSAPrivateKey_bio(bio, nil)
|
||||
private static func pkcs1DERPrivateKey<Bytes: ContiguousBytes>(
|
||||
_ derRepresentation: Bytes
|
||||
)
|
||||
-> OpaquePointer?
|
||||
{
|
||||
derRepresentation.withUnsafeBytes { derPtr in
|
||||
BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
|
||||
CCryptoBoringSSL_d2i_RSAPrivateKey_bio(bio, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -610,7 +682,10 @@ extension BoringSSLRSAPrivateKey {
|
||||
do {
|
||||
let rc = RSA_F4.withBignumPointer { bignumPtr in
|
||||
CCryptoBoringSSL_RSA_generate_key_ex(
|
||||
pointer, CInt(keySize.bitCount), bignumPtr, nil
|
||||
pointer,
|
||||
CInt(keySize.bitCount),
|
||||
bignumPtr,
|
||||
nil
|
||||
)
|
||||
}
|
||||
|
||||
@@ -627,7 +702,7 @@ extension BoringSSLRSAPrivateKey {
|
||||
}
|
||||
|
||||
fileprivate var derRepresentation: Data {
|
||||
return BIOHelper.withWritableMemoryBIO { bio in
|
||||
BIOHelper.withWritableMemoryBIO { bio in
|
||||
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let rc = CCryptoBoringSSL_i2d_RSAPrivateKey_bio(bio, rsaPrivateKey)
|
||||
precondition(rc == 1)
|
||||
@@ -637,9 +712,17 @@ extension BoringSSLRSAPrivateKey {
|
||||
}
|
||||
|
||||
fileprivate var pemRepresentation: String {
|
||||
return BIOHelper.withWritableMemoryBIO { bio in
|
||||
BIOHelper.withWritableMemoryBIO { bio in
|
||||
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let rc = CCryptoBoringSSL_PEM_write_bio_RSAPrivateKey(bio, rsaPrivateKey, nil, nil, 0, nil, nil)
|
||||
let rc = CCryptoBoringSSL_PEM_write_bio_RSAPrivateKey(
|
||||
bio,
|
||||
rsaPrivateKey,
|
||||
nil,
|
||||
nil,
|
||||
0,
|
||||
nil,
|
||||
nil
|
||||
)
|
||||
precondition(rc == 1)
|
||||
|
||||
return try! String(copyingUTF8MemoryBIO: bio)
|
||||
@@ -647,7 +730,7 @@ extension BoringSSLRSAPrivateKey {
|
||||
}
|
||||
|
||||
fileprivate var pkcs8PEMRepresentation: String {
|
||||
return BIOHelper.withWritableMemoryBIO { bio in
|
||||
BIOHelper.withWritableMemoryBIO { bio in
|
||||
let evp = CCryptoBoringSSL_EVP_PKEY_new()
|
||||
defer {
|
||||
CCryptoBoringSSL_EVP_PKEY_free(evp)
|
||||
@@ -668,7 +751,9 @@ extension BoringSSLRSAPrivateKey {
|
||||
|
||||
fileprivate var publicKey: BoringSSLRSAPublicKey {
|
||||
let pkey = CCryptoBoringSSL_EVP_PKEY_new()!
|
||||
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer))
|
||||
let rsaPublicKey = CCryptoBoringSSL_RSAPublicKey_dup(
|
||||
CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
)
|
||||
CCryptoBoringSSL_EVP_PKEY_assign_RSA(pkey, rsaPublicKey)
|
||||
let backing = BoringSSLRSAPublicKey.Backing(
|
||||
takingOwnershipOf: pkey
|
||||
@@ -676,12 +761,17 @@ extension BoringSSLRSAPrivateKey {
|
||||
return BoringSSLRSAPublicKey(backing)
|
||||
}
|
||||
|
||||
fileprivate func signature<D: Digest>(for digest: D, padding: _RSA.Signing.Padding) throws -> _RSA.Signing.RSASignature {
|
||||
fileprivate func signature<D: Digest>(
|
||||
for digest: D,
|
||||
padding: _RSA.Signing.Padding
|
||||
) throws
|
||||
-> _RSA.Signing.RSASignature
|
||||
{
|
||||
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let hashDigestType = try DigestType(forDigestType: D.self)
|
||||
let outputSize = Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey))
|
||||
|
||||
let output = try Array<UInt8>(unsafeUninitializedCapacity: outputSize) { bufferPtr, length in
|
||||
let output = try [UInt8](unsafeUninitializedCapacity: outputSize) { bufferPtr, length in
|
||||
var outputLength = 0
|
||||
|
||||
let rc: CInt = digest.withUnsafeBytes { digestPtr in
|
||||
@@ -733,12 +823,18 @@ extension BoringSSLRSAPrivateKey {
|
||||
return _RSA.Signing.RSASignature(signatureBytes: output)
|
||||
}
|
||||
|
||||
fileprivate func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
|
||||
fileprivate func decrypt<D: DataProtocol>(
|
||||
_ data: D,
|
||||
padding: _RSA.Encryption.Padding
|
||||
) throws
|
||||
-> Data
|
||||
{
|
||||
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let outputSize = Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey))
|
||||
var output = Data(count: outputSize)
|
||||
|
||||
let contiguousData: ContiguousBytes = data.regions.count == 1 ? data.regions.first! : Array(data)
|
||||
let contiguousData: ContiguousBytes =
|
||||
data.regions.count == 1 ? data.regions.first! : Array(data)
|
||||
let writtenLength: CInt = try output.withUnsafeMutableBytes { bufferPtr in
|
||||
try contiguousData.withUnsafeBytes { dataPtr in
|
||||
let ctx = CCryptoBoringSSL_EVP_PKEY_CTX_new(self.pointer, nil)
|
||||
@@ -752,13 +848,12 @@ extension BoringSSLRSAPrivateKey {
|
||||
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING)
|
||||
switch digest {
|
||||
case .sha1:
|
||||
break // default case, nothing to set
|
||||
break // default case, nothing to set
|
||||
case .sha256:
|
||||
CCryptoBoringSSL_EVP_PKEY_CTX_set_rsa_oaep_md(ctx, CCryptoBoringSSL_EVP_sha256())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var writtenLength = bufferPtr.count
|
||||
|
||||
let rc = CCryptoBoringSSLShims_EVP_PKEY_decrypt(
|
||||
@@ -777,11 +872,17 @@ extension BoringSSLRSAPrivateKey {
|
||||
}
|
||||
}
|
||||
|
||||
output.removeSubrange(output.index(output.startIndex, offsetBy: Int(writtenLength)) ..< output.endIndex)
|
||||
output.removeSubrange(
|
||||
output.index(output.startIndex, offsetBy: Int(writtenLength))..<output.endIndex
|
||||
)
|
||||
return output
|
||||
}
|
||||
|
||||
fileprivate func blindSignature<D: DataProtocol>(for message: D) throws -> _RSA.BlindSigning.BlindSignature {
|
||||
fileprivate func blindSignature<D: DataProtocol>(
|
||||
for message: D
|
||||
) throws
|
||||
-> _RSA.BlindSigning.BlindSignature
|
||||
{
|
||||
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
let signatureByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey))
|
||||
|
||||
@@ -789,21 +890,27 @@ extension BoringSSLRSAPrivateKey {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
let messageBytes: ContiguousBytes = message.regions.count == 1 ? message.regions.first! : Array(message)
|
||||
let messageBytes: ContiguousBytes =
|
||||
message.regions.count == 1 ? message.regions.first! : Array(message)
|
||||
|
||||
let signature = try withUnsafeTemporaryAllocation(of: UInt8.self, capacity: signatureByteCount) { signatureBufferPtr in
|
||||
let signature = try withUnsafeTemporaryAllocation(
|
||||
of: UInt8.self,
|
||||
capacity: signatureByteCount
|
||||
) { signatureBufferPtr in
|
||||
try messageBytes.withUnsafeBytes { messageBufferPtr in
|
||||
/// NOTE: BoringSSL promotes the use of `RSA_sign_raw` over `RSA_private_encrypt`.
|
||||
var outputCount = 0
|
||||
guard CCryptoBoringSSL_RSA_sign_raw(
|
||||
rsaPrivateKey,
|
||||
&outputCount,
|
||||
signatureBufferPtr.baseAddress,
|
||||
signatureBufferPtr.count,
|
||||
messageBufferPtr.baseAddress,
|
||||
messageBufferPtr.count,
|
||||
RSA_NO_PADDING
|
||||
) == 1 else {
|
||||
guard
|
||||
CCryptoBoringSSL_RSA_sign_raw(
|
||||
rsaPrivateKey,
|
||||
&outputCount,
|
||||
signatureBufferPtr.baseAddress,
|
||||
signatureBufferPtr.count,
|
||||
messageBufferPtr.baseAddress,
|
||||
messageBufferPtr.count,
|
||||
RSA_NO_PADDING
|
||||
) == 1
|
||||
else {
|
||||
switch CCryptoBoringSSL_ERR_GET_REASON(CCryptoBoringSSL_ERR_peek_last_error()) {
|
||||
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
|
||||
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.messageRepresentativeOutOfRange)
|
||||
@@ -822,27 +929,37 @@ extension BoringSSLRSAPrivateKey {
|
||||
return signature
|
||||
}
|
||||
|
||||
fileprivate func verifyBlindSignature<D: ContiguousBytes>(_ signature: _RSA.BlindSigning.BlindSignature, for blindedMessage: D) throws {
|
||||
fileprivate func verifyBlindSignature<D: ContiguousBytes>(
|
||||
_ signature: _RSA.BlindSigning.BlindSignature,
|
||||
for blindedMessage: D
|
||||
) throws {
|
||||
try signature.withUnsafeBytes { signatureBufferPtr in
|
||||
try blindedMessage.withUnsafeBytes { blindedMessageBufferPtr in
|
||||
try withUnsafeTemporaryAllocation(byteCount: blindedMessageBufferPtr.count, alignment: 1) { verificationBufferPtr in
|
||||
try withUnsafeTemporaryAllocation(byteCount: blindedMessageBufferPtr.count, alignment: 1) {
|
||||
verificationBufferPtr in
|
||||
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
|
||||
var outputCount = 0
|
||||
/// NOTE: BoringSSL promotes the use of `RSA_verify_raw` over `RSA_public_decrypt`.
|
||||
guard CCryptoBoringSSL_RSA_verify_raw(
|
||||
rsaPublicKey,
|
||||
&outputCount,
|
||||
verificationBufferPtr.baseAddress,
|
||||
verificationBufferPtr.count,
|
||||
signatureBufferPtr.baseAddress,
|
||||
signatureBufferPtr.count,
|
||||
RSA_NO_PADDING
|
||||
) == 1 else {
|
||||
guard
|
||||
CCryptoBoringSSL_RSA_verify_raw(
|
||||
rsaPublicKey,
|
||||
&outputCount,
|
||||
verificationBufferPtr.baseAddress,
|
||||
verificationBufferPtr.count,
|
||||
signatureBufferPtr.baseAddress,
|
||||
signatureBufferPtr.count,
|
||||
RSA_NO_PADDING
|
||||
) == 1
|
||||
else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
guard
|
||||
outputCount == blindedMessageBufferPtr.count,
|
||||
memcmp(verificationBufferPtr.baseAddress!, blindedMessageBufferPtr.baseAddress!, blindedMessageBufferPtr.count) == 0
|
||||
memcmp(
|
||||
verificationBufferPtr.baseAddress!,
|
||||
blindedMessageBufferPtr.baseAddress!,
|
||||
blindedMessageBufferPtr.count
|
||||
) == 0
|
||||
else {
|
||||
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.signingFailure)
|
||||
}
|
||||
@@ -868,7 +985,8 @@ enum BlindSigningHelpers {
|
||||
) throws -> Bool {
|
||||
let hashDigestType = try DigestType(forDigestType: H.Digest.self)
|
||||
return H.hash(data: message.rawRepresentation).withUnsafeBytes { messageHashBufferPtr in
|
||||
withUnsafeTemporaryAllocation(byteCount: modulusByteCount, alignment: 1) { encodedMessageBufferPtr in
|
||||
withUnsafeTemporaryAllocation(byteCount: modulusByteCount, alignment: 1) {
|
||||
encodedMessageBufferPtr in
|
||||
signature.withUnsafeBytes { signatureBufferPtr in
|
||||
var outputCount = 0
|
||||
guard
|
||||
@@ -904,18 +1022,21 @@ enum BlindSigningHelpers {
|
||||
message: _RSA.BlindSigning.PreparedMessage,
|
||||
parameters: _RSA.BlindSigning.Parameters<H>
|
||||
) throws -> ArbitraryPrecisionInteger {
|
||||
try withUnsafeTemporaryAllocation(of: UInt8.self, capacity: modulusByteCount) { encodedMessageBufferPtr in
|
||||
try withUnsafeTemporaryAllocation(of: UInt8.self, capacity: modulusByteCount) {
|
||||
encodedMessageBufferPtr in
|
||||
let hashDigestType = try DigestType(forDigestType: H.Digest.self)
|
||||
guard H.hash(data: message.rawRepresentation).withUnsafeBytes({ hashBufferPtr in
|
||||
CCryptoBoringSSL_RSA_padding_add_PKCS1_PSS_mgf1(
|
||||
rsaPublicKey,
|
||||
encodedMessageBufferPtr.baseAddress,
|
||||
hashBufferPtr.baseAddress,
|
||||
hashDigestType.dispatchTable,
|
||||
hashDigestType.dispatchTable,
|
||||
parameters.saltLength
|
||||
)
|
||||
}) == 1 else {
|
||||
guard
|
||||
H.hash(data: message.rawRepresentation).withUnsafeBytes({ hashBufferPtr in
|
||||
CCryptoBoringSSL_RSA_padding_add_PKCS1_PSS_mgf1(
|
||||
rsaPublicKey,
|
||||
encodedMessageBufferPtr.baseAddress,
|
||||
hashBufferPtr.baseAddress,
|
||||
hashDigestType.dispatchTable,
|
||||
hashDigestType.dispatchTable,
|
||||
parameters.saltLength
|
||||
)
|
||||
}) == 1
|
||||
else {
|
||||
switch CCryptoBoringSSL_ERR_GET_REASON(CCryptoBoringSSL_ERR_peek_last_error()) {
|
||||
case RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE:
|
||||
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.messageTooLong)
|
||||
|
||||
@@ -19,6 +19,6 @@ extension CryptoKitError {
|
||||
/// A helper function that packs the value of `ERR_get_error` into the internal error field.
|
||||
@usableFromInline
|
||||
static func internalBoringSSLError() -> CryptoKitError {
|
||||
return .underlyingCoreCryptoError(error: Int32(bitPattern: CCryptoBoringSSL_ERR_get_error()))
|
||||
.underlyingCoreCryptoError(error: Int32(bitPattern: CCryptoBoringSSL_ERR_get_error()))
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,11 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
@testable import CryptoBoringWrapper
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import CryptoBoringWrapper
|
||||
|
||||
final class ArbitraryPrecisionIntegerTests: XCTestCase {
|
||||
func testSimpleArithmetic() {
|
||||
let six = ArbitraryPrecisionInteger(6)
|
||||
@@ -148,9 +150,14 @@ final class ArbitraryPrecisionIntegerTests: XCTestCase {
|
||||
XCTAssertEqual(try ArbitraryPrecisionInteger.random(inclusiveMin: 4, exclusiveMax: 5), 4)
|
||||
|
||||
var previousRandom = ArbitraryPrecisionInteger()
|
||||
for _ in 1 ... 1000 {
|
||||
let exclusiveMax = try ArbitraryPrecisionInteger(bytes: Data(repeating: UInt8.max, count: 2048 / 8))
|
||||
let random = try ArbitraryPrecisionInteger.random(inclusiveMin: 42, exclusiveMax: exclusiveMax)
|
||||
for _ in 1...1000 {
|
||||
let exclusiveMax = try ArbitraryPrecisionInteger(
|
||||
bytes: Data(repeating: UInt8.max, count: 2048 / 8)
|
||||
)
|
||||
let random = try ArbitraryPrecisionInteger.random(
|
||||
inclusiveMin: 42,
|
||||
exclusiveMax: exclusiveMax
|
||||
)
|
||||
XCTAssert(random >= ArbitraryPrecisionInteger(42))
|
||||
XCTAssert(random < exclusiveMax)
|
||||
XCTAssert(random != previousRandom)
|
||||
@@ -196,7 +203,10 @@ final class ArbitraryPrecisionIntegerTests: XCTestCase {
|
||||
|
||||
func testModularInverse() throws {
|
||||
typealias I = ArbitraryPrecisionInteger
|
||||
enum O { case ok(I), throwsError }
|
||||
enum O {
|
||||
case ok(I)
|
||||
case throwsError
|
||||
}
|
||||
typealias Vector = (a: I, mod: I, expectedResult: O)
|
||||
for vector: Vector in [
|
||||
(a: 3, mod: 7, expectedResult: .ok(5)),
|
||||
@@ -206,16 +216,26 @@ final class ArbitraryPrecisionIntegerTests: XCTestCase {
|
||||
] {
|
||||
switch vector.expectedResult {
|
||||
case .ok(let expectedValue):
|
||||
XCTAssertEqual(try vector.a.inverse(modulo: vector.mod), expectedValue, "inverse(\(vector.a), modulo: \(vector.mod))")
|
||||
XCTAssertEqual(
|
||||
try vector.a.inverse(modulo: vector.mod),
|
||||
expectedValue,
|
||||
"inverse(\(vector.a), modulo: \(vector.mod))"
|
||||
)
|
||||
case .throwsError:
|
||||
XCTAssertThrowsError(try vector.a.inverse(modulo: vector.mod), "inverse(\(vector.a), modulo: \(vector.mod)")
|
||||
XCTAssertThrowsError(
|
||||
try vector.a.inverse(modulo: vector.mod),
|
||||
"inverse(\(vector.a), modulo: \(vector.mod)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testModularAddition() throws {
|
||||
typealias I = ArbitraryPrecisionInteger
|
||||
enum O { case ok(I), throwsError }
|
||||
enum O {
|
||||
case ok(I)
|
||||
case throwsError
|
||||
}
|
||||
typealias Vector = (a: I, b: I, mod: I, expectedResult: O)
|
||||
for vector: Vector in [
|
||||
(a: 0, b: 0, mod: 0, expectedResult: .throwsError),
|
||||
@@ -229,16 +249,26 @@ final class ArbitraryPrecisionIntegerTests: XCTestCase {
|
||||
] {
|
||||
switch vector.expectedResult {
|
||||
case .ok(let expectedValue):
|
||||
XCTAssertEqual(try vector.a.add(vector.b, modulo: vector.mod), expectedValue, "\(vector.a) + \(vector.b) (mod \(vector.mod))")
|
||||
XCTAssertEqual(
|
||||
try vector.a.add(vector.b, modulo: vector.mod),
|
||||
expectedValue,
|
||||
"\(vector.a) + \(vector.b) (mod \(vector.mod))"
|
||||
)
|
||||
case .throwsError:
|
||||
XCTAssertThrowsError(try vector.a.add(vector.b, modulo: vector.mod), "\(vector.a) + \(vector.b) (mod \(vector.mod))")
|
||||
XCTAssertThrowsError(
|
||||
try vector.a.add(vector.b, modulo: vector.mod),
|
||||
"\(vector.a) + \(vector.b) (mod \(vector.mod))"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testModularSubtraction() throws {
|
||||
typealias I = ArbitraryPrecisionInteger
|
||||
enum O { case ok(I), throwsError }
|
||||
enum O {
|
||||
case ok(I)
|
||||
case throwsError
|
||||
}
|
||||
typealias Vector = (a: I, b: I, mod: I, expectedResult: O)
|
||||
for vector: Vector in [
|
||||
(a: 0, b: 0, mod: 0, expectedResult: .throwsError),
|
||||
@@ -254,16 +284,26 @@ final class ArbitraryPrecisionIntegerTests: XCTestCase {
|
||||
] {
|
||||
switch vector.expectedResult {
|
||||
case .ok(let expectedValue):
|
||||
XCTAssertEqual(try vector.a.sub(vector.b, modulo: vector.mod), expectedValue, "\(vector.a) - \(vector.b) (mod \(vector.mod))")
|
||||
XCTAssertEqual(
|
||||
try vector.a.sub(vector.b, modulo: vector.mod),
|
||||
expectedValue,
|
||||
"\(vector.a) - \(vector.b) (mod \(vector.mod))"
|
||||
)
|
||||
case .throwsError:
|
||||
XCTAssertThrowsError(try vector.a.sub(vector.b, modulo: vector.mod), "\(vector.a) - \(vector.b) (mod \(vector.mod))")
|
||||
XCTAssertThrowsError(
|
||||
try vector.a.sub(vector.b, modulo: vector.mod),
|
||||
"\(vector.a) - \(vector.b) (mod \(vector.mod))"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testModularMultiplication() throws {
|
||||
typealias I = ArbitraryPrecisionInteger
|
||||
enum O { case ok(I), throwsError }
|
||||
enum O {
|
||||
case ok(I)
|
||||
case throwsError
|
||||
}
|
||||
typealias Vector = (a: I, b: I, mod: I, expectedResult: O)
|
||||
for vector: Vector in [
|
||||
(a: 0, b: 0, mod: 0, expectedResult: .throwsError),
|
||||
@@ -277,9 +317,16 @@ final class ArbitraryPrecisionIntegerTests: XCTestCase {
|
||||
] {
|
||||
switch vector.expectedResult {
|
||||
case .ok(let expectedValue):
|
||||
XCTAssertEqual(try vector.a.mul(vector.b, modulo: vector.mod), expectedValue, "\(vector.a) × \(vector.b) (mod \(vector.mod))")
|
||||
XCTAssertEqual(
|
||||
try vector.a.mul(vector.b, modulo: vector.mod),
|
||||
expectedValue,
|
||||
"\(vector.a) × \(vector.b) (mod \(vector.mod))"
|
||||
)
|
||||
case .throwsError:
|
||||
XCTAssertThrowsError(try vector.a.mul(vector.b, modulo: vector.mod), "\(vector.a) × \(vector.b) (mod \(vector.mod))")
|
||||
XCTAssertThrowsError(
|
||||
try vector.a.mul(vector.b, modulo: vector.mod),
|
||||
"\(vector.a) × \(vector.b) (mod \(vector.mod))"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
@testable import CryptoBoringWrapper
|
||||
|
||||
import XCTest
|
||||
|
||||
@testable import CryptoBoringWrapper
|
||||
|
||||
final class FiniteFieldArithmeticTests: XCTestCase {
|
||||
func testResidue() throws {
|
||||
let ff = try FiniteFieldArithmeticContext(fieldSize: 3)
|
||||
@@ -84,7 +86,7 @@ final class FiniteFieldArithmeticTests: XCTestCase {
|
||||
XCTAssertEqual(try ff.inverse(4), 1)
|
||||
XCTAssertEqual(try ff.inverse(5), 2)
|
||||
XCTAssertEqual(try ff.inverse(6), nil)
|
||||
for i: Int64 in 1 ... 100 {
|
||||
for i: Int64 in 1...100 {
|
||||
let integer = ArbitraryPrecisionInteger(integerLiteral: i)
|
||||
let inverse = try ff.inverse(integer)
|
||||
if i % 3 == 0 {
|
||||
@@ -98,14 +100,16 @@ final class FiniteFieldArithmeticTests: XCTestCase {
|
||||
func testPow() throws {
|
||||
let m: ArbitraryPrecisionInteger = 7
|
||||
let ff = try FiniteFieldArithmeticContext(fieldSize: m)
|
||||
for (x, p, expectedResult): (ArbitraryPrecisionInteger, ArbitraryPrecisionInteger, ArbitraryPrecisionInteger) in [
|
||||
(1, 0, 1), (1, 1, 1), (1, 2, 1), (1, 3, 1),
|
||||
(2, 0, 1), (2, 1, 2), (2, 2, 4), (2, 3, 1),
|
||||
(3, 0, 1), (3, 1, 3), (3, 2, 2), (3, 3, 6),
|
||||
(5, 0, 1), (5, 1, 5), (5, 2, 4), (5, 3, 6),
|
||||
(7, 0, 1), (7, 1, 0), (7, 2, 0), (7, 3, 0), // x = m
|
||||
(8, 0, 1), (8, 1, 1), (8, 2, 1), (8, 3, 1), // x > m
|
||||
] {
|
||||
for (x, p, expectedResult): (ArbitraryPrecisionInteger, ArbitraryPrecisionInteger, ArbitraryPrecisionInteger)
|
||||
in [
|
||||
(1, 0, 1), (1, 1, 1), (1, 2, 1), (1, 3, 1),
|
||||
(2, 0, 1), (2, 1, 2), (2, 2, 4), (2, 3, 1),
|
||||
(3, 0, 1), (3, 1, 3), (3, 2, 2), (3, 3, 6),
|
||||
(5, 0, 1), (5, 1, 5), (5, 2, 4), (5, 3, 6),
|
||||
(7, 0, 1), (7, 1, 0), (7, 2, 0), (7, 3, 0), // x = m
|
||||
(8, 0, 1), (8, 1, 1), (8, 2, 1), (8, 3, 1), // x > m
|
||||
]
|
||||
{
|
||||
let message = "\(x)^\(p) (mod \(m))"
|
||||
XCTAssertEqual(try ff.pow(x, p), expectedResult, message)
|
||||
if x < m {
|
||||
@@ -114,7 +118,7 @@ final class FiniteFieldArithmeticTests: XCTestCase {
|
||||
} else {
|
||||
XCTAssertThrowsError(try ff.pow(secret: x, p), message) { error in
|
||||
switch error as? CryptoBoringWrapperError {
|
||||
case .incorrectParameterSize: break // OK
|
||||
case .incorrectParameterSize: break // OK
|
||||
default: XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +200,7 @@ struct ASN1ObjectIdentifier {
|
||||
case ..<40:
|
||||
oidComponents.append(0)
|
||||
oidComponents.append(subcomponents.first!)
|
||||
case 40 ..< 80:
|
||||
case 40..<80:
|
||||
oidComponents.append(1)
|
||||
oidComponents.append(subcomponents.first! - 40)
|
||||
default:
|
||||
@@ -289,7 +289,7 @@ extension ArraySlice where Element == UInt8 {
|
||||
throw ECDHTestErrors.ParseSPKIFailure
|
||||
}
|
||||
|
||||
let oidSlice = self[self.startIndex ... subidentifierEndIndex]
|
||||
let oidSlice = self[self.startIndex...subidentifierEndIndex]
|
||||
self = self[self.index(after: subidentifierEndIndex)...]
|
||||
|
||||
// We need to compact the bits. These are 7-bit integers, which is really awkward.
|
||||
@@ -337,4 +337,4 @@ extension UInt {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
@@ -25,7 +25,16 @@ import XCTest
|
||||
#endif
|
||||
|
||||
extension NISTECDHTests {
|
||||
func testGroupOpenSSL<PrivKey: NISTECPrivateKey & DiffieHellmanKeyAgreement, Curve: OpenSSLSupportedNISTCurve>(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type, file: StaticString = #file, line: UInt = #line) {
|
||||
func testGroupOpenSSL<
|
||||
PrivKey: NISTECPrivateKey & DiffieHellmanKeyAgreement,
|
||||
Curve: OpenSSLSupportedNISTCurve
|
||||
>(
|
||||
group: ECDHTestGroup,
|
||||
privateKeys: PrivKey.Type,
|
||||
onCurve curve: Curve.Type,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) {
|
||||
for testVector in group.tests {
|
||||
do {
|
||||
let pkBytes = try Array(hexString: testVector.publicKey)
|
||||
@@ -43,18 +52,41 @@ extension NISTECDHTests {
|
||||
|
||||
XCTAssertEqual(Array(result.ss), Array(expectedResult), file: file, line: line)
|
||||
} catch ECDHTestErrors.PublicKeyFailure {
|
||||
XCTAssert(testVector.flags.contains("CompressedPoint") || testVector.result == "invalid" || testVector.flags.contains("InvalidPublic") || testVector.flags.contains("InvalidAsn"), file: file, line: line)
|
||||
XCTAssert(
|
||||
testVector.flags.contains("CompressedPoint") || testVector.result == "invalid"
|
||||
|| testVector.flags.contains("InvalidPublic")
|
||||
|| testVector.flags.contains("InvalidAsn"),
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
} catch ECDHTestErrors.ParseSPKIFailure {
|
||||
XCTAssert(testVector.flags.contains("InvalidAsn") || testVector.flags.contains("UnnamedCurve"), file: file, line: line)
|
||||
XCTAssert(
|
||||
testVector.flags.contains("InvalidAsn") || testVector.flags.contains("UnnamedCurve"),
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
} catch {
|
||||
if testVector.result == "valid" {
|
||||
XCTAssert(testVector.tcId == 31 || testVector.tcId == 20 || testVector.tcId == 25, file: file, line: line)
|
||||
XCTAssert(
|
||||
testVector.tcId == 31 || testVector.tcId == 20 || testVector.tcId == 25,
|
||||
file: file,
|
||||
line: line
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testGroupPointOpenSSL<PrivKey: NISTECPrivateKey & DiffieHellmanKeyAgreement, Curve: OpenSSLSupportedNISTCurve>(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type, file: StaticString = #file, line: UInt = #line) {
|
||||
func testGroupPointOpenSSL<
|
||||
PrivKey: NISTECPrivateKey & DiffieHellmanKeyAgreement,
|
||||
Curve: OpenSSLSupportedNISTCurve
|
||||
>(
|
||||
group: ECDHTestGroup,
|
||||
privateKeys: PrivKey.Type,
|
||||
onCurve curve: Curve.Type,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) {
|
||||
for testVector in group.tests {
|
||||
do {
|
||||
let pkBytes = try Array(hexString: testVector.publicKey)
|
||||
@@ -86,7 +118,12 @@ extension NISTECDHTests {
|
||||
}
|
||||
}
|
||||
|
||||
private func padKeyIfNecessary<Curve: OpenSSLSupportedNISTCurve>(curve: Curve.Type, vector: String, file: StaticString = #file, line: UInt = #line) throws -> [UInt8] {
|
||||
private func padKeyIfNecessary<Curve: OpenSSLSupportedNISTCurve>(
|
||||
curve: Curve.Type,
|
||||
vector: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) throws -> [UInt8] {
|
||||
// There are a few edge cases here.
|
||||
//
|
||||
// First, our raw bytes function requires the
|
||||
@@ -107,7 +144,10 @@ extension NISTECDHTests {
|
||||
privateBytes = privateKeyVector
|
||||
} else {
|
||||
// Input is too short
|
||||
privateBytes.replaceSubrange((privateBytes.count - privateKeyVector.count) ..< privateBytes.count, with: privateKeyVector)
|
||||
privateBytes.replaceSubrange(
|
||||
(privateBytes.count - privateKeyVector.count)..<privateBytes.count,
|
||||
with: privateKeyVector
|
||||
)
|
||||
}
|
||||
|
||||
return privateBytes
|
||||
@@ -125,7 +165,9 @@ extension NISTECPublicKey {
|
||||
// This means we've only one option: we have to implement "just enough" ASN.1.
|
||||
var derBytes = derBytes[...]
|
||||
let spki = try ASN1SubjectPublicKeyInfo(fromASN1: &derBytes)
|
||||
guard derBytes.count == 0, spki.algorithm.algorithm == ASN1ObjectIdentifier.AlgorithmIdentifier.idEcPublicKey else {
|
||||
guard derBytes.count == 0,
|
||||
spki.algorithm.algorithm == ASN1ObjectIdentifier.AlgorithmIdentifier.idEcPublicKey
|
||||
else {
|
||||
throw ECDHTestErrors.ParseSPKIFailure
|
||||
}
|
||||
|
||||
@@ -138,4 +180,4 @@ extension NISTECPublicKey {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
@@ -28,4 +28,4 @@ extension DERTests {
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
##===----------------------------------------------------------------------===##
|
||||
##
|
||||
## This source file is part of the SwiftCrypto open source project
|
||||
##
|
||||
## Copyright (c) 2024 Apple Inc. and the SwiftCrypto project authors
|
||||
## Licensed under Apache License v2.0
|
||||
##
|
||||
## See LICENSE.txt for license information
|
||||
## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
##
|
||||
## SPDX-License-Identifier: Apache-2.0
|
||||
##
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# The upstream soundness check only supports _excluding_ specific files using
|
||||
# an ignore file, but we want to only _include_ some specific files based on
|
||||
# patterns. That's fine, we'll invert the predicate here to create the ignore
|
||||
# file on the fly, then run the same command as the upstream soundness check.
|
||||
repo_root=$(git rev-parse --show-toplevel)
|
||||
git -C "${repo_root}" ls-files \
|
||||
'*.swift' \
|
||||
':(exclude)*/*Boring*/*.swift' \
|
||||
':(exclude)*_boring.swift' \
|
||||
> "${repo_root}/.swiftformatignore"
|
||||
Reference in new issue
Block a user