diff --git a/Sources/_CryptoExtras/CMakeLists.txt b/Sources/_CryptoExtras/CMakeLists.txt index 21290594..6582d439 100644 --- a/Sources/_CryptoExtras/CMakeLists.txt +++ b/Sources/_CryptoExtras/CMakeLists.txt @@ -41,7 +41,7 @@ add_library(_CryptoExtras "Key Derivation/PBKDF2/PBKDF2.swift" "Key Derivation/Scrypt/BoringSSL/Scrypt_boring.swift" "Key Derivation/Scrypt/Scrypt.swift" - "MLDSA/MLDSA65_boring.swift" + "MLDSA/MLDSA_boring.swift" "MLKEM/MLKEM_boring.swift" "OPRFs/OPRF.swift" "OPRFs/OPRFClient.swift" diff --git a/Sources/_CryptoExtras/MLDSA/MLDSA65_boring.swift b/Sources/_CryptoExtras/MLDSA/MLDSA_boring.swift similarity index 95% rename from Sources/_CryptoExtras/MLDSA/MLDSA65_boring.swift rename to Sources/_CryptoExtras/MLDSA/MLDSA_boring.swift index 64843040..975243bb 100644 --- a/Sources/_CryptoExtras/MLDSA/MLDSA65_boring.swift +++ b/Sources/_CryptoExtras/MLDSA/MLDSA_boring.swift @@ -12,6 +12,10 @@ // //===----------------------------------------------------------------------===// +// MARK: - Generated file, do NOT edit +// any edits of this file WILL be overwritten and thus discarded +// see section `gyb` in `README` for details. + @_implementationOnly import CCryptoBoringSSL import Crypto import Foundation @@ -86,7 +90,7 @@ extension MLDSA65 { self.seed = try withUnsafeTemporaryAllocation( of: UInt8.self, - capacity: MLDSA65.seedByteCount + capacity: MLDSA.seedByteCount ) { seedPtr in try withUnsafeTemporaryAllocation( of: UInt8.self, @@ -102,7 +106,7 @@ extension MLDSA65 { throw CryptoKitError.internalBoringSSLError() } - return Data(bytes: seedPtr.baseAddress!, count: MLDSA65.seedByteCount) + return Data(bytes: seedPtr.baseAddress!, count: MLDSA.seedByteCount) } } } @@ -113,7 +117,7 @@ extension MLDSA65 { /// /// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 32 bytes long. init(seedRepresentation: some DataProtocol) throws { - guard seedRepresentation.count == MLDSA65.seedByteCount else { + guard seedRepresentation.count == MLDSA.seedByteCount else { throw CryptoKitError.incorrectKeySize } @@ -125,7 +129,7 @@ extension MLDSA65 { CCryptoBoringSSL_MLDSA65_private_key_from_seed( &self.key, seedPtr.baseAddress, - MLDSA65.seedByteCount + MLDSA.seedByteCount ) }) == 1 else { @@ -172,7 +176,7 @@ extension MLDSA65 { } /// The size of the private key in bytes. - static let byteCount = 4032 + static let byteCount = Int(MLDSA65_PRIVATE_KEY_BYTES) } } } @@ -311,16 +315,18 @@ extension MLDSA65 { } /// The size of the public key in bytes. - static let byteCount = 1952 + static let byteCount = Int(MLDSA65_PUBLIC_KEY_BYTES) } } } @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) extension MLDSA65 { - /// The size of the seed in bytes. - private static let seedByteCount = 32 - /// The size of the signature in bytes. - private static let signatureByteCount = 3309 + private static let signatureByteCount = Int(MLDSA65_SIGNATURE_BYTES) +} + +private enum MLDSA { + /// The size of the seed in bytes. + fileprivate static let seedByteCount = 32 } diff --git a/Sources/_CryptoExtras/MLDSA/MLDSA_boring.swift.gyb b/Sources/_CryptoExtras/MLDSA/MLDSA_boring.swift.gyb new file mode 100644 index 00000000..734dfffc --- /dev/null +++ b/Sources/_CryptoExtras/MLDSA/MLDSA_boring.swift.gyb @@ -0,0 +1,337 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// MARK: - Generated file, do NOT edit +// any edits of this file WILL be overwritten and thus discarded +// see section `gyb` in `README` for details. + +@_implementationOnly import CCryptoBoringSSL +import Crypto +import Foundation +%{ + parameter_sets = ["65"] +}% +% for parameter_set in parameter_sets: + +/// A module-lattice-based digital signature algorithm that provides security against quantum computing attacks. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +public enum MLDSA${parameter_set} {} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension MLDSA${parameter_set} { + /// A ML-DSA-${parameter_set} private key. + public struct PrivateKey: Sendable { + private var backing: Backing + + /// Initialize a ML-DSA-${parameter_set} private key from a random seed. + public init() throws { + self.backing = try Backing() + } + + /// Initialize a ML-DSA-${parameter_set} private key from a seed. + /// + /// - Parameter seedRepresentation: The seed to use to generate the private key. + /// + /// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 32 bytes long. + public init(seedRepresentation: some DataProtocol) throws { + self.backing = try Backing(seedRepresentation: seedRepresentation) + } + + /// The seed from which this private key was generated. + public var seedRepresentation: Data { + self.backing.seed + } + + /// The public key associated with this private key. + public var publicKey: PublicKey { + self.backing.publicKey + } + + /// Generate a signature for the given data. + /// + /// - Parameter data: The message to sign. + /// + /// - Returns: The signature of the message. + public func signature(for data: D) throws -> Data { + let context: Data? = nil + return try self.backing.signature(for: data, context: context) + } + + /// Generate a signature for the given data. + /// + /// - Parameters: + /// - data: The message to sign. + /// - context: The context to use for the signature. + /// + /// - Returns: The signature of the message. + public func signature(for data: D, context: C) throws -> Data { + try self.backing.signature(for: data, context: context) + } + + /// The size of the private key in bytes. + static let byteCount = Backing.byteCount + + fileprivate final class Backing { + fileprivate var key: MLDSA${parameter_set}_private_key + var seed: Data + + /// Initialize a ML-DSA-${parameter_set} private key from a random seed. + init() throws { + // We have to initialize all members before `self` is captured by the closure + self.key = .init() + self.seed = Data() + + self.seed = try withUnsafeTemporaryAllocation( + of: UInt8.self, + capacity: MLDSA.seedByteCount + ) { seedPtr in + try withUnsafeTemporaryAllocation( + of: UInt8.self, + capacity: MLDSA${parameter_set}.PublicKey.Backing.byteCount + ) { publicKeyPtr in + guard + CCryptoBoringSSL_MLDSA${parameter_set}_generate_key( + publicKeyPtr.baseAddress, + seedPtr.baseAddress, + &self.key + ) == 1 + else { + throw CryptoKitError.internalBoringSSLError() + } + + return Data(bytes: seedPtr.baseAddress!, count: MLDSA.seedByteCount) + } + } + } + + /// Initialize a ML-DSA-${parameter_set} private key from a seed. + /// + /// - Parameter seedRepresentation: The seed to use to generate the private key. + /// + /// - Throws: `CryptoKitError.incorrectKeySize` if the seed is not 32 bytes long. + init(seedRepresentation: some DataProtocol) throws { + guard seedRepresentation.count == MLDSA.seedByteCount else { + throw CryptoKitError.incorrectKeySize + } + + self.key = .init() + self.seed = Data(seedRepresentation) + + guard + self.seed.withUnsafeBytes({ seedPtr in + CCryptoBoringSSL_MLDSA${parameter_set}_private_key_from_seed( + &self.key, + seedPtr.baseAddress, + MLDSA.seedByteCount + ) + }) == 1 + else { + throw CryptoKitError.internalBoringSSLError() + } + } + + /// The public key associated with this private key. + var publicKey: PublicKey { + PublicKey(privateKeyBacking: self) + } + + /// Generate a signature for the given data. + /// + /// - Parameters: + /// - data: The message to sign. + /// - context: The context to use for the signature. + /// + /// - Returns: The signature of the message. + func signature(for data: D, context: C?) throws -> Data { + var signature = Data(repeating: 0, count: MLDSA${parameter_set}.signatureByteCount) + + let rc: CInt = signature.withUnsafeMutableBytes { signaturePtr in + let bytes: ContiguousBytes = data.regions.count == 1 ? data.regions.first! : Array(data) + return bytes.withUnsafeBytes { dataPtr in + context.withUnsafeBytes { contextPtr in + CCryptoBoringSSL_MLDSA${parameter_set}_sign( + signaturePtr.baseAddress, + &self.key, + dataPtr.baseAddress, + dataPtr.count, + contextPtr.baseAddress, + contextPtr.count + ) + } + } + } + + guard rc == 1 else { + throw CryptoKitError.internalBoringSSLError() + } + + return signature + } + + /// The size of the private key in bytes. + static let byteCount = Int(MLDSA${parameter_set}_PRIVATE_KEY_BYTES) + } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension MLDSA${parameter_set} { + /// A ML-DSA-${parameter_set} public key. + public struct PublicKey: Sendable { + private var backing: Backing + + fileprivate init(privateKeyBacking: PrivateKey.Backing) { + self.backing = Backing(privateKeyBacking: privateKeyBacking) + } + + /// Initialize a ML-DSA-${parameter_set} public key from a raw representation. + /// + /// - Parameter rawRepresentation: The public key bytes. + /// + /// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size. + public init(rawRepresentation: some DataProtocol) throws { + self.backing = try Backing(rawRepresentation: rawRepresentation) + } + + /// The raw binary representation of the public key. + public var rawRepresentation: Data { + self.backing.rawRepresentation + } + + /// Verify a signature for the given data. + /// + /// - Parameters: + /// - signature: The signature to verify. + /// - data: The message to verify the signature against. + /// + /// - Returns: `true` if the signature is valid, `false` otherwise. + public func isValidSignature(_ signature: S, for data: D) -> Bool { + let context: Data? = nil + return self.backing.isValidSignature(signature, for: data, context: context) + } + + /// Verify a signature for the given data. + /// + /// - Parameters: + /// - signature: The signature to verify. + /// - data: The message to verify the signature against. + /// - context: The context to use for the signature verification. + /// + /// - Returns: `true` if the signature is valid, `false` otherwise. + public func isValidSignature( + _ signature: S, + for data: D, + context: C + ) -> Bool { + self.backing.isValidSignature(signature, for: data, context: context) + } + + /// The size of the public key in bytes. + static let byteCount = Backing.byteCount + + fileprivate final class Backing { + private var key: MLDSA${parameter_set}_public_key + + init(privateKeyBacking: PrivateKey.Backing) { + self.key = .init() + CCryptoBoringSSL_MLDSA${parameter_set}_public_from_private(&self.key, &privateKeyBacking.key) + } + + /// Initialize a ML-DSA-${parameter_set} public key from a raw representation. + /// + /// - Parameter rawRepresentation: The public key bytes. + /// + /// - Throws: `CryptoKitError.incorrectKeySize` if the raw representation is not the correct size. + init(rawRepresentation: some DataProtocol) throws { + guard rawRepresentation.count == MLDSA${parameter_set}.PublicKey.Backing.byteCount else { + throw CryptoKitError.incorrectKeySize + } + + self.key = .init() + + let bytes: ContiguousBytes = + rawRepresentation.regions.count == 1 + ? rawRepresentation.regions.first! + : Array(rawRepresentation) + try bytes.withUnsafeBytes { rawBuffer in + try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in + var cbs = CBS(data: buffer.baseAddress, len: buffer.count) + guard CCryptoBoringSSL_MLDSA${parameter_set}_parse_public_key(&self.key, &cbs) == 1 else { + throw CryptoKitError.internalBoringSSLError() + } + } + } + } + + /// The raw binary representation of the public key. + var rawRepresentation: Data { + var cbb = CBB() + // The following BoringSSL functions can only fail on allocation failure, which we define as impossible. + CCryptoBoringSSL_CBB_init(&cbb, MLDSA${parameter_set}.PublicKey.Backing.byteCount) + defer { CCryptoBoringSSL_CBB_cleanup(&cbb) } + CCryptoBoringSSL_MLDSA${parameter_set}_marshal_public_key(&cbb, &self.key) + return Data(bytes: CCryptoBoringSSL_CBB_data(&cbb), count: CCryptoBoringSSL_CBB_len(&cbb)) + } + + /// Verify a signature for the given data. + /// + /// - Parameters: + /// - signature: The signature to verify. + /// - data: The message to verify the signature against. + /// - context: The context to use for the signature verification. + /// + /// - Returns: `true` if the signature is valid, `false` otherwise. + func isValidSignature( + _ signature: S, + for data: D, + context: C? + ) -> Bool { + let signatureBytes: ContiguousBytes = + signature.regions.count == 1 ? signature.regions.first! : Array(signature) + return signatureBytes.withUnsafeBytes { signaturePtr in + let dataBytes: ContiguousBytes = data.regions.count == 1 ? data.regions.first! : Array(data) + let rc: CInt = dataBytes.withUnsafeBytes { dataPtr in + context.withUnsafeBytes { contextPtr in + CCryptoBoringSSL_MLDSA${parameter_set}_verify( + &self.key, + signaturePtr.baseAddress, + signaturePtr.count, + dataPtr.baseAddress, + dataPtr.count, + contextPtr.baseAddress, + contextPtr.count + ) + } + } + return rc == 1 + } + } + + /// The size of the public key in bytes. + static let byteCount = Int(MLDSA${parameter_set}_PUBLIC_KEY_BYTES) + } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *) +extension MLDSA${parameter_set} { + /// The size of the signature in bytes. + private static let signatureByteCount = Int(MLDSA${parameter_set}_SIGNATURE_BYTES) +} +% end + +private enum MLDSA { + /// The size of the seed in bytes. + fileprivate static let seedByteCount = 32 +}