mirror of
https://github.com/apple/swift-crypto
synced 2026-11-26 04:47:49 +00:00
## Motivation Xcode 27 is now available[^1] so it's time to merge in our 5.x branch to main and release 5.0. ## Modifications See "Release Notes" section below for overview of changes and links to the PRs that landed on the 5.x branch during the beta period. ## Result The main branch will be ready to tag a 5.0 release. [^1]: https://developer.apple.com/download/all/?q=Xcode%2027 --- ## Release Notes Swift Crypto 5.0 aligns the cross-platform API surface with CryptoKit as shipped in Xcode 27 (CryptoKit-383.2.1), and takes the opportunity to streamline the package for both adopters and maintainers. Most users will be able to depend on the 1.0.0, 2.0.0, 3.0.0, 4.0.0, or 5.0.0 series of releases. To do so, please use the following dependency in your `Package.swift`: ```swift .package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "6.0.0"), ``` ### Requires Swift 6.2 The package now declares 6.2 as the minimum Swift version in its package manifest. ### New span-based API CryptoKit's new non-allocating, span-based entry points are now available cross-platform: - `SymmetricKey` gains `bytes: RawSpan`, `init(copying: RawSpan)`, `init(copyingWithZeroing: inout MutableRawSpan)`, and `init(size:initializingWith:)` which initializes the key through an `inout OutputRawSpan`. - `HashFunction` gains `update(bytes: RawSpan)` and `hash(bytes: RawSpan)`, and `Digest` gains `init?(copying: RawSpan)`. - `HMAC` gains `authenticationCode(for: RawSpan, using:)`. - `HKDF` gains `deriveKey(inputKeyMaterial:salt:info:output:)` writing into an `inout OutputRawSpan`, along with span-based `extract` and `expand`. The existing `DataProtocol` overload now has a fast path for contiguous salt and info. - `AES.GCM` and `ChaChaPoly` gain in-place `seal(inPlace:using:nonce:authenticating:tag:)` and `open(inPlace:using:nonce:authenticating:tag:)` over `MutableRawSpan`, and their `Nonce` types gain `bytes: RawSpan` and `init(copying: RawSpan)`. ### Single-use KEM keys A new `KEMOneTimePrivateKey` protocol, refining `~Copyable` and `Sendable`, provides a `consuming func decapsulate(_:)` so a decapsulation key cannot be reused. Conforming types are `MLKEM768.OneTimePrivateKey`, `MLKEM1024.OneTimePrivateKey`, and `XWingMLKEM768X25519.OneTimePrivateKey`. ### Extensible enums Historically Swift Crypto needed a new major version each time CryptoKit added a case to a non-frozen enum, because Swift Crypto is not built with library evolution. All public non-frozen enums are now marked `@nonexhaustive` (SE-0487), which should remove that reason for future major bumps. Adopters who do not switch over these enums should not need to widen their version constraints again. ### Other changes - Symbols that were previously marked `@_spi(...) public` have been made internal; they were never intended to be available. - `@available` annotations have been removed from `Crypto`; they are unused in all supported compilation modes. - Some internal reference types are now marked `final` - Some unused code, e.g. `ECDSASignature.derBytes`, is removed. ### Build and packaging - The `CCryptoBoringSSLShims` target is removed, along with all `bindMemory(to:)` calls. - The `.gyb` templates for nonces, digests, ECDH, ECDSA, MLDSA, and MLKEM are removed and the generated Swift is checked in. The BoringSSL backend templates for MLDSA and MLKEM remain. - Conditional compilation is simplified to `#if canImport(CryptoKit)`; branches that could never be taken are gone. - Developing the BoringSSL backend on macOS is no longer supported. Use the Dev Container configuration now shipped in the repository, or build on the target platform. - Warnings are silenced for vendored C sources: `-Wshorten-64-to-32` for BoringSSL and `macro-redefined` for XKCP. CI builds with `-warnings-as-errors`. ### Commits The changes in this release were reviewed and merged to the 5.x branch during the beta period: -0a26a9e3[5.x] Align with CryptoKit APIs from Xcode 27 beta 1 (#442) -8ee9962f[5.x] Align with CryptoKit APIs from Xcode 27 beta 2 (#444) -ce8db476[5.x] Align with CryptoKit APIs from Xcode 27 beta 4 (#453) -15b0fb5b[5.x] Adopt CheckImplementationOnly and CI with -warnings-as-errors (#454) -b3746b14[5.x] Remove bindMemory(to:) calls and the CCryptoBoringSSLShims target (#455) -57782dc6[5.x] Remove duplicate imports from gyb-generated MLDSA backend code (#458) -2c45ca2f[5.x] Remove unused internal code path: ECDSASignature.derBytes (#457) -33785f67[5.x] Mark some class types as final (#456) -2e074efb[5.x] Remove native SwiftPM build-system workaround in CI (#461) -20f90497[5.x] Align with CryptoKit from Xcode 27 beta 6 (#462) --------- Co-authored-by: Dmitry <45711841+darkdi@users.noreply.github.com> Co-authored-by: Cory Benfield <lukasa@apple.com>
643 lines
26 KiB
Swift
643 lines
26 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// 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.
|
|
|
|
#if canImport(CryptoKit)
|
|
@_exported import CryptoKit
|
|
#else
|
|
#if hasFeature(SourceWarningControl)
|
|
@diagnose(ImplementationOnlyDeprecated, as: ignored) @_implementationOnly import CCryptoBoringSSL
|
|
#else
|
|
@_implementationOnly import CCryptoBoringSSL
|
|
#endif
|
|
#if canImport(FoundationEssentials)
|
|
import FoundationEssentials
|
|
#else
|
|
import Foundation
|
|
#endif
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
extension MLDSA65 {
|
|
/// A ML-DSA-65 private key.
|
|
struct InternalPrivateKey: @unchecked Sendable {
|
|
private var backing: Backing
|
|
|
|
/// Initialize a ML-DSA-65 private key from a random seed.
|
|
init() throws {
|
|
self.backing = try Backing()
|
|
}
|
|
|
|
/// Initialize a ML-DSA-65 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 {
|
|
self.backing = try Backing(seedRepresentation: seedRepresentation)
|
|
}
|
|
|
|
/// The seed from which this private key was generated.
|
|
var seedRepresentation: Data {
|
|
self.backing.seed
|
|
}
|
|
|
|
/// The public key associated with this private key.
|
|
var publicKey: InternalPublicKey {
|
|
self.backing.publicKey
|
|
}
|
|
|
|
/// Generate a signature for the given data.
|
|
///
|
|
/// - Parameter data: The message to sign.
|
|
///
|
|
/// - Returns: The signature of the message.
|
|
func signature<D: DataProtocol>(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.
|
|
func signature<D: DataProtocol, C: DataProtocol>(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: MLDSA65_private_key
|
|
var seed: Data
|
|
|
|
/// Initialize a ML-DSA-65 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: MLDSA65.InternalPublicKey.Backing.byteCount
|
|
) { publicKeyPtr in
|
|
guard
|
|
CCryptoBoringSSL_MLDSA65_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-65 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_MLDSA65_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: InternalPublicKey {
|
|
InternalPublicKey(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<D: DataProtocol, C: DataProtocol>(for data: D, context: C?) throws -> Data {
|
|
var signature = Data(repeating: 0, count: MLDSA65.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_MLDSA65_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(MLDSA65_PRIVATE_KEY_BYTES)
|
|
}
|
|
}
|
|
}
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
extension MLDSA65 {
|
|
/// A ML-DSA-65 public key.
|
|
struct InternalPublicKey: @unchecked Sendable {
|
|
private var backing: Backing
|
|
|
|
fileprivate init(privateKeyBacking: InternalPrivateKey.Backing) {
|
|
self.backing = Backing(privateKeyBacking: privateKeyBacking)
|
|
}
|
|
|
|
/// Initialize a ML-DSA-65 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 {
|
|
self.backing = try Backing(rawRepresentation: rawRepresentation)
|
|
}
|
|
|
|
/// The raw binary representation of the public key.
|
|
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.
|
|
func isValidSignature<S: DataProtocol, D: DataProtocol>(_ 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.
|
|
func isValidSignature<S: DataProtocol, D: DataProtocol, C: DataProtocol>(
|
|
_ 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: MLDSA65_public_key
|
|
|
|
init(privateKeyBacking: InternalPrivateKey.Backing) {
|
|
self.key = .init()
|
|
CCryptoBoringSSL_MLDSA65_public_from_private(&self.key, &privateKeyBacking.key)
|
|
}
|
|
|
|
/// Initialize a ML-DSA-65 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 == MLDSA65.InternalPublicKey.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_MLDSA65_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, MLDSA65.InternalPublicKey.Backing.byteCount)
|
|
defer { CCryptoBoringSSL_CBB_cleanup(&cbb) }
|
|
CCryptoBoringSSL_MLDSA65_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<S: DataProtocol, D: DataProtocol, C: DataProtocol>(
|
|
_ 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_MLDSA65_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(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 signature in bytes.
|
|
private static let signatureByteCount = Int(MLDSA65_SIGNATURE_BYTES)
|
|
}
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
extension MLDSA87 {
|
|
/// A ML-DSA-87 private key.
|
|
struct InternalPrivateKey: @unchecked Sendable {
|
|
private var backing: Backing
|
|
|
|
/// Initialize a ML-DSA-87 private key from a random seed.
|
|
init() throws {
|
|
self.backing = try Backing()
|
|
}
|
|
|
|
/// Initialize a ML-DSA-87 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 {
|
|
self.backing = try Backing(seedRepresentation: seedRepresentation)
|
|
}
|
|
|
|
/// The seed from which this private key was generated.
|
|
var seedRepresentation: Data {
|
|
self.backing.seed
|
|
}
|
|
|
|
/// The public key associated with this private key.
|
|
var publicKey: InternalPublicKey {
|
|
self.backing.publicKey
|
|
}
|
|
|
|
/// Generate a signature for the given data.
|
|
///
|
|
/// - Parameter data: The message to sign.
|
|
///
|
|
/// - Returns: The signature of the message.
|
|
func signature<D: DataProtocol>(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.
|
|
func signature<D: DataProtocol, C: DataProtocol>(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: MLDSA87_private_key
|
|
var seed: Data
|
|
|
|
/// Initialize a ML-DSA-87 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: MLDSA87.InternalPublicKey.Backing.byteCount
|
|
) { publicKeyPtr in
|
|
guard
|
|
CCryptoBoringSSL_MLDSA87_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-87 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_MLDSA87_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: InternalPublicKey {
|
|
InternalPublicKey(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<D: DataProtocol, C: DataProtocol>(for data: D, context: C?) throws -> Data {
|
|
var signature = Data(repeating: 0, count: MLDSA87.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_MLDSA87_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(MLDSA87_PRIVATE_KEY_BYTES)
|
|
}
|
|
}
|
|
}
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
extension MLDSA87 {
|
|
/// A ML-DSA-87 public key.
|
|
struct InternalPublicKey: @unchecked Sendable {
|
|
private var backing: Backing
|
|
|
|
fileprivate init(privateKeyBacking: InternalPrivateKey.Backing) {
|
|
self.backing = Backing(privateKeyBacking: privateKeyBacking)
|
|
}
|
|
|
|
/// Initialize a ML-DSA-87 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 {
|
|
self.backing = try Backing(rawRepresentation: rawRepresentation)
|
|
}
|
|
|
|
/// The raw binary representation of the public key.
|
|
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.
|
|
func isValidSignature<S: DataProtocol, D: DataProtocol>(_ 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.
|
|
func isValidSignature<S: DataProtocol, D: DataProtocol, C: DataProtocol>(
|
|
_ 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: MLDSA87_public_key
|
|
|
|
init(privateKeyBacking: InternalPrivateKey.Backing) {
|
|
self.key = .init()
|
|
CCryptoBoringSSL_MLDSA87_public_from_private(&self.key, &privateKeyBacking.key)
|
|
}
|
|
|
|
/// Initialize a ML-DSA-87 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 == MLDSA87.InternalPublicKey.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_MLDSA87_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, MLDSA87.InternalPublicKey.Backing.byteCount)
|
|
defer { CCryptoBoringSSL_CBB_cleanup(&cbb) }
|
|
CCryptoBoringSSL_MLDSA87_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<S: DataProtocol, D: DataProtocol, C: DataProtocol>(
|
|
_ 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_MLDSA87_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(MLDSA87_PUBLIC_KEY_BYTES)
|
|
}
|
|
}
|
|
}
|
|
|
|
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
|
extension MLDSA87 {
|
|
/// The size of the signature in bytes.
|
|
private static let signatureByteCount = Int(MLDSA87_SIGNATURE_BYTES)
|
|
}
|
|
|
|
enum MLDSA {
|
|
/// The size of the seed in bytes.
|
|
static let seedByteCount = 32
|
|
}
|
|
|
|
#endif // canImport(CryptoKit)
|