mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b51f1d6845 | ||
|
|
faad1cf4fd | ||
|
|
629f0b679d | ||
|
|
953b34a601 | ||
|
|
710deacf79 | ||
|
|
a234f8a62e | ||
|
|
9c1b699540 | ||
|
|
5ac5632286 | ||
|
|
cba358dec9 | ||
|
|
c433cd3341 |
No files matched your search
+14
-8
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version:5.6
|
||||
// swift-tools-version:5.7
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
@@ -89,12 +89,11 @@ let package = Package(
|
||||
"crypto/bio/socket.c"
|
||||
],
|
||||
cSettings: [
|
||||
/*
|
||||
* This define is required on Windows, but because we need older
|
||||
* versions of SPM, we cannot conditionally define this on Windows
|
||||
* only. Unconditionally define it instead.
|
||||
*/
|
||||
.define("WIN32_LEAN_AND_MEAN"),
|
||||
// These defines come from BoringSSL's build system
|
||||
.define("_HAS_EXCEPTIONS", to: "0", .when(platforms: [Platform.windows])),
|
||||
.define("WIN32_LEAN_AND_MEAN", .when(platforms: [Platform.windows])),
|
||||
.define("NOMINMAX", .when(platforms: [Platform.windows])),
|
||||
.define("_CRT_SECURE_NO_WARNINGS", .when(platforms: [Platform.windows])),
|
||||
/*
|
||||
* These defines are required on Wasm/WASI, to disable use of pthread.
|
||||
*/
|
||||
@@ -144,7 +143,14 @@ let package = Package(
|
||||
]
|
||||
),
|
||||
.executableTarget(name: "crypto-shasum", dependencies: ["Crypto"]),
|
||||
.testTarget(name: "CryptoTests", dependencies: ["Crypto"], swiftSettings: swiftSettings),
|
||||
.testTarget(
|
||||
name: "CryptoTests",
|
||||
dependencies: ["Crypto"],
|
||||
resources: [
|
||||
.copy("HPKE/hpke-test-vectors.json"),
|
||||
],
|
||||
swiftSettings: swiftSettings
|
||||
),
|
||||
.testTarget(name: "_CryptoExtrasTests", dependencies: ["_CryptoExtras"]),
|
||||
],
|
||||
cxxLanguageStandard: .cxx11
|
||||
|
||||
@@ -108,14 +108,15 @@ If you believe you have identified a vulnerability in Swift Crypto, please [repo
|
||||
|
||||
### Swift versions
|
||||
|
||||
The most recent versions of Swift Crypto support Swift 5.6 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
||||
The most recent versions of Swift Crypto support Swift 5.7 and newer. The minimum Swift version supported by Swift Crypto releases are detailed below:
|
||||
|
||||
Swift Crypto | Minimum Swift Version
|
||||
------------------|----------------------
|
||||
`2.0.0 ..< 2.1.0` | 5.2
|
||||
`2.1.0 ..< 2.2.0` | 5.4
|
||||
`2.2.0 ..< 2.4.2` | 5.5
|
||||
`2.4.2 ...` | 5.6
|
||||
`2.4.2 ..< 3.1.0` | 5.6
|
||||
`3.1.0 ...` | 5.7
|
||||
|
||||
### Compatibility
|
||||
|
||||
|
||||
@@ -24,60 +24,67 @@ typealias AESGCMImpl = OpenSSLAESGCMImpl
|
||||
import Foundation
|
||||
|
||||
extension AES {
|
||||
/// AES in GCM mode with 128-bit tags.
|
||||
/// The Advanced Encryption Standard (AES) Galois Counter Mode (GCM) cipher
|
||||
/// suite.
|
||||
public enum GCM: Cipher {
|
||||
static let tagByteCount = 16
|
||||
static let defaultNonceByteCount = 12
|
||||
|
||||
/// Encrypts and authenticates data using AES-GCM.
|
||||
/// Secures the given plaintext message with encryption and an
|
||||
/// authentication tag that covers both the encrypted data and
|
||||
/// additional data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The message to encrypt and authenticate
|
||||
/// - key: An encryption key of 128, 192 or 256 bits
|
||||
/// - nonce: An Nonce for AES-GCM encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce()
|
||||
/// - authenticatedData: Data to authenticate as part of the seal
|
||||
/// - Returns: A sealed box returning the authentication tag (seal) and the ciphertext
|
||||
/// - Throws: CipherError errors
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``AES.GCM.Nonce()``.
|
||||
/// - authenticatedData: Additional data to be authenticated.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
public static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil, authenticating authenticatedData: AuthenticatedData) throws -> SealedBox {
|
||||
return try AESGCMImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: authenticatedData)
|
||||
}
|
||||
|
||||
/// Encrypts and authenticates data using AES-GCM.
|
||||
/// Secures the given plaintext message with encryption and an
|
||||
/// authentication tag.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The message to encrypt and authenticate
|
||||
/// - key: An encryption key of 128, 192 or 256 bits
|
||||
/// - nonce: An Nonce for AES-GCM encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce()
|
||||
/// - Returns: A sealed box returning the authentication tag (seal) and the ciphertext
|
||||
/// - Throws: CipherError errors
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``AES.GCM.Nonce()``.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
public static func seal<Plaintext: DataProtocol>
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil) throws -> SealedBox {
|
||||
return try AESGCMImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
||||
}
|
||||
|
||||
/// Authenticates and decrypts data using AES-GCM.
|
||||
/// Decrypts the message and verifies the authenticity of both the
|
||||
/// encrypted message and additional data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sealedBox: The sealed box to authenticate and decrypt
|
||||
/// - key: An encryption key of 128, 192 or 256 bits
|
||||
/// - nonce: An Nonce for AES-GCM encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
|
||||
/// - authenticatedData: Data that was authenticated as part of the seal
|
||||
/// - Returns: The ciphertext if opening was successful
|
||||
/// - Throws: CipherError errors. If the authentication of the sealedbox failed, incorrectTag is thrown.
|
||||
/// - sealedBox: The sealed box to open.
|
||||
/// - key: The cryptographic key that was used to seal the message.
|
||||
/// - authenticatedData: Additional data that was authenticated.
|
||||
///
|
||||
/// - Returns: The original plaintext message that was sealed in the
|
||||
/// box, as long as the correct key is used and authentication succeeds.
|
||||
/// The call throws an error if decryption or authentication fail.
|
||||
public static func open<AuthenticatedData: DataProtocol>
|
||||
(_ sealedBox: SealedBox, using key: SymmetricKey, authenticating authenticatedData: AuthenticatedData) throws -> Data {
|
||||
return try AESGCMImpl.open(key: key, sealedBox: sealedBox, authenticatedData: authenticatedData)
|
||||
}
|
||||
|
||||
/// Authenticates and decrypts data using AES-GCM.
|
||||
/// Decrypts the message and verifies its authenticity.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sealedBox: The sealed box to authenticate and decrypt
|
||||
/// - key: An encryption key of 128, 192 or 256 bits
|
||||
/// - nonce: An Nonce for AES-GCM encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
|
||||
/// - Returns: The ciphertext if opening was successful
|
||||
/// - Throws: CipherError errors. If the authentication of the sealedbox failed, incorrectTag is thrown.
|
||||
/// - sealedBox: The sealed box to open.
|
||||
/// - key: The cryptographic key that was used to seal the message.
|
||||
///
|
||||
/// - Returns: The original plaintext message that was sealed in the
|
||||
/// box, as long as the correct key is used and authentication succeeds.
|
||||
/// The call throws an error if decryption or authentication fail.
|
||||
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
|
||||
return try AESGCMImpl.open(key: key, sealedBox: sealedBox, authenticatedData: Data?.none)
|
||||
}
|
||||
@@ -85,24 +92,49 @@ extension AES {
|
||||
}
|
||||
|
||||
extension AES.GCM {
|
||||
/// A secure container for your data that you can access using a cipher.
|
||||
///
|
||||
/// Use a sealed box as a container for data that you want to transmit
|
||||
/// securely. Seal data into a box with one of the cipher algorithms, like
|
||||
/// ``seal(_:using:nonce:)``.
|
||||
///
|
||||
/// The box holds an encrypted version of the original data, an
|
||||
/// authentication tag, and the nonce during encryption. The encryption
|
||||
/// makes the data unintelligible to anyone without the key, while the
|
||||
/// authentication tag makes it possible for the intended receiver to be
|
||||
/// sure the data remains intact.
|
||||
///
|
||||
/// The receiver uses another instance of the same cipher, like the
|
||||
/// ``open(_:using:)`` method, to open the box.
|
||||
public struct SealedBox: AEADSealedBox {
|
||||
private let combinedRepresentation: Data
|
||||
private let nonceByteCount: Int
|
||||
|
||||
/// The authentication tag
|
||||
/// An authentication tag.
|
||||
///
|
||||
/// The authentication tag has a length of 16 bytes.
|
||||
public var tag: Data {
|
||||
return combinedRepresentation.suffix(AES.GCM.tagByteCount)
|
||||
}
|
||||
/// The ciphertext
|
||||
/// The encrypted data.
|
||||
///
|
||||
/// The length of the ciphertext of a sealed box is the same as the
|
||||
/// length of the plaintext you encrypt.
|
||||
public var ciphertext: Data {
|
||||
return combinedRepresentation.dropFirst(nonceByteCount).dropLast(AES.GCM.tagByteCount)
|
||||
}
|
||||
/// The Nonce
|
||||
/// The nonce used to encrypt the data.
|
||||
public var nonce: AES.GCM.Nonce {
|
||||
return try! AES.GCM.Nonce(data: combinedRepresentation.prefix(nonceByteCount))
|
||||
}
|
||||
|
||||
/// The combined representation ( nonce || ciphertext || tag)
|
||||
/// A combined element composed of the nonce, encrypted data, and
|
||||
/// authentication tag.
|
||||
///
|
||||
/// The combined representation is only available when the
|
||||
/// ``AES/GCM/Nonce`` size is the default size of 12 bytes. The data
|
||||
/// layout of the combined representation is nonce, ciphertext, then
|
||||
/// tag.
|
||||
public var combined: Data? {
|
||||
if nonceByteCount == AES.GCM.defaultNonceByteCount {
|
||||
return self.combinedRepresentation
|
||||
@@ -122,6 +154,12 @@ extension AES.GCM {
|
||||
self.nonceByteCount = nonceByteCount
|
||||
}
|
||||
|
||||
/// Creates a sealed box from the combined bytes of an authentication
|
||||
/// tag, nonce, and encrypted data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - combined: The combined bytes of the nonce, encrypted data, and
|
||||
/// authentication tag.
|
||||
@inlinable
|
||||
public init<D: DataProtocol>(combined: D) throws {
|
||||
// AES minimum nonce (12 bytes) + AES tag (16 bytes)
|
||||
@@ -135,13 +173,25 @@ extension AES.GCM {
|
||||
self.init(combined: Data(combined))
|
||||
}
|
||||
|
||||
/// Creates a sealed box from the given tag, nonce, and ciphertext.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - nonce: The nonce.
|
||||
/// - ciphertext: The encrypted data.
|
||||
/// - tag: The authentication tag.
|
||||
public init<C: DataProtocol, T: DataProtocol>(nonce: AES.GCM.Nonce, ciphertext: C, tag: T) throws {
|
||||
guard tag.count == AES.GCM.tagByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
self.combinedRepresentation = nonce.bytes + ciphertext + tag
|
||||
self.nonceByteCount = nonce.bytes.count
|
||||
|
||||
let nonceByteCount = nonce.bytes.count
|
||||
var combinedRepresentation = Data()
|
||||
combinedRepresentation.reserveCapacity(nonceByteCount + ciphertext.count + tag.count)
|
||||
combinedRepresentation.append(contentsOf: nonce.bytes)
|
||||
combinedRepresentation.append(contentsOf: ciphertext)
|
||||
combinedRepresentation.append(contentsOf: tag)
|
||||
|
||||
self.init(combined: combinedRepresentation, nonceByteCount: nonceByteCount)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -23,61 +23,67 @@ typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl
|
||||
|
||||
import Foundation
|
||||
|
||||
/// ChaCha20-Poly1305 as described in RFC 7539 with 96-bit nonces.
|
||||
/// An implementation of the ChaCha20-Poly1305 cipher.
|
||||
public enum ChaChaPoly: Cipher {
|
||||
static let tagByteCount = 16
|
||||
static let keyBitsCount = 256
|
||||
static let nonceByteCount = 12
|
||||
|
||||
/// Encrypts and seals data using ChaCha20-Poly1305.
|
||||
/// Secures the given plaintext message with encryption and an
|
||||
/// authentication tag that covers both the encrypted data and additional
|
||||
/// data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The message to encrypt and authenticate
|
||||
/// - key: A 256-bit encryption key
|
||||
/// - nonce: A nonce for ChaChaPoly encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with ChaChaPoly.Nonce()
|
||||
/// - authenticatedData: Data to authenticate as part of the seal
|
||||
/// - Returns: A sealed box returning the authentication tag (seal) and the ciphertext
|
||||
/// - Throws: CipherError errors
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``ChaChaPoly.Nonce()``.
|
||||
/// - authenticatedData: Additional data to be authenticated.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
public static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil, authenticating authenticatedData: AuthenticatedData) throws -> SealedBox {
|
||||
return try ChaChaPolyImpl.encrypt(key: key, message: message, nonce: nonce, authenticatedData: authenticatedData)
|
||||
}
|
||||
|
||||
/// Encrypts and seals data using ChaCha20-Poly1305.
|
||||
/// Secures the given plaintext message with encryption and an
|
||||
/// authentication tag.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The message to encrypt and authenticate
|
||||
/// - key: A 256-bit encryption key
|
||||
/// - nonce: A nonce for ChaChaPoly encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with ChaChaPoly.Nonce()
|
||||
/// - Returns: A sealed box returning the authentication tag (seal) and the ciphertext
|
||||
/// - Throws: CipherError errors
|
||||
/// - message: The plaintext data to seal.
|
||||
/// - key: A cryptographic key used to seal the message.
|
||||
/// - nonce: The nonce the sealing process requires. If you don't provide a nonce, the method generates a random one by invoking ``ChaChaPoly.Nonce()``.
|
||||
///
|
||||
/// - Returns: The sealed message.
|
||||
public static func seal<Plaintext: DataProtocol>
|
||||
(_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil) throws -> SealedBox {
|
||||
return try ChaChaPolyImpl.encrypt(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
|
||||
}
|
||||
|
||||
/// Authenticates and decrypts data using ChaCha20-Poly1305.
|
||||
/// Decrypts the message and verifies the authenticity of both the encrypted
|
||||
/// message and additional data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sealedBox: The sealed box to authenticate and decrypt
|
||||
/// - key: A 256-bit encryption key
|
||||
/// - nonce: The nonce that was provided for encryption.
|
||||
/// - authenticatedData: Data that was authenticated as part of the seal
|
||||
/// - Returns: The ciphertext if opening was successful
|
||||
/// - Throws: CipherError errors. If the authentication of the sealedbox failed, incorrectTag is thrown.
|
||||
/// - sealedBox: The sealed box to open.
|
||||
/// - key: The cryptographic key that was used to seal the message.
|
||||
/// - authenticatedData: Additional data that was authenticated.
|
||||
///
|
||||
/// - Returns: The original plaintext message that was sealed in the box, as
|
||||
/// long as the correct key is used and authentication succeeds. The call
|
||||
/// throws an error if decryption or authentication fail.
|
||||
public static func open<AuthenticatedData: DataProtocol>
|
||||
(_ sealedBox: SealedBox, using key: SymmetricKey, authenticating authenticatedData: AuthenticatedData) throws -> Data {
|
||||
return try ChaChaPolyImpl.decrypt(key: key, ciphertext: sealedBox, authenticatedData: authenticatedData)
|
||||
}
|
||||
|
||||
/// Authenticates and decrypts data using ChaCha20-Poly1305.
|
||||
/// Decrypts the message and verifies its authenticity.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sealedBox: The sealed box to authenticate and decrypt
|
||||
/// - key: A 256-bit encryption key
|
||||
/// - nonce: The nonce that was provided for encryption.
|
||||
/// - Returns: The ciphertext if opening was successful
|
||||
/// - Throws: CipherError errors. If the authentication of the sealedbox failed, incorrectTag is thrown.
|
||||
/// - sealedBox: The sealed box to open.
|
||||
/// - key: The cryptographic key that was used to seal the message.
|
||||
///
|
||||
/// - Returns: The original plaintext message that was sealed in the box, as
|
||||
/// long as the correct key is used and authentication succeeds. The call
|
||||
/// throws an error if decryption or authentication fail.
|
||||
public static func open
|
||||
(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
|
||||
return try ChaChaPolyImpl.decrypt(key: key, ciphertext: sealedBox, authenticatedData: Data?.none)
|
||||
@@ -85,23 +91,47 @@ public enum ChaChaPoly: Cipher {
|
||||
}
|
||||
|
||||
extension ChaChaPoly {
|
||||
/// A secure container for your data that you access using a cipher.
|
||||
///
|
||||
/// Use a sealed box as a container for data that you want to transmit
|
||||
/// securely. Seal data into a box with one of the cipher algorithms, like
|
||||
/// ``seal(_:using:nonce:)``.
|
||||
///
|
||||
/// The box holds an encrypted version of the original data, an
|
||||
/// authentication tag, and the nonce during encryption. The encryption
|
||||
/// makes the data unintelligible to anyone without the key, while the
|
||||
/// authentication tag makes it possible for the intended receiver to be
|
||||
/// sure the data remains intact.
|
||||
///
|
||||
/// The receiver uses another instance of the same cipher, like the
|
||||
/// ``open(_:using:)`` method, to open the box.
|
||||
@frozen
|
||||
public struct SealedBox: AEADSealedBox {
|
||||
/// The combined representation ( nonce || ciphertext || tag)
|
||||
/// A combined element composed of the tag, the nonce, and the
|
||||
/// ciphertext.
|
||||
///
|
||||
/// The data layout of the combined representation is: nonce,
|
||||
/// ciphertext, then tag.
|
||||
public let combined: Data
|
||||
/// The authentication tag
|
||||
/// An authentication tag.
|
||||
///
|
||||
/// The authentication tag has a length of 16 bytes.
|
||||
public var tag: Data {
|
||||
return combined.suffix(ChaChaPoly.tagByteCount)
|
||||
}
|
||||
/// The ciphertext
|
||||
/// The encrypted data.
|
||||
public var ciphertext: Data {
|
||||
return combined.dropFirst(ChaChaPoly.nonceByteCount).dropLast(ChaChaPoly.tagByteCount)
|
||||
}
|
||||
/// The Nonce
|
||||
/// The nonce used to encrypt the data.
|
||||
public var nonce: ChaChaPoly.Nonce {
|
||||
return try! ChaChaPoly.Nonce(data: combined.prefix(ChaChaPoly.nonceByteCount))
|
||||
}
|
||||
|
||||
/// Creates a sealed box from the given data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - combined: The combined bytes of the tag and ciphertext.
|
||||
@inlinable
|
||||
public init<D: DataProtocol>(combined: D) throws {
|
||||
// ChachaPoly nonce (12 bytes) + ChachaPoly tag (16 bytes)
|
||||
@@ -115,6 +145,12 @@ extension ChaChaPoly {
|
||||
self.combined = Data(combined)
|
||||
}
|
||||
|
||||
/// Creates a sealed box from the given tag, nonce, and ciphertext.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - nonce: The nonce.
|
||||
/// - ciphertext: The encrypted data.
|
||||
/// - tag: An authentication tag.
|
||||
public init<C: DataProtocol, T: DataProtocol>(nonce: ChaChaPoly.Nonce, ciphertext: C, tag: T) throws {
|
||||
guard tag.count == ChaChaPoly.tagByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
|
||||
@@ -21,10 +21,17 @@ import Foundation
|
||||
|
||||
// MARK: - AES.GCM + Nonce
|
||||
extension AES.GCM {
|
||||
/// A value used once during a cryptographic operation and then discarded.
|
||||
///
|
||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
let bytes: Data
|
||||
|
||||
/// Generates a fresh random Nonce. Unless required by a specification to provide a specific Nonce, this is the recommended initializer.
|
||||
/// Creates a new random nonce.
|
||||
///
|
||||
/// The default nonce is a 12-byte random nonce.
|
||||
public init() {
|
||||
var data = Data(repeating: 0, count: AES.GCM.defaultNonceByteCount)
|
||||
data.withUnsafeMutableBytes {
|
||||
@@ -33,7 +40,15 @@ extension AES.GCM {
|
||||
}
|
||||
self.bytes = data
|
||||
}
|
||||
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A 12-byte data representation of the nonce. The initializer throws an
|
||||
/// error if the data has a length other than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws {
|
||||
if data.count < AES.GCM.defaultNonceByteCount {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
@@ -41,11 +56,23 @@ extension AES.GCM {
|
||||
|
||||
self.bytes = Data(data)
|
||||
}
|
||||
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||
/// contiguous storage.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure with an `UnsafeRawBufferPointer` parameter that points to the
|
||||
/// contiguous storage for the array. The system creates the storage if it doesn’t
|
||||
/// exist. If body has a return value, that value is also used as the return value
|
||||
/// for the ``withUnsafeBytes(_:)`` method. The argument is valid only for
|
||||
/// the duration of the closure’s execution.
|
||||
///
|
||||
/// - Returns: The return value, if any, of the body closure parameter.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
|
||||
/// Returns an iterator over the elements of the nonce.
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
return Array(buffPtr).makeIterator()
|
||||
@@ -56,10 +83,17 @@ extension AES.GCM {
|
||||
|
||||
// MARK: - ChaChaPoly + Nonce
|
||||
extension ChaChaPoly {
|
||||
/// A value used once during a cryptographic operation and then discarded.
|
||||
///
|
||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
let bytes: Data
|
||||
|
||||
/// Generates a fresh random Nonce. Unless required by a specification to provide a specific Nonce, this is the recommended initializer.
|
||||
/// Creates a new random nonce.
|
||||
///
|
||||
/// The default nonce is a 12-byte random nonce.
|
||||
public init() {
|
||||
var data = Data(repeating: 0, count: ChaChaPoly.nonceByteCount)
|
||||
data.withUnsafeMutableBytes {
|
||||
@@ -68,7 +102,15 @@ extension ChaChaPoly {
|
||||
}
|
||||
self.bytes = data
|
||||
}
|
||||
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A 12-byte data representation of the nonce. The initializer throws an
|
||||
/// error if the data has a length other than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws {
|
||||
if data.count != ChaChaPoly.nonceByteCount {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
@@ -76,11 +118,23 @@ extension ChaChaPoly {
|
||||
|
||||
self.bytes = Data(data)
|
||||
}
|
||||
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||
/// contiguous storage.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure with an `UnsafeRawBufferPointer` parameter that points to the
|
||||
/// contiguous storage for the array. The system creates the storage if it doesn’t
|
||||
/// exist. If body has a return value, that value is also used as the return value
|
||||
/// for the ``withUnsafeBytes(_:)`` method. The argument is valid only for
|
||||
/// the duration of the closure’s execution.
|
||||
///
|
||||
/// - Returns: The return value, if any, of the body closure parameter.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
|
||||
/// Returns an iterator over the elements of the nonce.
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
return Array(buffPtr).makeIterator()
|
||||
|
||||
@@ -30,10 +30,17 @@ nonceValidation = cipher["nonceValidation"]
|
||||
|
||||
// MARK: - ${name} + Nonce
|
||||
extension ${name} {
|
||||
/// A value used once during a cryptographic operation and then discarded.
|
||||
///
|
||||
/// Don’t reuse the same nonce for multiple calls to encryption APIs. It’s critical
|
||||
/// that nonces are unique per call to encryption APIs in order to protect the
|
||||
/// integrity of the encryption.
|
||||
public struct Nonce: ContiguousBytes, Sequence {
|
||||
let bytes: Data
|
||||
|
||||
/// Generates a fresh random Nonce. Unless required by a specification to provide a specific Nonce, this is the recommended initializer.
|
||||
/// Creates a new random nonce.
|
||||
///
|
||||
/// The default nonce is a 12-byte random nonce.
|
||||
public init() {
|
||||
var data = Data(repeating: 0, count: ${nonceSize})
|
||||
data.withUnsafeMutableBytes {
|
||||
@@ -42,7 +49,15 @@ extension ${name} {
|
||||
}
|
||||
self.bytes = data
|
||||
}
|
||||
|
||||
|
||||
/// Creates a nonce from the given data.
|
||||
///
|
||||
/// Unless your use case calls for a nonce with a specific value, use the
|
||||
/// ``init()`` method to instead create a random nonce.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A 12-byte data representation of the nonce. The initializer throws an
|
||||
/// error if the data has a length other than 12 bytes.
|
||||
public init<D: DataProtocol>(data: D) throws {
|
||||
if data.count ${nonceValidation} {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
@@ -50,11 +65,23 @@ extension ${name} {
|
||||
|
||||
self.bytes = Data(data)
|
||||
}
|
||||
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of the array’s
|
||||
/// contiguous storage.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure with an `UnsafeRawBufferPointer` parameter that points to the
|
||||
/// contiguous storage for the array. The system creates the storage if it doesn’t
|
||||
/// exist. If body has a return value, that value is also used as the return value
|
||||
/// for the ``withUnsafeBytes(_:)`` method. The argument is valid only for
|
||||
/// the duration of the closure’s execution.
|
||||
///
|
||||
/// - Returns: The return value, if any, of the body closure parameter.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try self.bytes.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
|
||||
/// Returns an iterator over the elements of the nonce.
|
||||
public func makeIterator() -> Array<UInt8>.Iterator {
|
||||
self.withUnsafeBytes({ (buffPtr) in
|
||||
return Array(buffPtr).makeIterator()
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from
|
||||
/// a INTEGER.
|
||||
/// A protocol that represents any internal object that can present itself as an INTEGER, or be parsed from
|
||||
/// an INTEGER.
|
||||
///
|
||||
/// This is not a very good solution for a fully-fledged ASN.1 library: we'd rather have a better numerics
|
||||
/// protocol that could both initialize from and serialize to either bytes or words. However, no such
|
||||
|
||||
@@ -42,8 +42,24 @@ add_library(Crypto
|
||||
"Digests/Digests.swift"
|
||||
"Digests/HashFunctions.swift"
|
||||
"Digests/HashFunctions_SHA2.swift"
|
||||
"HPKE/Ciphersuite/HPKE-AEAD.swift"
|
||||
"HPKE/Ciphersuite/HPKE-Ciphersuite.swift"
|
||||
"HPKE/Ciphersuite/HPKE-KDF.swift"
|
||||
"HPKE/Ciphersuite/HPKE-KexKeyDerivation.swift"
|
||||
"HPKE/Ciphersuite/HPKE-LabeledExtract.swift"
|
||||
"HPKE/Ciphersuite/HPKE-Utils.swift"
|
||||
"HPKE/Ciphersuite/KEM/Conformances/DHKEM.swift"
|
||||
"HPKE/Ciphersuite/KEM/Conformances/HPKE-KEM-Curve25519.swift"
|
||||
"HPKE/Ciphersuite/KEM/Conformances/HPKE-NIST-EC-KEMs.swift"
|
||||
"HPKE/Ciphersuite/KEM/HPKE-KEM.swift"
|
||||
"HPKE/HPKE-Errors.swift"
|
||||
"HPKE/HPKE.swift"
|
||||
"HPKE/Key Schedule/HPKE-Context.swift"
|
||||
"HPKE/Key Schedule/HPKE-KeySchedule.swift"
|
||||
"HPKE/Modes/HPKE-Modes.swift"
|
||||
"Insecure/Insecure.swift"
|
||||
"Insecure/Insecure_HashFunctions.swift"
|
||||
"KEM/KEM.swift"
|
||||
"Key Agreement/BoringSSL/ECDH_boring.swift"
|
||||
"Key Agreement/DH.swift"
|
||||
"Key Agreement/ECDH.swift"
|
||||
@@ -56,7 +72,7 @@ add_library(Crypto
|
||||
"Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift"
|
||||
"Keys/EC/BoringSSL/X25519Keys_boring.swift"
|
||||
"Keys/EC/Curve25519.swift"
|
||||
"Keys/EC/Ed25519.swift"
|
||||
"Keys/EC/Ed25519Keys.swift"
|
||||
"Keys/EC/NISTCurvesKeys.swift"
|
||||
"Keys/EC/X25519Keys.swift"
|
||||
"Keys/Symmetric/SymmetricKeys.swift"
|
||||
@@ -68,7 +84,7 @@ add_library(Crypto
|
||||
"Signatures/BoringSSL/ECDSA_boring.swift"
|
||||
"Signatures/BoringSSL/EdDSA_boring.swift"
|
||||
"Signatures/ECDSA.swift"
|
||||
"Signatures/EdDSA.swift"
|
||||
"Signatures/Ed25519.swift"
|
||||
"Signatures/Signature.swift"
|
||||
"Util/BoringSSL/ArbitraryPrecisionInteger_boring.swift"
|
||||
"Util/BoringSSL/CryptoKitErrors_boring.swift"
|
||||
|
||||
@@ -14,47 +14,51 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// Errors thrown in CryptoKit
|
||||
/// - incorrectKeySize: A key is being deserialized with an incorrect key size.
|
||||
/// - incorrectParameterSize: The number of bytes passed for a given argument is incorrect.
|
||||
/// - authenticationFailure: The authentication tag or signature is incorrect.
|
||||
/// - underlyingCoreCryptoError: An unexpected error at a lower-level occurred.
|
||||
/// - wrapFailure: Failed to wrap key
|
||||
/// - unwrapFailure: Failed to unwrap key
|
||||
/// General cryptography errors used by CryptoKit.
|
||||
public enum CryptoKitError: Error {
|
||||
/// The key size is incorrect.
|
||||
case incorrectKeySize
|
||||
/// The parameter size is incorrect.
|
||||
case incorrectParameterSize
|
||||
/// The authentication tag or signature is incorrect.
|
||||
case authenticationFailure
|
||||
/// The underlying corecrypto library is unable to complete the requested
|
||||
/// action.
|
||||
case underlyingCoreCryptoError(error: Int32)
|
||||
/// The framework can't wrap the specified key.
|
||||
case wrapFailure
|
||||
/// The framework can't unwrap the specified key.
|
||||
case unwrapFailure
|
||||
/// The parameter is invalid.
|
||||
case invalidParameter
|
||||
}
|
||||
|
||||
/// Errors encountered when parsing ASN.1 formatted keys.
|
||||
/// Errors from decoding ASN.1 content.
|
||||
public enum CryptoKitASN1Error: Error {
|
||||
/// The ASN.1 tag for this field is invalid or unsupported.
|
||||
case invalidFieldIdentifier
|
||||
|
||||
/// The ASN.1 tag for the parsed field does not match the required format.
|
||||
/// The ASN.1 tag for the parsed field doesn’t match the required format.
|
||||
case unexpectedFieldType
|
||||
|
||||
/// An invalid ASN.1 object identifier was encountered.
|
||||
/// An ASN.1 object identifier is invalid.
|
||||
case invalidObjectIdentifier
|
||||
|
||||
/// The format of the parsed ASN.1 object does not match the format required for the data type
|
||||
/// being decoded.
|
||||
/// The format of the parsed ASN.1 object doesn’t match the format required
|
||||
/// for the data type being decoded.
|
||||
case invalidASN1Object
|
||||
|
||||
/// An ASN.1 integer was decoded that does not use the minimum number of bytes for its encoding.
|
||||
/// An ASN.1 integer doesn’t use the minimum number of bytes for its
|
||||
/// encoding.
|
||||
case invalidASN1IntegerEncoding
|
||||
|
||||
/// An ASN.1 field was truncated and could not be decoded.
|
||||
/// An ASN.1 field is truncated.
|
||||
case truncatedASN1Field
|
||||
|
||||
/// The encoding used for the field length is not supported.
|
||||
/// The encoding used for the field length is unsupported.
|
||||
case unsupportedFieldLength
|
||||
|
||||
/// It was not possible to parse a string as a PEM document.
|
||||
/// The string doesn’t parse as a PEM document.
|
||||
case invalidPEMDocument
|
||||
}
|
||||
#endif
|
||||
@@ -16,8 +16,9 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A protocol defining requirements for digests
|
||||
/// A type that represents the output of a hash.
|
||||
public protocol Digest: Hashable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
|
||||
/// The number of bytes in the digest.
|
||||
static var byteCount: Int { get }
|
||||
}
|
||||
|
||||
@@ -50,10 +51,26 @@ extension Digest {
|
||||
|
||||
// We want to implement constant-time comparison for digests.
|
||||
extension Digest {
|
||||
/// Determines whether two digests are equal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lhs: The first digest to compare.
|
||||
/// - rhs: The second digest to compare.
|
||||
///
|
||||
/// - Returns: A Boolean value set to `true` if the two digests are equal.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
return safeCompare(lhs, rhs)
|
||||
}
|
||||
|
||||
/// Determines whether a digest is equivalent to a collection of contiguous
|
||||
/// bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lhs: A digest to compare.
|
||||
/// - rhs: A collection of contiguous bytes to compare.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` if the digest is equivalent to
|
||||
/// the collection of binary data.
|
||||
public static func == <D: DataProtocol>(lhs: Self, rhs: D) -> Bool {
|
||||
if rhs.regions.count != 1 {
|
||||
let rhsContiguous = Data(rhs)
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
// see section `gyb` in `README` for details.
|
||||
|
||||
// MARK: - SHA256Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 256-bit digest.
|
||||
public struct SHA256Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
@@ -34,10 +35,19 @@ public struct SHA256Digest: DigestPrivate {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return 32
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try Swift.withUnsafeBytes(of: bytes) {
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
||||
@@ -55,10 +65,23 @@ public struct SHA256Digest: DigestPrivate {
|
||||
return array.prefix(upTo: SHA256Digest.byteCount)
|
||||
}
|
||||
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA256") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``SHA256/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
@@ -66,6 +89,7 @@ public struct SHA256Digest: DigestPrivate {
|
||||
|
||||
|
||||
// MARK: - SHA384Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 384-bit digest.
|
||||
public struct SHA384Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
@@ -81,10 +105,19 @@ public struct SHA384Digest: DigestPrivate {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return 48
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try Swift.withUnsafeBytes(of: bytes) {
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
||||
@@ -104,10 +137,23 @@ public struct SHA384Digest: DigestPrivate {
|
||||
return array.prefix(upTo: SHA384Digest.byteCount)
|
||||
}
|
||||
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA384") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``SHA384/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
@@ -115,6 +161,7 @@ public struct SHA384Digest: DigestPrivate {
|
||||
|
||||
|
||||
// MARK: - SHA512Digest + DigestPrivate
|
||||
/// The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a 512-bit digest.
|
||||
public struct SHA512Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
|
||||
|
||||
@@ -130,10 +177,19 @@ public struct SHA512Digest: DigestPrivate {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return 64
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try Swift.withUnsafeBytes(of: bytes) {
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
||||
@@ -155,10 +211,23 @@ public struct SHA512Digest: DigestPrivate {
|
||||
return array.prefix(upTo: SHA512Digest.byteCount)
|
||||
}
|
||||
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA512") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``SHA512/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
@@ -166,6 +235,7 @@ public struct SHA512Digest: DigestPrivate {
|
||||
|
||||
extension Insecure {
|
||||
// MARK: - SHA1Digest + DigestPrivate
|
||||
/// The output of a SHA1 hash.
|
||||
public struct SHA1Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64, UInt64)
|
||||
|
||||
@@ -181,10 +251,19 @@ public struct SHA1Digest: DigestPrivate {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return 20
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try Swift.withUnsafeBytes(of: bytes) {
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
||||
@@ -201,10 +280,23 @@ public struct SHA1Digest: DigestPrivate {
|
||||
return array.prefix(upTo: SHA1Digest.byteCount)
|
||||
}
|
||||
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("SHA1") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``Insecure/SHA1/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
@@ -212,6 +304,7 @@ public struct SHA1Digest: DigestPrivate {
|
||||
}
|
||||
extension Insecure {
|
||||
// MARK: - MD5Digest + DigestPrivate
|
||||
/// The output of a MD5 hash.
|
||||
public struct MD5Digest: DigestPrivate {
|
||||
let bytes: (UInt64, UInt64)
|
||||
|
||||
@@ -227,10 +320,19 @@ public struct MD5Digest: DigestPrivate {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return 16
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try Swift.withUnsafeBytes(of: bytes) {
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
||||
@@ -246,10 +348,23 @@ public struct MD5Digest: DigestPrivate {
|
||||
return array.prefix(upTo: MD5Digest.byteCount)
|
||||
}
|
||||
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("MD5") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``Insecure/MD5/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
|
||||
@@ -24,19 +24,27 @@ digests_and_length = [{"name": "SHA256", "count": 32},{"name": "SHA384","count":
|
||||
%{
|
||||
name = HF["name"]
|
||||
byteCount = HF["count"]
|
||||
wordsCount = (byteCount*8)/64 + (0 if ((byteCount*8)%64) == 0 else 1)
|
||||
wordsCount = (byteCount*8)//64 + (0 if ((byteCount*8)%64) == 0 else 1)
|
||||
}%
|
||||
%{
|
||||
if "prefix" in HF.keys():
|
||||
protocol_prefix = ""
|
||||
protocol_prefix = protocol_prefix + "extension " + HF["prefix"] + "{"
|
||||
protocol_suffix = "}"
|
||||
parent = HF["prefix"].strip() + "/" + name
|
||||
else:
|
||||
protocol_prefix = ""
|
||||
protocol_suffix = ""
|
||||
parent = name
|
||||
|
||||
if name == "SHA1" or name == "MD5":
|
||||
abstract = "The output of a " + name + " hash."
|
||||
else:
|
||||
abstract = "The output of a Secure Hashing Algorithm 2 (SHA-2) hash with a " + name[-3:] + "-bit digest."
|
||||
}%
|
||||
${protocol_prefix}
|
||||
// MARK: - ${name}Digest + DigestPrivate
|
||||
/// ${abstract}
|
||||
public struct ${name}Digest: DigestPrivate {
|
||||
let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"})
|
||||
|
||||
@@ -52,10 +60,19 @@ public struct ${name}Digest: DigestPrivate {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// The number of bytes in the digest.
|
||||
public static var byteCount: Int {
|
||||
return ${byteCount}
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes of
|
||||
/// the digest.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the digest
|
||||
/// and returns the digest.
|
||||
///
|
||||
/// - Returns: The digest, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try Swift.withUnsafeBytes(of: bytes) {
|
||||
let boundsCheckedPtr = UnsafeRawBufferPointer(start: $0.baseAddress,
|
||||
@@ -73,10 +90,23 @@ public struct ${name}Digest: DigestPrivate {
|
||||
return array.prefix(upTo: ${name}Digest.byteCount)
|
||||
}
|
||||
|
||||
/// A human-readable description of the digest.
|
||||
public var description: String {
|
||||
return "\("${name}") digest: \(toArray().hexString)"
|
||||
}
|
||||
|
||||
/// Hashes the essential components of the digest by feeding them into the
|
||||
/// given hash function.
|
||||
///
|
||||
/// This method is part of the digest’s conformance to Swift standard library’s
|
||||
/// <doc://com.apple.documentation/documentation/swift/hashable> protocol, making
|
||||
/// it possible to compare digests. Don’t confuse that hashing with the
|
||||
/// cryptographically secure hashing that you use to create the digest in the
|
||||
/// first place by, for example, calling ``${parent}/hash(data:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hasher: The hash function to use when combining the components of
|
||||
/// the digest.
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
self.withUnsafeBytes { hasher.combine(bytes: $0) }
|
||||
}
|
||||
|
||||
@@ -22,9 +22,26 @@ typealias DigestImpl = OpenSSLDigestImpl
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Declares methods on cryptographic hash functions.
|
||||
/// A type that performs cryptographically secure hashing.
|
||||
///
|
||||
/// The ``HashFunction`` protocol describes an interface for computing a
|
||||
/// fixed-length digest from an arbitrarily large collection of bytes. Because
|
||||
/// the digest is small, you can quickly compare the digests to detect a
|
||||
/// difference in two corresponding data sets. Alternatively, transmit or store
|
||||
/// data with its digest to detect changes introduced after initially
|
||||
/// calculating the digest.
|
||||
///
|
||||
/// Use one of the protocol’s adopters, like ``SHA256``, ``SHA384``, or
|
||||
/// ``SHA512``, to output a digest whose value varies significantly over even
|
||||
/// small differences in the input data.
|
||||
///
|
||||
/// Checking a digest doesn’t guard against changes made by a malicious user who
|
||||
/// also changes the digest to match. To handle this, compute a message
|
||||
/// authentication code (MAC) like ``HMAC`` instead. MACs rely on hashing, but
|
||||
/// incorporate a secret cryptographic key into the digest computation. Only a
|
||||
/// user that has the key can generate a valid MAC.
|
||||
public protocol HashFunction {
|
||||
/// The block size of the hash function. It is different from the output size that can be retrieved from Digest.byteCount.
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
static var blockByteCount: Int { get }
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
/// The type of the digest returned by the hash function.
|
||||
@@ -33,25 +50,56 @@ public protocol HashFunction {
|
||||
associatedtype Digest: Crypto.Digest
|
||||
#endif
|
||||
|
||||
/// Initializes the hasher instance.
|
||||
/// Creates a hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash the data iteratively, such as when you don’t have a buffer large
|
||||
/// enough to hold all the data at once. Provide data blocks to the hash
|
||||
/// function using the ``update(data:)`` or ``update(bufferPointer:)``
|
||||
/// method. After providing all the data, call ``finalize()`` to get the
|
||||
/// digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead to compute the digest in a single call.
|
||||
init()
|
||||
|
||||
/// Updates the hasher with the buffer.
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// - Parameter bufferPointer: The buffer to update the hash
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``HashFunction/update(data:)``
|
||||
/// method instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
mutating func update(bufferPointer: UnsafeRawBufferPointer)
|
||||
|
||||
/// Returns the digest from the input in the hash function instance.
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// - Returns: The digest of the data
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash using one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
func finalize() -> Digest
|
||||
}
|
||||
|
||||
extension HashFunction {
|
||||
/// Computes a digest of the buffer.
|
||||
///
|
||||
/// - Parameter bufferPointer: The buffer to be hashed
|
||||
/// - Returns: The computed digest
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: The buffer to be hashed.
|
||||
/// - Returns: The computed digest.
|
||||
@inlinable
|
||||
static func hash(bufferPointer: UnsafeRawBufferPointer) -> Digest {
|
||||
var hasher = Self()
|
||||
@@ -59,10 +107,23 @@ extension HashFunction {
|
||||
return hasher.finalize()
|
||||
}
|
||||
|
||||
/// Computes a digest of the data.
|
||||
/// Computes the SHA1 digest of the bytes in the given data instance and
|
||||
/// returns the computed digest.
|
||||
///
|
||||
/// - Parameter data: The data to be hashed
|
||||
/// - Returns: The computed digest
|
||||
/// Use this method if all your data fits into a single data instance. If
|
||||
/// the data you want to hash is too large, initialize a hash function and
|
||||
/// use the ``update(data:)`` and ``finalize()`` methods to compute the
|
||||
/// digest in blocks.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: The data whose digest the hash function should compute. This can
|
||||
/// be any type that conforms to
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// like <doc://com.apple.documentation/documentation/foundation/data> or an
|
||||
/// array of <doc://com.apple.documentation/documentation/swift/uint8>
|
||||
/// instances.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
@inlinable
|
||||
public static func hash<D: DataProtocol>(data: D) -> Self.Digest {
|
||||
var hasher = Self()
|
||||
@@ -70,9 +131,20 @@ extension HashFunction {
|
||||
return hasher.finalize()
|
||||
}
|
||||
|
||||
/// Updates the hasher with the data.
|
||||
/// Incrementally updates the hash function with the given data.
|
||||
///
|
||||
/// - Parameter data: The data to update the hash
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: The next block of data for the ongoing digest calculation. You
|
||||
/// can provide this as any type that conforms to
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// like <doc://com.apple.documentation/documentation/foundation/data> or an
|
||||
/// array of <doc://com.apple.documentation/documentation/swift/uint8>
|
||||
/// instances.
|
||||
@inlinable
|
||||
public mutating func update<D: DataProtocol>(data: D) {
|
||||
data.regions.forEach { (regionData) in
|
||||
|
||||
@@ -14,23 +14,46 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// The SHA-256 Hash Function
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 256-bit digest.
|
||||
///
|
||||
/// The ``SHA256`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-2 hashing with a 256-bit digest (``SHA256Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to fit
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
public struct SHA256: HashFunctionImplementationDetails {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set SHA256.blockByteCount") }
|
||||
}
|
||||
/// The number of bytes in a SHA256 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 32 }
|
||||
|
||||
set { fatalError("Cannot set SHA256.byteCount") }
|
||||
}
|
||||
/// The digest type for a SHA256 hash function.
|
||||
public typealias Digest = SHA256Digest
|
||||
|
||||
var impl: DigestImpl<SHA256>
|
||||
|
||||
/// Initializes the hash function instance.
|
||||
/// Creates a SHA256 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash data iteratively, such as when you don’t have a buffer large enough
|
||||
/// to hold all the data at once. Provide data blocks to the hash function
|
||||
/// using the ``update(data:)`` or ``update(bufferPointer:)`` method. After
|
||||
/// providing all the data, call ``finalize()`` to get the digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead, to compute the digest in a single call.
|
||||
public init() {
|
||||
impl = DigestImpl()
|
||||
}
|
||||
@@ -38,34 +61,82 @@ public struct SHA256: HashFunctionImplementationDetails {
|
||||
// Once https://github.com/apple/swift-evolution/pull/910 is landed,
|
||||
// we will be able to implement `init` here and remove the duplicate code.
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Returns the digest from the data input in the hash function instance.
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// - Returns: The digest of the inputted data
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
/// The SHA-384 Hash Function
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 384-bit digest.
|
||||
///
|
||||
/// The ``SHA384`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-2 hashing with a 384-bit digest (``SHA384Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to fit
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
public struct SHA384: HashFunctionImplementationDetails {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 128 }
|
||||
|
||||
set { fatalError("Cannot set SHA384.blockByteCount") }
|
||||
}
|
||||
/// The number of bytes in a SHA384 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 48 }
|
||||
|
||||
set { fatalError("Cannot set SHA384.byteCount") }
|
||||
}
|
||||
|
||||
/// The digest type for a SHA384 hash function.
|
||||
public typealias Digest = SHA384Digest
|
||||
var impl: DigestImpl<SHA384>
|
||||
|
||||
/// Creates a SHA384 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash the data iteratively, such as when you don’t have a buffer large
|
||||
/// enough to hold all the data at once. Provide data blocks to the hash
|
||||
/// function using the ``update(data:)`` or ``update(bufferPointer:)``
|
||||
/// method. After providing all the data, call ``finalize()`` to get the
|
||||
/// digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead, to compute the digest in a single call.
|
||||
public init() {
|
||||
impl = DigestImpl()
|
||||
}
|
||||
@@ -73,40 +144,116 @@ public struct SHA384: HashFunctionImplementationDetails {
|
||||
// Once https://github.com/apple/swift-evolution/pull/910 is landed,
|
||||
// we will be able to implement `init` here and remove the duplicate code.
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
/// The SHA-512 Hash Function
|
||||
/// An implementation of Secure Hashing Algorithm 2 (SHA-2) hashing with a
|
||||
/// 512-bit digest.
|
||||
///
|
||||
/// The ``SHA512`` hash implements the ``HashFunction`` protocol for the
|
||||
/// specific case of SHA-2 hashing with a 512-bit digest (``SHA512Digest``).
|
||||
/// Larger digests take more space but are more secure.
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to fit
|
||||
/// in memory, you can compute the digest iteratively by creating a new hash
|
||||
/// instance, calling the ``update(data:)`` method repeatedly with blocks of
|
||||
/// data, and then calling the ``finalize()`` method to get the result.
|
||||
public struct SHA512: HashFunctionImplementationDetails {
|
||||
/// The number of bytes that represents the hash function’s internal state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 128 }
|
||||
|
||||
set { fatalError("Cannot set SHA512.blockByteCount") }
|
||||
}
|
||||
/// The number of bytes in a SHA512 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set SHA512.byteCount") }
|
||||
}
|
||||
/// The digest type for a SHA512 hash function.
|
||||
public typealias Digest = SHA512Digest
|
||||
|
||||
var impl: DigestImpl<SHA512>
|
||||
|
||||
/// Initializes the hash function instance.
|
||||
/// Creates a SHA512 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash the data iteratively, such as when you don’t have a buffer large
|
||||
/// enough to hold all the data at once. Provide data blocks to the hash
|
||||
/// function using the ``update(data:)`` or ``update(bufferPointer:)``
|
||||
/// method. After providing all the data, call ``finalize()`` to get the
|
||||
/// digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the ``hash(data:)``
|
||||
/// method instead, to compute the digest in a single call.
|
||||
public init() {
|
||||
impl = DigestImpl()
|
||||
}
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash function
|
||||
/// in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the update
|
||||
/// method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or some
|
||||
/// other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// Call this method after you provide the hash function with all the data
|
||||
/// to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash function,
|
||||
/// discard it. To compute a new digest, create a new hash function with a
|
||||
/// call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
|
||||
extension HPKE {
|
||||
/// The authenticated encryption with associated data (AEAD) algorithms to use in HPKE.
|
||||
public enum AEAD: CaseIterable, Hashable {
|
||||
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 128 bits.
|
||||
case AES_GCM_128
|
||||
/// An Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||
case AES_GCM_256
|
||||
/// A ChaCha20 stream cipher with the Poly1305 message authentication code.
|
||||
case chaChaPoly
|
||||
/// An export-only mode.
|
||||
///
|
||||
/// In export-only mode, HPKE negotiates key derivation, but you can't use it to encrypt or decrypt data.
|
||||
case exportOnly
|
||||
|
||||
internal var value: UInt16 {
|
||||
switch self {
|
||||
case .AES_GCM_128: return 0x0001
|
||||
case .AES_GCM_256: return 0x0002
|
||||
case .chaChaPoly: return 0x0003
|
||||
case .exportOnly: return 0xFFFF
|
||||
}
|
||||
}
|
||||
|
||||
var isExportOnly: Bool {
|
||||
return self == .exportOnly
|
||||
}
|
||||
|
||||
internal var keyByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128:
|
||||
return 16
|
||||
case .AES_GCM_256:
|
||||
return 32
|
||||
case .chaChaPoly:
|
||||
return 32
|
||||
case .exportOnly:
|
||||
fatalError("ExportOnly should not return a key size.")
|
||||
}
|
||||
}
|
||||
|
||||
internal var nonceByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||
return 12
|
||||
case .exportOnly:
|
||||
fatalError("ExportOnly should not return a nonce size.")
|
||||
}
|
||||
}
|
||||
|
||||
internal var tagByteCount: Int {
|
||||
switch self {
|
||||
case .AES_GCM_128, .AES_GCM_256, .chaChaPoly:
|
||||
return 16
|
||||
case .exportOnly:
|
||||
fatalError("ExportOnly should not return a tag size.")
|
||||
}
|
||||
}
|
||||
|
||||
internal var identifier: Data {
|
||||
return I2OSP(value: Int(self.value), outputByteCount: 2)
|
||||
}
|
||||
|
||||
internal func seal<D: DataProtocol, AD: DataProtocol>(_ message: D, authenticating aad: AD, nonce: Data, using key: SymmetricKey) throws -> Data {
|
||||
switch self {
|
||||
case .chaChaPoly:
|
||||
return try ChaChaPoly.seal(message, using: key, nonce: ChaChaPoly.Nonce(data: nonce), authenticating: aad).combined.suffix(from: nonce.count)
|
||||
default:
|
||||
return try AES.GCM.seal(message, using: key, nonce: AES.GCM.Nonce(data: nonce), authenticating: aad).combined!.suffix(from: nonce.count)
|
||||
}
|
||||
}
|
||||
|
||||
internal func open<C: DataProtocol, AD: DataProtocol>(_ ct: C, nonce: Data, authenticating aad: AD, using key: SymmetricKey) throws -> Data {
|
||||
guard ct.count >= self.tagByteCount else {
|
||||
throw HPKE.Errors.expectedPSK
|
||||
}
|
||||
|
||||
switch self {
|
||||
case .AES_GCM_128, .AES_GCM_256: do {
|
||||
let nonce = try AES.GCM.Nonce(data: nonce)
|
||||
let sealedBox = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ct.dropLast(16), tag: ct.suffix(16))
|
||||
return try AES.GCM.open(sealedBox, using: key, authenticating: aad)
|
||||
}
|
||||
case .chaChaPoly: do {
|
||||
let nonce = try ChaChaPoly.Nonce(data: nonce)
|
||||
let sealedBox = try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: ct.dropLast(16), tag: ct.suffix(16))
|
||||
return try ChaChaPoly.open(sealedBox, using: key, authenticating: aad)
|
||||
}
|
||||
case .exportOnly:
|
||||
throw HPKE.Errors.exportOnlyMode
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,72 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
|
||||
extension HPKE {
|
||||
/// Cipher suites to use in hybrid public key encryption.
|
||||
///
|
||||
/// HPKE cipher suites identify the authenticated encryption with additional data (AEAD) algorithm for encrypting
|
||||
/// and decrypting messages, the key derivation function (KDF) for deriving the shared key, and the key encapsulation
|
||||
/// mechanism (KEM) for sharing the symmetric key. The sender and recipient of encrypted messages need to use the
|
||||
/// same cipher suite.
|
||||
public struct Ciphersuite {
|
||||
/// A cipher suite for HPKE that uses NIST P-256 elliptic curve key agreement, SHA-2 key derivation
|
||||
/// with a 256-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||
public static let P256_SHA256_AES_GCM_256 = Ciphersuite(kem: .P256_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .AES_GCM_256)
|
||||
/// A cipher suite that you use for HPKE using NIST P-384 elliptic curve key agreement, SHA-2 key derivation
|
||||
/// with a 384-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||
public static let P384_SHA384_AES_GCM_256 = Ciphersuite(kem: .P384_HKDF_SHA384, kdf: .HKDF_SHA384, aead: .AES_GCM_256)
|
||||
/// A cipher suite for HPKE that uses NIST P-521 elliptic curve key agreement, SHA-2 key derivation
|
||||
/// with a 512-bit digest, and the Advanced Encryption Standard cipher in Galois/Counter Mode with a key length of 256 bits.
|
||||
public static let P521_SHA512_AES_GCM_256 = Ciphersuite(kem: .P521_HKDF_SHA512, kdf: .HKDF_SHA512, aead: .AES_GCM_256)
|
||||
/// A cipher suite for HPKE that uses X25519 elliptic curve key agreement, SHA-2 key derivation
|
||||
/// with a 256-bit digest, and the ChaCha20 stream cipher with the Poly1305 message authentication code.
|
||||
public static let Curve25519_SHA256_ChachaPoly = Ciphersuite(kem: .Curve25519_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .chaChaPoly)
|
||||
|
||||
fileprivate static let ciphersuiteLabel = Data("HPKE".utf8)
|
||||
|
||||
/// The key encapsulation mechanism (KEM) for encapsulating the symmetric key.
|
||||
public let kem: HPKE.KEM
|
||||
/// The key derivation function (KDF) for deriving the symmetric key.
|
||||
public let kdf: HPKE.KDF
|
||||
/// The authenticated encryption with additional data (AEAD) algorithm for encrypting and decrypting messages.
|
||||
public let aead: HPKE.AEAD
|
||||
|
||||
/// Creates an HPKE cipher suite.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kem: The key encapsulation mechanism for encapsulating the symmetric key.
|
||||
/// - kdf: The key derivation function for deriving the symmetric key.
|
||||
/// - aead: The authenticated encryption with additional data (AEAD) algorithm for encrypting and decrypting messages.
|
||||
public init(kem: HPKE.KEM, kdf: HPKE.KDF, aead: HPKE.AEAD) {
|
||||
self.kem = kem
|
||||
self.kdf = kdf
|
||||
self.aead = aead
|
||||
}
|
||||
|
||||
internal var identifier: Data {
|
||||
var identifier = Ciphersuite.ciphersuiteLabel
|
||||
identifier.append(kem.identifier)
|
||||
identifier.append(kdf.identifier)
|
||||
identifier.append(aead.identifier)
|
||||
return identifier
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,99 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension HPKE {
|
||||
/// The key derivation functions to use in HPKE.
|
||||
public enum KDF: CaseIterable, Hashable {
|
||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 256-bit digest.
|
||||
case HKDF_SHA256
|
||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 384-bit digest.
|
||||
case HKDF_SHA384
|
||||
/// An HMAC-based key derivation function that uses SHA-2 hashing with a 512-bit digest.
|
||||
case HKDF_SHA512
|
||||
|
||||
/// Assigned value
|
||||
internal var value: UInt16 {
|
||||
switch self {
|
||||
case .HKDF_SHA256: return 0x0001
|
||||
case .HKDF_SHA384: return 0x0002
|
||||
case .HKDF_SHA512: return 0x0003
|
||||
}
|
||||
}
|
||||
|
||||
internal var identifier: Data {
|
||||
return I2OSP(value: Int(self.value), outputByteCount: 2)
|
||||
}
|
||||
|
||||
/// Hash Function Output Size
|
||||
internal var Nh: Int {
|
||||
switch self {
|
||||
case .HKDF_SHA256:
|
||||
return SHA256.Digest.byteCount
|
||||
case .HKDF_SHA384:
|
||||
return SHA384.Digest.byteCount
|
||||
case .HKDF_SHA512:
|
||||
return SHA512.Digest.byteCount
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates cryptographically strong key material from initial key material that you specify.
|
||||
///
|
||||
/// Generate a derived symmetric key from the cryptographically strong key material this function
|
||||
/// creates by calling ``expand(prk:info:outputByteCount:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - salt: The salt to use for key derivation.
|
||||
/// - ikm: The initial key material the derivation function uses to derive a key.
|
||||
///
|
||||
/// - Returns: A pseudorandom, cryptographically strong key in the form of a hashed authentication code.
|
||||
func extract<S: DataProtocol>(salt: S, ikm: SymmetricKey) -> SymmetricKey {
|
||||
switch self {
|
||||
case .HKDF_SHA256:
|
||||
return SymmetricKey(data: HKDF<SHA256>.extract(inputKeyMaterial: ikm, salt: salt))
|
||||
case .HKDF_SHA384:
|
||||
return SymmetricKey(data: HKDF<SHA384>.extract(inputKeyMaterial: ikm, salt: salt))
|
||||
case .HKDF_SHA512:
|
||||
return SymmetricKey(data: HKDF<SHA512>.extract(inputKeyMaterial: ikm, salt: salt))
|
||||
}
|
||||
}
|
||||
|
||||
/// Expands cryptographically strong key material into a derived symmetric key.
|
||||
///
|
||||
/// Generate cryptographically strong key material to use with this function by calling
|
||||
/// ``extract(salt:ikm:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - prk: A pseudorandom, cryptographically strong key generated from the ``extract(salt:ikm:)`` function.
|
||||
/// - info: The shared information to use for key derivation.
|
||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
func expand(prk: SymmetricKey, info: Data, outputByteCount: Int) -> SymmetricKey {
|
||||
switch self {
|
||||
case .HKDF_SHA256:
|
||||
return SymmetricKey(data: HKDF<SHA256>.expand(pseudoRandomKey: prk, info: info, outputByteCount: outputByteCount))
|
||||
case .HKDF_SHA384:
|
||||
return SymmetricKey(data: HKDF<SHA384>.expand(pseudoRandomKey: prk, info: info, outputByteCount: outputByteCount))
|
||||
case .HKDF_SHA512:
|
||||
return SymmetricKey(data: HKDF<SHA512>.expand(pseudoRandomKey: prk, info: info, outputByteCount: outputByteCount))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,46 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
private let suiteIDLabel = Data("KEM".utf8)
|
||||
|
||||
extension HPKE {
|
||||
struct KexUtils {
|
||||
static func ExtractAndExpand(dh: ContiguousBytes, enc: Data,
|
||||
pkRm: Data, pkSm: Data? = nil, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
var suiteID = suiteIDLabel
|
||||
suiteID.append(kem.identifier)
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return CryptoKit.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
|
||||
suiteID: suiteID, kem: kem, kdf: kdf)
|
||||
#else
|
||||
return Crypto.ExtractAndExpand(zz: dh, kemContext: kemContext(enc: enc, pkRm: pkRm, pkSm: pkSm),
|
||||
suiteID: suiteID, kem: kem, kdf: kdf)
|
||||
#endif
|
||||
}
|
||||
|
||||
static func kemContext(enc: Data, pkRm: Data, pkSm: Data? = nil) -> Data {
|
||||
var context = Data()
|
||||
context.append(enc)
|
||||
context.append(pkRm)
|
||||
if let pkSm = pkSm { context.append(pkSm) }
|
||||
return context
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,61 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
private let protocolLabel = Data("HPKE-v1".utf8)
|
||||
private let eaePRKLabel = Data("eae_prk".utf8)
|
||||
private let sharedSecretLabel = Data("shared_secret".utf8)
|
||||
|
||||
extension Data {
|
||||
internal init(unsafeFromContiguousBytes cb: ContiguousBytes) {
|
||||
self = cb.withUnsafeBytes { return Data($0) }
|
||||
}
|
||||
}
|
||||
|
||||
internal func ExtractAndExpand(zz: ContiguousBytes, kemContext: Data, suiteID: Data, kem: HPKE.KEM, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
let eaePrk = LabeledExtract(salt: Data(), label: eaePRKLabel, ikm: zz, suiteID: suiteID, kdf: kdf)
|
||||
|
||||
return LabeledExpand(prk: eaePrk, label: sharedSecretLabel,
|
||||
info: kemContext, outputByteCount: kem.nSecret, suiteID: suiteID, kdf: kdf)
|
||||
}
|
||||
|
||||
internal func LabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
var labeled_ikm = protocolLabel
|
||||
labeled_ikm.append(suiteID)
|
||||
labeled_ikm.append(label)
|
||||
ikm.map { labeled_ikm.append(Data(unsafeFromContiguousBytes: $0)) }
|
||||
return kdf.extract(salt: salt ?? Data(), ikm: SymmetricKey(data: labeled_ikm))
|
||||
}
|
||||
|
||||
internal func LabeledExpand<Info: DataProtocol>(prk: SymmetricKey, label: Data, info: Info, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> SymmetricKey {
|
||||
var labeled_info = I2OSP(value: Int(outputByteCount), outputByteCount: 2)
|
||||
labeled_info.append(protocolLabel)
|
||||
labeled_info.append(suiteID)
|
||||
labeled_info.append(label)
|
||||
labeled_info.append(contentsOf: info)
|
||||
return kdf.expand(prk: prk, info: labeled_info, outputByteCount: Int(outputByteCount))
|
||||
}
|
||||
|
||||
internal func NonSecretOutputLabeledExtract(salt: Data?, label: Data, ikm: ContiguousBytes?, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
||||
return Data(unsafeFromContiguousBytes: LabeledExtract(salt: salt, label: label, ikm: ikm, suiteID: suiteID, kdf: kdf))
|
||||
}
|
||||
|
||||
internal func NonSecretOutputLabeledExpand(prk: SymmetricKey, label: Data, info: Data, outputByteCount: UInt16, suiteID: Data, kdf: HPKE.KDF) -> Data {
|
||||
return Data(unsafeFromContiguousBytes: LabeledExpand(prk: prk, label: label, info: info, outputByteCount: outputByteCount, suiteID: suiteID, kdf: kdf))
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,35 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
internal func I2OSP(value: Int, outputByteCount: Int) -> Data {
|
||||
precondition(outputByteCount > 0, "Cannot I2OSP with no output length.")
|
||||
precondition(value >= 0, "I2OSP requires a non-null value.")
|
||||
|
||||
let requiredBytes = Int(ceil(log2(Double(max(value, 1) + 1)) / 8))
|
||||
precondition(outputByteCount >= requiredBytes)
|
||||
|
||||
var data = Data(repeating: 0, count: outputByteCount)
|
||||
|
||||
for i in (outputByteCount - requiredBytes)...(outputByteCount - 1) {
|
||||
data[i] = UInt8(truncatingIfNeeded: (value >> (8 * (outputByteCount - 1 - i))))
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,147 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A type that ``HPKE`` uses to encode the public key.
|
||||
public protocol HPKEPublicKeySerialization {
|
||||
/// Creates a public key from an encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - serialization: The serialized key data.
|
||||
/// - kem: The key encapsulation mechanism that the sender used to encapsulate the key.
|
||||
init<D: ContiguousBytes>(_ serialization: D, kem: HPKE.KEM) throws
|
||||
/// Creates an encoded representation of the public key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kem: The key encapsulation mechanism for encapsulating the key.
|
||||
///
|
||||
/// - Returns: The encoded key data.
|
||||
func hpkeRepresentation(kem: HPKE.KEM) throws -> Data
|
||||
}
|
||||
|
||||
/// A type that represents the public key in a Diffie-Hellman key exchange.
|
||||
public protocol HPKEDiffieHellmanPublicKey: HPKEPublicKeySerialization where EphemeralPrivateKey.PublicKey == Self {
|
||||
/// The type of the ephemeral private key.
|
||||
associatedtype EphemeralPrivateKey: HPKEDiffieHellmanPrivateKeyGeneration
|
||||
}
|
||||
|
||||
/// A type that represents the private key in a Diffie-Hellman key exchange.
|
||||
|
||||
public protocol HPKEDiffieHellmanPrivateKey: DiffieHellmanKeyAgreement where PublicKey: HPKEDiffieHellmanPublicKey {}
|
||||
|
||||
/// A type that represents the generation of private keys in a Diffie-Hellman key exchange.
|
||||
public protocol HPKEDiffieHellmanPrivateKeyGeneration: HPKEDiffieHellmanPrivateKey {
|
||||
/// Creates a private key generator.
|
||||
init()
|
||||
}
|
||||
|
||||
extension HPKE {
|
||||
/// A container for Diffie-Hellman key encapsulation mechanisms (KEMs).
|
||||
public enum DHKEM {
|
||||
struct PublicKey<DHPK: HPKEDiffieHellmanPublicKey>: KEMPublicKey where DHPK == DHPK.EphemeralPrivateKey.PublicKey {
|
||||
let kem: HPKE.KEM
|
||||
let key: DHPK
|
||||
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
typealias EncapsulationResult = CryptoKit.KEM.EncapsulationResult
|
||||
#else
|
||||
typealias EncapsulationResult = Crypto.KEM.EncapsulationResult
|
||||
#endif
|
||||
|
||||
init(_ publicKey: DHPK, kem: HPKE.KEM) throws {
|
||||
// TODO: Validate Ciphersuite Mismatches
|
||||
_ = try publicKey.hpkeRepresentation(kem: kem)
|
||||
self.key = publicKey
|
||||
self.kem = kem
|
||||
}
|
||||
|
||||
func encapsulate() throws -> EncapsulationResult {
|
||||
let ephemeralKeys = DHPK.EphemeralPrivateKey()
|
||||
let dh =
|
||||
try ephemeralKeys.sharedSecretFromKeyAgreement(with: key)
|
||||
|
||||
let enc = try! ephemeralKeys.publicKey.hpkeRepresentation(kem: kem)
|
||||
let selfRepresentation = try self.key.hpkeRepresentation(kem: kem)
|
||||
return EncapsulationResult(sharedSecret: HPKE.KexUtils.ExtractAndExpand(dh: dh,
|
||||
enc: enc,
|
||||
pkRm: selfRepresentation,
|
||||
kem: kem,
|
||||
kdf: kem.kdf), encapsulated: enc)
|
||||
}
|
||||
}
|
||||
|
||||
struct PrivateKey<DHSK: HPKEDiffieHellmanPrivateKey>: KEMPrivateKey {
|
||||
let kem: HPKE.KEM
|
||||
let key: DHSK
|
||||
|
||||
init(_ privateKey: DHSK, kem: HPKE.KEM) throws {
|
||||
// TODO: Validate Ciphersuite Mismatches
|
||||
_ = try privateKey.publicKey.hpkeRepresentation(kem: kem)
|
||||
self.key = privateKey
|
||||
self.kem = kem
|
||||
}
|
||||
|
||||
static func generate() throws -> Self {
|
||||
fatalError("generate() is not available on HPKE.DHKEM.PrivateKey, use generate(kem:) instead.")
|
||||
}
|
||||
|
||||
public func decapsulate(_ encapsulated: Data) throws -> SymmetricKey {
|
||||
let pkE = try DHSK.PublicKey(encapsulated, kem: kem)
|
||||
let dh = try key.sharedSecretFromKeyAgreement(with: pkE)
|
||||
|
||||
return HPKE.KexUtils.ExtractAndExpand(dh: dh,
|
||||
enc: encapsulated,
|
||||
pkRm: try key.publicKey.hpkeRepresentation(kem: kem),
|
||||
kem: kem, kdf: kem.kdf)
|
||||
}
|
||||
|
||||
func decapsulate(_ encapsulated: Data, authenticating pkS: DHSK.PublicKey) throws -> SymmetricKey {
|
||||
let pkE = try DHSK.PublicKey(encapsulated, kem: kem)
|
||||
|
||||
var dh = try Data(unsafeFromContiguousBytes: key.sharedSecretFromKeyAgreement(with: pkE))
|
||||
try dh.append(Data(unsafeFromContiguousBytes: key.sharedSecretFromKeyAgreement(with: pkS)))
|
||||
|
||||
return HPKE.KexUtils.ExtractAndExpand(dh: dh,
|
||||
enc: encapsulated,
|
||||
pkRm: try key.publicKey.hpkeRepresentation(kem: kem),
|
||||
pkSm: try pkS.hpkeRepresentation(kem: kem),
|
||||
kem: kem,
|
||||
kdf: kem.kdf)
|
||||
}
|
||||
|
||||
func authenticateAndEncapsulateTo(_ publicKey: Self.PublicKey) throws -> (sharedSecret: SymmetricKey, encapsulated: Data) {
|
||||
let ephemeralKeys = DHSK.PublicKey.EphemeralPrivateKey()
|
||||
|
||||
var dh = try Data(unsafeFromContiguousBytes: ephemeralKeys.sharedSecretFromKeyAgreement(with: publicKey.key))
|
||||
try dh.append(Data(unsafeFromContiguousBytes: key.sharedSecretFromKeyAgreement(with: publicKey.key)))
|
||||
let enc = try ephemeralKeys.publicKey.hpkeRepresentation(kem: kem)
|
||||
|
||||
return (HPKE.KexUtils.ExtractAndExpand(dh: dh,
|
||||
enc: enc,
|
||||
pkRm: try publicKey.key.hpkeRepresentation(kem: kem),
|
||||
pkSm: try key.publicKey.hpkeRepresentation(kem: kem),
|
||||
kem: kem, kdf: kem.kdf), enc)
|
||||
}
|
||||
|
||||
var publicKey: HPKE.DHKEM.PublicKey<DHSK.PublicKey> {
|
||||
return try! HPKE.DHKEM.PublicKey(key.publicKey, kem: kem)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,64 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension Curve25519.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {}
|
||||
|
||||
|
||||
extension Curve25519.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
||||
|
||||
static func validateCiphersuite(_ kem: HPKE.KEM) throws {
|
||||
switch kem {
|
||||
case .Curve25519_HKDF_SHA256: do {}
|
||||
default: do {
|
||||
throw HPKE.Errors.inconsistentCiphersuiteAndKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a Curve25519 elliptic curve public key for use with Diffie-Hellman key exchange.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - serialization: The serialized bytes of the public key.
|
||||
/// - kem: The key encapsulation mechanism to use with the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public init<D>(_ serialization: D, kem: HPKE.KEM) throws where D: ContiguousBytes {
|
||||
try Self.validateCiphersuite(kem)
|
||||
try self.init(rawRepresentation: serialization)
|
||||
}
|
||||
|
||||
/// Creates a serialized representation of the public key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kem: The Key Encapsulation Mechanism to use with the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
///
|
||||
/// - Returns: The serialized representation of the public key.
|
||||
public func hpkeRepresentation(kem: HPKE.KEM) throws -> Data {
|
||||
try Self.validateCiphersuite(kem)
|
||||
return self.rawRepresentation
|
||||
}
|
||||
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias HPKEEphemeralPrivateKey = Curve25519.KeyAgreement.PrivateKey
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,167 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
|
||||
|
||||
extension P256.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
/// Creates a NIST P-256 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||
public init() {
|
||||
self.init(compactRepresentable: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension P256.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
||||
|
||||
static func validatekem(_ kem: HPKE.KEM) throws {
|
||||
switch kem {
|
||||
case .P256_HKDF_SHA256: do {}
|
||||
default: do {
|
||||
throw HPKE.Errors.inconsistentCiphersuiteAndKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a NIST P-256 elliptic curve public key for use with Diffie-Hellman key exchange.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - serialization: The serialized bytes of the public key.
|
||||
/// - kem: The key encapsulation mechanism to use with the public key.
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public init<D>(_ serialization: D, kem: HPKE.KEM) throws where D: ContiguousBytes {
|
||||
try Self.validatekem(kem)
|
||||
try self.init(x963Representation: serialization)
|
||||
}
|
||||
|
||||
/// Creates a serialized representation of the public key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kem: The Key Encapsulation Mechanism to use with the public key.
|
||||
/// - Returns: The serialized representation of the public key.
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public func hpkeRepresentation(kem: HPKE.KEM) throws -> Data {
|
||||
try Self.validatekem(kem)
|
||||
return self.x963Representation
|
||||
}
|
||||
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias HPKEEphemeralPrivateKey = P256.KeyAgreement.PrivateKey
|
||||
}
|
||||
|
||||
|
||||
extension P384.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
/// Creates a NIST P-384 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||
public init() {
|
||||
self.init(compactRepresentable: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension P384.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = P384.KeyAgreement.PrivateKey
|
||||
|
||||
static func validatekem(_ kem: HPKE.KEM) throws {
|
||||
switch kem {
|
||||
case .P384_HKDF_SHA384: do {}
|
||||
default: do {
|
||||
throw HPKE.Errors.inconsistentCiphersuiteAndKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a NIST P-384 elliptic curve public key for use with Diffie-Hellman key exchange.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - serialization: The serialized bytes of the public key.
|
||||
/// - kem: The Key Encapsulation Mechanism to use with the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public init<D>(_ serialization: D, kem: HPKE.KEM) throws where D: ContiguousBytes {
|
||||
try Self.validatekem(kem)
|
||||
try self.init(x963Representation: serialization)
|
||||
}
|
||||
|
||||
/// Creates a serialized representation of the public key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kem: The Key Encapsulation Mechanism to use with the public key.
|
||||
///
|
||||
/// - Returns: The serialized representation of the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public func hpkeRepresentation(kem: HPKE.KEM) throws -> Data {
|
||||
try Self.validatekem(kem)
|
||||
return self.x963Representation
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension P521.KeyAgreement.PrivateKey: HPKEDiffieHellmanPrivateKeyGeneration {
|
||||
/// Creates a NIST P-521 elliptic curve private key for use with Diffie-Hellman key exchange.
|
||||
public init() {
|
||||
self.init(compactRepresentable: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension P521.KeyAgreement.PublicKey: HPKEDiffieHellmanPublicKey {
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias EphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
||||
|
||||
static func validatekem(_ kem: HPKE.KEM) throws {
|
||||
switch kem {
|
||||
case .P521_HKDF_SHA512: do {}
|
||||
default: do {
|
||||
throw HPKE.Errors.inconsistentCiphersuiteAndKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a NIST P-521 elliptic curve public key for use with Diffie-Hellman key exchange.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - serialization: The serialized bytes of the public key.
|
||||
/// - kem: The Key Encapsulation Mechanism to use with the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public init<D>(_ serialization: D, kem: HPKE.KEM) throws where D: ContiguousBytes {
|
||||
try Self.validatekem(kem)
|
||||
try self.init(x963Representation: serialization)
|
||||
}
|
||||
|
||||
/// Creates a serialized representation of the public key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kem: The Key Encapsulation Mechanism to use with the public key.
|
||||
///
|
||||
/// - Returns: The serialized representation of the public key.
|
||||
///
|
||||
/// - Throws: ``CryptoKit/HPKE/Errors/inconsistentCiphersuiteAndKey`` if the key encapsulation mechanism requested is incompatible with this public key.
|
||||
public func hpkeRepresentation(kem: HPKE.KEM) throws -> Data {
|
||||
try Self.validatekem(kem)
|
||||
return self.x963Representation
|
||||
}
|
||||
|
||||
/// The type of the ephemeral private key associated with this public key.
|
||||
public typealias HPKEEphemeralPrivateKey = P521.KeyAgreement.PrivateKey
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,68 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension HPKE {
|
||||
/// The key encapsulation mechanisms to use in HPKE.
|
||||
public enum KEM: CaseIterable, Hashable {
|
||||
/// A key encapsulation mechanism using NIST P-256 elliptic curve key agreement
|
||||
/// and SHA-2 hashing with a 256-bit digest.
|
||||
case P256_HKDF_SHA256
|
||||
/// A key encapsulation mechanism using NIST P-384 elliptic curve key agreement
|
||||
/// and SHA-2 hashing with a 384-bit digest.
|
||||
case P384_HKDF_SHA384
|
||||
/// A key encapsulation mechanism using NIST P-521 elliptic curve key agreement
|
||||
/// and SHA-2 hashing with a 512-bit digest.
|
||||
case P521_HKDF_SHA512
|
||||
/// A key encapsulation mechanism using X25519 elliptic curve key agreement
|
||||
/// and SHA-2 hashing with a 256-bit digest.
|
||||
case Curve25519_HKDF_SHA256
|
||||
|
||||
internal var value: UInt16 {
|
||||
switch self {
|
||||
case .P256_HKDF_SHA256: return 0x0010
|
||||
case .P384_HKDF_SHA384: return 0x0011
|
||||
case .P521_HKDF_SHA512: return 0x0012
|
||||
case .Curve25519_HKDF_SHA256: return 0x0020
|
||||
}
|
||||
}
|
||||
|
||||
internal var kdf: HPKE.KDF {
|
||||
switch self {
|
||||
case .P256_HKDF_SHA256: return .HKDF_SHA256
|
||||
case .P384_HKDF_SHA384: return .HKDF_SHA384
|
||||
case .P521_HKDF_SHA512: return .HKDF_SHA512
|
||||
case .Curve25519_HKDF_SHA256: return .HKDF_SHA256
|
||||
}
|
||||
}
|
||||
|
||||
internal var identifier: Data {
|
||||
return I2OSP(value: Int(self.value), outputByteCount: 2)
|
||||
}
|
||||
|
||||
internal var nSecret: UInt16 {
|
||||
switch self {
|
||||
case .P256_HKDF_SHA256: return 32
|
||||
case .P384_HKDF_SHA384: return 48
|
||||
case .P521_HKDF_SHA512: return 64
|
||||
case .Curve25519_HKDF_SHA256: return 32
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,41 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension HPKE {
|
||||
/// Hybrid public key encryption (HPKE) errors that CryptoKit uses.
|
||||
public enum Errors: Error {
|
||||
/// The parameters for initializing an HPKE sender or receiver are inconsistent.
|
||||
case inconsistentParameters
|
||||
/// The supplied encryption key is incompatible with the requested cipher suite.
|
||||
case inconsistentCiphersuiteAndKey
|
||||
/// The object is in export-only mode and received a request to encrypt or decrypt data.
|
||||
case exportOnlyMode
|
||||
/// The PSK is nil and the PSK ID isn't nil, or the PSK ID is nil and the PSK isn't nil.
|
||||
case inconsistentPSKInputs
|
||||
/// The PSK is nil and the object is in PSK mode, or in authentication and PSK mode.
|
||||
case expectedPSK
|
||||
/// The PSK isn't nil and the object is in base mode, or in authentication mode.
|
||||
case unexpectedPSK
|
||||
/// The sequence number for encrypting or decrypting the message is out of range.
|
||||
case outOfRangeSequenceNumber
|
||||
/// The ciphertext is too short.
|
||||
case ciphertextTooShort
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,320 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A container for hybrid public key encryption (HPKE) operations.
|
||||
///
|
||||
/// Hybrid public key encryption (HPKE) uses a symmetric encryption algorithm to encrypt data, and encapsulates the symmetric
|
||||
/// encryption material using a public key encryption algorithm.
|
||||
///
|
||||
/// HPKE ensures that the ciphertext wasn't tampered with after its creation. It can also check the validity
|
||||
/// of additional cleartext data in apps where you need to send headers or other metadata as cleartext.
|
||||
///
|
||||
/// HPKE optionally incorporates sender authentication, allowing the recipient to validate the authenticity of
|
||||
/// messages using the sender's public key.
|
||||
///
|
||||
/// HPKE is described in the Internet Research Task Force (IRTF) document
|
||||
/// [RFC 9180](https://www.ietf.org/rfc/rfc9180.pdf).
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Sending and receiving messages
|
||||
/// - ``Sender``
|
||||
/// - ``Recipient``
|
||||
///
|
||||
/// ### Choosing cryptographic algorithms
|
||||
/// - ``Ciphersuite``
|
||||
/// - ``AEAD``
|
||||
/// - ``KDF``
|
||||
/// - ``KEM``
|
||||
/// - ``DHKEM``
|
||||
///
|
||||
/// ### Handling errors
|
||||
/// - ``Errors``
|
||||
public enum HPKE {}
|
||||
|
||||
extension HPKE {
|
||||
/// A type that represents the sending side of an HPKE message exchange.
|
||||
///
|
||||
/// To create encrypted messages, initialize a `Sender` specifying the appropriate cipher suite,
|
||||
/// the recipient's public key, and the additional cryptographic material relevant to your chosen mode of operation.
|
||||
/// Call ``seal(_:)`` or ``seal(_:authenticating:)`` on the `Sender` instance for each message
|
||||
/// in turn to retrieve its ciphertext. The recipient of the messages needs to process them in the
|
||||
/// same order as the `Sender`, using the same encryption mode, cipher suite, and key schedule information
|
||||
/// (`info`), as well as the `Sender`'s ``encapsulatedKey``.
|
||||
public struct Sender {
|
||||
private var context: Context
|
||||
/// The encapsulated symmetric key that the recipient uses to decrypt messages.
|
||||
public let encapsulatedKey: Data
|
||||
|
||||
/// The exporter secret.
|
||||
internal var exporterSecret: SymmetricKey {
|
||||
return context.keySchedule.exporterSecret
|
||||
}
|
||||
|
||||
/// Exports a secret given domain-separation context and the desired output length.
|
||||
/// - Parameters:
|
||||
/// - context: Application-specific information providing context on the use of this key.
|
||||
/// - outputByteCount: The desired length of the exported secret.
|
||||
/// - Returns: The exported secret.
|
||||
public func exportSecret<Context: DataProtocol>(context: Context, outputByteCount: Int) throws -> SymmetricKey {
|
||||
precondition(outputByteCount > 0);
|
||||
return LabeledExpand(prk: self.exporterSecret,
|
||||
label: Data("sec".utf8),
|
||||
info: context,
|
||||
outputByteCount: UInt16(outputByteCount),
|
||||
suiteID: self.context.keySchedule.ciphersuite.identifier,
|
||||
kdf: self.context.keySchedule.ciphersuite.kdf)
|
||||
}
|
||||
|
||||
/// Creates a sender in base mode.
|
||||
///
|
||||
/// The `Sender` encrypts messages in base mode with a symmetric encryption key it derives using a key derivation function (KDF).
|
||||
/// The KDF uses the key schedule data in `info` as input to generate the key.
|
||||
/// The `Sender` encapsulates the derived key using the recipient's public key.
|
||||
/// You access the encapsulated key using ``encapsulatedKey``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - recipientKey: The recipient's public key for encrypting the messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<PK: HPKEDiffieHellmanPublicKey>(recipientKey: PK, ciphersuite: Ciphersuite, info: Data) throws {
|
||||
self.context = try Context(senderRoleWithCiphersuite: ciphersuite, mode: .base, psk: nil, pskID: nil, pkR: recipientKey, info: info)
|
||||
self.encapsulatedKey = context.encapsulated
|
||||
}
|
||||
|
||||
/// Creates a sender in preshared key (PSK) mode.
|
||||
///
|
||||
/// The `Sender` encrypts messages in PSK mode using a symmetric encryption key that the sender and recipient both know in advance, in combination with a key it derives using a key derivation function (KDF) and
|
||||
/// the key schedule data in `info`.
|
||||
/// The `Sender` encapsulates the derived key using the recipient's public key.
|
||||
/// You access the encapsulated key using ``encapsulatedKey``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - recipientKey: The recipient's public key for encrypting the messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - psk: A preshared key (PSK) that the sender and the recipient both hold.
|
||||
/// - pskID: An identifier for the PSK.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<PK: HPKEDiffieHellmanPublicKey>(recipientKey: PK, ciphersuite: Ciphersuite, info: Data, presharedKey psk: SymmetricKey, presharedKeyIdentifier pskID: Data) throws {
|
||||
self.context = try Context(senderRoleWithCiphersuite: ciphersuite, mode: .psk, psk: psk, pskID: pskID, pkR: recipientKey, info: info)
|
||||
self.encapsulatedKey = context.encapsulated
|
||||
}
|
||||
|
||||
/// Creates a sender in authentication mode.
|
||||
///
|
||||
/// The `Sender` encrypts messages in authentication mode with a symmetric encryption key.
|
||||
/// Messages also include authentication data so that the recipient can verify the authenticity of the sender’s private key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - recipientKey: The recipient's public key for encrypting the messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - authenticationKey: The sender's private key for generating the HMAC.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(recipientKey: SK.PublicKey, ciphersuite: Ciphersuite, info: Data, authenticatedBy authenticationKey: SK) throws {
|
||||
self.context = try Context(senderRoleWithCiphersuite: ciphersuite, mode: .auth, psk: nil, pskID: nil, pkR: recipientKey, info: info, skS: authenticationKey)
|
||||
self.encapsulatedKey = context.encapsulated
|
||||
}
|
||||
|
||||
/// Creates a sender in authentication and preshared key mode.
|
||||
///
|
||||
/// The `Sender` encrypts messages in authentication and preshared key (`auth_psk`) mode using
|
||||
/// a symmetric encryption key that the sender and recipient both know in advance, in combination with a key it derives using a key derivation function (KDF) and
|
||||
/// the key schedule data in `info`.
|
||||
/// Messages also include authentication data so that the recipient can verify the authenticity of the sender’s private key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - recipientKey: The recipient's public key for encrypting the messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - authenticationKey: The sender's private key for generating the HMAC.
|
||||
/// - psk: A preshared key (PSK) that the sender and the recipient both hold.
|
||||
/// - pskID: An identifier for the PSK.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(recipientKey: SK.PublicKey, ciphersuite: Ciphersuite, info: Data, authenticatedBy authenticationKey: SK, presharedKey psk: SymmetricKey, presharedKeyIdentifier pskID: Data) throws {
|
||||
self.context = try Context(senderRoleWithCiphersuite: ciphersuite, mode: .auth_psk, psk: psk, pskID: pskID, pkR: recipientKey, info: info, skS: authenticationKey)
|
||||
self.encapsulatedKey = context.encapsulated
|
||||
}
|
||||
|
||||
/// Encrypts the given cleartext message and attaches additional authenticated data.
|
||||
///
|
||||
/// You can call this method multiple times to encrypt a series of messages.
|
||||
/// When using this method, you need to supply ciphertext messages to the decryption
|
||||
/// code on the receiving side in the same order as you encrypt them.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - msg: The cleartext message to encrypt.
|
||||
/// - aad: Additional data that the `Sender` authenticates and adds to the message in cleartext.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
/// - Returns: The ciphertext for the recipient to decrypt.
|
||||
public mutating func seal<M: DataProtocol, AD: DataProtocol>(_ msg: M, authenticating aad: AD) throws -> Data {
|
||||
return try context.keySchedule.seal(msg, authenticating: aad)
|
||||
}
|
||||
|
||||
/// Encrypts the given cleartext message.
|
||||
///
|
||||
/// You can call this method multiple times to encrypt a series of messages.
|
||||
/// When using this method, you need to supply ciphertext messages to the decryption
|
||||
/// code on the receiving side in the same order as you encrypt them.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - msg: The cleartext message to encrypt.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
/// - Returns: The ciphertext for the recipient to decrypt.
|
||||
public mutating func seal<M: DataProtocol>(_ msg: M) throws -> Data {
|
||||
return try context.keySchedule.seal(msg, authenticating: Data())
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that represents the receiving side of an HPKE message exchange.
|
||||
///
|
||||
/// To decrypt and verify the identity of encrypted messages, initialize a `Recipient` specifying the appropriate
|
||||
/// cipher suite, the receiver's private key, the encapsulated symmetric key, and the additional cryptographic
|
||||
/// material relevant to your chosen mode of operation.
|
||||
/// Call ``open(_:)`` or ``open(_:authenticating:)`` on the `Recipient` instance for each message
|
||||
/// in turn to retrieve its cleartext. The recipient of the messages needs to process them in the
|
||||
/// same order as the `Sender`, using the same cipher suite, encryption mode, and key schedule information
|
||||
/// (`info` data).
|
||||
/// Use a separate `Recipient` instance for each stream of messages.
|
||||
public struct Recipient {
|
||||
|
||||
private var context: Context
|
||||
|
||||
/// The exporter secret.
|
||||
internal var exporterSecret: SymmetricKey {
|
||||
return context.keySchedule.exporterSecret
|
||||
}
|
||||
|
||||
/// Exports a secret given domain-separation context and the desired output length.
|
||||
/// - Parameters:
|
||||
/// - context: Application-specific information providing context on the use of this key.
|
||||
/// - outputByteCount: The desired length of the exported secret.
|
||||
/// - Returns: The exported secret.
|
||||
public func exportSecret<Context: DataProtocol>(context: Context, outputByteCount: Int) throws -> SymmetricKey {
|
||||
precondition(outputByteCount > 0);
|
||||
return LabeledExpand(prk: self.exporterSecret,
|
||||
label: Data("sec".utf8),
|
||||
info: context,
|
||||
outputByteCount: UInt16(outputByteCount),
|
||||
suiteID: self.context.keySchedule.ciphersuite.identifier,
|
||||
kdf: self.context.keySchedule.ciphersuite.kdf)
|
||||
}
|
||||
|
||||
/// Creates a recipient in base mode.
|
||||
///
|
||||
/// The `Receiver` decrypts messages in base mode using the encapsulated key with the key schedule information (`info` data).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - privateKey: The recipient's private key for decrypting the incoming messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - encapsulatedKey: The encapsulated symmetric key that the sender provides.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data) throws {
|
||||
self.context = try Context(recipientRoleWithCiphersuite: ciphersuite, mode: .base, enc: encapsulatedKey, psk: nil, pskID: nil, skR: privateKey, info: info, pkS: nil)
|
||||
}
|
||||
|
||||
/// Creates a recipient in preshared key (PSK) mode.
|
||||
///
|
||||
/// The `Receiver` decrypts messages in PSK mode using the encapsulated key with the key schedule information (`info` data),
|
||||
/// in addition to a symmetric encryption key that the sender and recipient both know in advance.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - privateKey: The recipient's private key for decrypting the incoming messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - encapsulatedKey: The encapsulated symmetric key that the sender provides.
|
||||
/// - psk: A preshared key (PSK) that the sender and the recipient both hold.
|
||||
/// - pskID: An identifier for the PSK.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data, presharedKey psk: SymmetricKey, presharedKeyIdentifier pskID: Data) throws {
|
||||
self.context = try Context(recipientRoleWithCiphersuite: ciphersuite, mode: .psk, enc: encapsulatedKey, psk: psk, pskID: pskID, skR: privateKey, info: info, pkS: nil)
|
||||
}
|
||||
|
||||
/// Creates a recipient in authentication mode.
|
||||
///
|
||||
/// The `Receiver` decrypts messages in authentication mode using the encapsulated key with the key schedule information (`info` data).
|
||||
/// Messages also include authentication data so that the recipient can verify the authenticity of the sender’s private key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - privateKey: The recipient's private key for decrypting the incoming messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - encapsulatedKey: The encapsulated symmetric key that the sender provides.
|
||||
/// - authenticationKey: The sender's public key for authenticating the messages.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data, authenticatedBy authenticationKey: SK.PublicKey) throws {
|
||||
self.context = try Context(recipientRoleWithCiphersuite: ciphersuite, mode: .auth, enc: encapsulatedKey, psk: nil, pskID: nil, skR: privateKey, info: info, pkS: authenticationKey)
|
||||
}
|
||||
|
||||
/// Creates a recipient in authentication and preshared key mode.
|
||||
///
|
||||
/// The `Receiver` decrypts messages it receives in authentication and preshared key (`auth_psk`) mode
|
||||
/// using the encapsulated key with the key schedule information (`info` data),
|
||||
/// in addition to a symmetric encryption key that the sender and recipient both know in advance.
|
||||
/// Messages also include authentication data so that the recipient can verify the authenticity of the sender’s private key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - privateKey: The recipient's private key for decrypting the incoming messages.
|
||||
/// - ciphersuite: The cipher suite that defines the cryptographic algorithms to use.
|
||||
/// - info: Data that the key derivation function uses to compute the symmetric key material. The sender and the recipient need to use the same `info` data.
|
||||
/// - encapsulatedKey: The encapsulated symmetric key that the sender provides.
|
||||
/// - authenticationKey: The sender's public key for authenticating the messages.
|
||||
/// - psk: A preshared key (PSK) that the sender and the recipient both hold.
|
||||
/// - pskID: An identifier for the PSK.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
public init<SK: HPKEDiffieHellmanPrivateKey>(privateKey: SK, ciphersuite: Ciphersuite, info: Data, encapsulatedKey: Data, authenticatedBy authenticationKey: SK.PublicKey, presharedKey psk: SymmetricKey, presharedKeyIdentifier pskID: Data) throws {
|
||||
self.context = try Context(recipientRoleWithCiphersuite: ciphersuite, mode: .auth_psk, enc: encapsulatedKey, psk: psk, pskID: pskID, skR: privateKey, info: info, pkS: authenticationKey)
|
||||
}
|
||||
|
||||
/// Decrypts a message, if the ciphertext is valid, verifying the integrity of additional authentication data.
|
||||
///
|
||||
/// You can call this method multiple times to decrypt a series of messages.
|
||||
/// When using this method, the recipient of the ciphertext messages needs to decrypt
|
||||
/// them in the same order that the sender encrypts them.
|
||||
/// The system doesn't decrypt the additional authentication data in the `aad` parameter
|
||||
/// that the recipient uses to verify the message integrity.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ciphertext: The ciphertext message to decrypt.
|
||||
/// - aad: Additional cleartext data to authenticate.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
/// - Returns: The resulting cleartext message if the message is authentic.
|
||||
public mutating func open<C: DataProtocol, AD: DataProtocol>(_ ciphertext: C, authenticating aad: AD) throws -> Data {
|
||||
return try context.keySchedule.open(ciphertext, authenticating: aad)
|
||||
}
|
||||
|
||||
/// Decrypts a message, if the ciphertext is valid.
|
||||
///
|
||||
/// You can call this method multiple times to decrypt a series of messages.
|
||||
/// When using this method, the recipient of the ciphertext messages needs to decrypt
|
||||
/// them in the same order that the sender encrypts them.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ciphertext: The ciphertext message to decrypt.
|
||||
/// - Note: The system throws errors from ``CryptoKit/HPKE/Errors`` when it encounters them.
|
||||
/// - Returns: The resulting cleartext message if the message is authentic.
|
||||
public mutating func open<C: DataProtocol>(_ ciphertext: C) throws -> Data {
|
||||
return try context.keySchedule.open(ciphertext, authenticating: Data())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,61 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension HPKE {
|
||||
struct Context {
|
||||
var keySchedule: KeySchedule
|
||||
var encapsulated: Data
|
||||
|
||||
init<PublicKey: HPKEDiffieHellmanPublicKey>(senderRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, psk: SymmetricKey?, pskID: Data?, pkR: PublicKey, info: Data) throws {
|
||||
let pkRKEM = try HPKE.DHKEM.PublicKey(pkR, kem: ciphersuite.kem)
|
||||
|
||||
let encapsulationResult = try pkRKEM.encapsulate()
|
||||
encapsulated = encapsulationResult.encapsulated
|
||||
self.keySchedule = try KeySchedule(mode: mode,
|
||||
sharedSecret: encapsulationResult.sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
|
||||
}
|
||||
|
||||
init<SK: HPKEDiffieHellmanPrivateKey>(senderRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, psk: SymmetricKey?, pskID: Data?, pkR: SK.PublicKey, info: Data, skS: SK) throws {
|
||||
|
||||
let skSKEM = try HPKE.DHKEM.PrivateKey(skS, kem: ciphersuite.kem)
|
||||
let pkRKEM = try HPKE.DHKEM.PublicKey(pkR, kem: ciphersuite.kem)
|
||||
|
||||
let encapsulationResult = try skSKEM.authenticateAndEncapsulateTo(pkRKEM)
|
||||
|
||||
encapsulated = encapsulationResult.encapsulated
|
||||
self.keySchedule = try KeySchedule(mode: mode, sharedSecret: encapsulationResult.sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
|
||||
}
|
||||
|
||||
init<PrivateKey: HPKEDiffieHellmanPrivateKey>(recipientRoleWithCiphersuite ciphersuite: Ciphersuite, mode: Mode, enc: Data, psk: SymmetricKey?, pskID: Data?, skR: PrivateKey, info: Data, pkS: PrivateKey.PublicKey?) throws {
|
||||
let skRKEM = try HPKE.DHKEM.PrivateKey(skR, kem: ciphersuite.kem)
|
||||
|
||||
let sharedSecret: SymmetricKey
|
||||
if let pkS = pkS {
|
||||
sharedSecret = try skRKEM.decapsulate(enc, authenticating: pkS)
|
||||
} else {
|
||||
sharedSecret = try skRKEM.decapsulate(enc)
|
||||
}
|
||||
|
||||
self.encapsulated = enc
|
||||
self.keySchedule = try KeySchedule(mode: mode, sharedSecret: sharedSecret, info: info, psk: psk, pskID: pskID, ciphersuite: ciphersuite)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,144 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension HPKE {
|
||||
internal struct KeySchedule {
|
||||
fileprivate static let pksIDHashLabel = Data("psk_id_hash".utf8)
|
||||
fileprivate static let infoHashLabel = Data("info_hash".utf8)
|
||||
fileprivate static let secretLabel = Data("secret".utf8)
|
||||
fileprivate static let keyLabel = Data("key".utf8)
|
||||
fileprivate static let baseLabel = Data("base_nonce".utf8)
|
||||
fileprivate static let exporterLabel = Data("exp".utf8)
|
||||
|
||||
var sequenceNumber: UInt64 = 0
|
||||
var key: SymmetricKey?
|
||||
var nonce: Data?
|
||||
var exporterSecret: SymmetricKey
|
||||
var ciphersuite: HPKE.Ciphersuite
|
||||
|
||||
static func verifyPSKInputs(mode: HPKE.Mode, psk: SymmetricKey?, pskID: Data?) throws {
|
||||
let gotPSK = (psk != nil)
|
||||
let gotPSKID = (pskID != nil)
|
||||
|
||||
if gotPSK != gotPSKID {
|
||||
throw HPKE.Errors.inconsistentPSKInputs
|
||||
}
|
||||
|
||||
if gotPSK && !HPKE.Mode.pskModes.contains(mode) {
|
||||
throw HPKE.Errors.unexpectedPSK
|
||||
}
|
||||
|
||||
if !gotPSK && HPKE.Mode.pskModes.contains(mode) {
|
||||
throw HPKE.Errors.expectedPSK
|
||||
}
|
||||
}
|
||||
|
||||
init(mode: HPKE.Mode, sharedSecret: ContiguousBytes, info: Data, psk: SymmetricKey?, pskID: Data?, ciphersuite: Ciphersuite) throws {
|
||||
try HPKE.KeySchedule.verifyPSKInputs(mode: mode, psk: psk, pskID: pskID)
|
||||
|
||||
let pskIDHash = NonSecretOutputLabeledExtract(salt: nil,
|
||||
label: HPKE.KeySchedule.pksIDHashLabel,
|
||||
ikm: pskID.map { SymmetricKey(data: $0) },
|
||||
suiteID: ciphersuite.identifier,
|
||||
kdf: ciphersuite.kdf)
|
||||
|
||||
let infoHash = NonSecretOutputLabeledExtract(salt: nil,
|
||||
label: HPKE.KeySchedule.infoHashLabel,
|
||||
ikm: SymmetricKey(data: info),
|
||||
suiteID: ciphersuite.identifier,
|
||||
kdf: ciphersuite.kdf)
|
||||
|
||||
var keyScheduleContext = Data()
|
||||
keyScheduleContext.append(mode.value)
|
||||
keyScheduleContext.append(pskIDHash)
|
||||
keyScheduleContext.append(infoHash)
|
||||
|
||||
let secret = LabeledExtract(salt: Data(unsafeFromContiguousBytes: sharedSecret),
|
||||
label: HPKE.KeySchedule.secretLabel,
|
||||
ikm: psk.map { SymmetricKey(data: $0) },
|
||||
suiteID: ciphersuite.identifier,
|
||||
kdf: ciphersuite.kdf)
|
||||
|
||||
if !ciphersuite.aead.isExportOnly {
|
||||
self.key = LabeledExpand(prk: secret,
|
||||
label: HPKE.KeySchedule.keyLabel,
|
||||
info: keyScheduleContext,
|
||||
outputByteCount: UInt16(ciphersuite.aead.keyByteCount),
|
||||
suiteID: ciphersuite.identifier,
|
||||
kdf: ciphersuite.kdf)
|
||||
|
||||
self.nonce = NonSecretOutputLabeledExpand(prk: secret,
|
||||
label: HPKE.KeySchedule.baseLabel,
|
||||
info: keyScheduleContext,
|
||||
outputByteCount: UInt16(ciphersuite.aead.nonceByteCount),
|
||||
suiteID: ciphersuite.identifier,
|
||||
kdf: ciphersuite.kdf)
|
||||
}
|
||||
|
||||
self.exporterSecret = LabeledExpand(prk: secret,
|
||||
label: HPKE.KeySchedule.exporterLabel,
|
||||
info: keyScheduleContext,
|
||||
outputByteCount: UInt16(ciphersuite.kdf.Nh),
|
||||
suiteID: ciphersuite.identifier,
|
||||
kdf: ciphersuite.kdf)
|
||||
|
||||
|
||||
self.ciphersuite = ciphersuite
|
||||
}
|
||||
|
||||
mutating func incrementSequenceNumber() throws {
|
||||
if self.sequenceNumber >= ((1 << (self.ciphersuite.aead.nonceByteCount)) - 1) {
|
||||
throw HPKE.Errors.outOfRangeSequenceNumber
|
||||
}
|
||||
sequenceNumber += 1
|
||||
}
|
||||
|
||||
mutating func seal<M: DataProtocol, AD: DataProtocol>(_ msg: M, authenticating aad: AD) throws -> Data {
|
||||
guard !self.ciphersuite.aead.isExportOnly else {
|
||||
throw HPKE.Errors.exportOnlyMode
|
||||
}
|
||||
|
||||
let ct = try ciphersuite.aead.seal(msg, authenticating: aad, nonce: currentNonce, using: self.key!)
|
||||
try incrementSequenceNumber()
|
||||
return ct
|
||||
}
|
||||
|
||||
mutating func open<C: DataProtocol, AD: DataProtocol>(_ ciphertext: C, authenticating aad: AD) throws -> Data {
|
||||
guard !self.ciphersuite.aead.isExportOnly else {
|
||||
throw HPKE.Errors.exportOnlyMode
|
||||
}
|
||||
|
||||
let pt = try ciphersuite.aead.open(ciphertext, nonce: currentNonce, authenticating: aad, using: self.key!)
|
||||
try incrementSequenceNumber()
|
||||
return pt
|
||||
}
|
||||
|
||||
var currentNonce: Data {
|
||||
var nonceData = [UInt8](repeating: 0, count: ciphersuite.aead.nonceByteCount - MemoryLayout.size(ofValue: sequenceNumber))
|
||||
var bigEndian = sequenceNumber.bigEndian
|
||||
withUnsafeBytes(of: &(bigEndian)) { (bufferPointer) in
|
||||
nonceData.append(contentsOf: bufferPointer)
|
||||
}
|
||||
let nonce = self.nonce!
|
||||
precondition(nonce.count == nonceData.count)
|
||||
return Data(zip(nonceData, nonce).lazy.map { $0.0 ^ $0.1 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -0,0 +1,41 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
|
||||
extension HPKE {
|
||||
|
||||
internal enum Mode: CaseIterable {
|
||||
case base
|
||||
case psk
|
||||
case auth
|
||||
case auth_psk
|
||||
|
||||
var value: UInt8 {
|
||||
switch self {
|
||||
case .base: return 0x00
|
||||
case .psk: return 0x01
|
||||
case .auth: return 0x02
|
||||
case .auth_psk: return 0x03
|
||||
}
|
||||
}
|
||||
|
||||
static var pskModes: [HPKE.Mode] {
|
||||
return [Mode.psk, Mode.auth_psk]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -14,7 +14,10 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// Algorithms that we support for legacy reasons but that are insecure to use.
|
||||
/// Do not adopt in new protocols.
|
||||
/// A container for older, cryptographically insecure algorithms.
|
||||
///
|
||||
/// - Important: These algorithms aren’t considered cryptographically secure,
|
||||
/// but the framework provides them for backward compatibility with older
|
||||
/// services that require them. For new services, avoid these algorithms.
|
||||
public enum Insecure {}
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -15,70 +15,176 @@
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
extension Insecure {
|
||||
/// The SHA-1 Hash Function.
|
||||
/// ⚠️ Security Recommendation: The SHA-1 hash function is no longer considered secure. We strongly recommend using the SHA-256 hash function instead.
|
||||
/// An implementation of SHA1 hashing.
|
||||
///
|
||||
/// The ``SHA1`` hash implements the ``HashFunction`` protocol to produce a
|
||||
/// SHA1 digest (``SHA1Digest``).
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to
|
||||
/// fit in memory, you can compute the digest iteratively by creating a new
|
||||
/// hash instance, calling the ``update(data:)`` method repeatedly with
|
||||
/// blocks of data, and then calling the ``finalize()`` method to get the
|
||||
/// result.
|
||||
///
|
||||
/// - Important: This hash algorithm isn’t considered cryptographically
|
||||
/// secure, but is provided for backward compatibility with older services
|
||||
/// that require it. For new services, prefer one of the secure hashes, like
|
||||
/// ``SHA512``.
|
||||
public struct SHA1: HashFunctionImplementationDetails {
|
||||
/// The number of bytes that represents the hash function’s internal
|
||||
/// state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set SHA1.blockByteCount") }
|
||||
}
|
||||
|
||||
/// The number of bytes in a SHA1 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 20 }
|
||||
|
||||
set { fatalError("Cannot set SHA1.byteCount") }
|
||||
}
|
||||
|
||||
/// The digest type for a SHA1 hash function.
|
||||
public typealias Digest = Insecure.SHA1Digest
|
||||
var impl: DigestImpl<SHA1>
|
||||
|
||||
/// Initializes the hash function instance.
|
||||
/// Creates a SHA1 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash the data iteratively, such as when you don’t have a buffer
|
||||
/// large enough to hold all the data at once. Provide data blocks to
|
||||
/// the hash function using the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After providing all the data,
|
||||
/// call ``finalize()`` to get the digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the
|
||||
/// ``hash(data:)`` method instead, to compute the digest in a single
|
||||
/// call.
|
||||
public init() {
|
||||
impl = DigestImpl()
|
||||
}
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the
|
||||
/// buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash
|
||||
/// function in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the
|
||||
/// update method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or
|
||||
/// some other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Returns the digest from the data input in the hash function instance.
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// - Returns: The digest of the inputted data
|
||||
/// Call this method after you provide the hash function with all the
|
||||
/// data to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash
|
||||
/// function, discard it. To compute a new digest, create a new hash
|
||||
/// function with a call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
/// The MD5 Hash Function.
|
||||
/// ⚠️ Security Recommendation: The MD5 hash function is no longer considered secure. We strongly recommend using the SHA-256 hash function instead.
|
||||
/// An implementation of MD5 hashing.
|
||||
///
|
||||
/// The ``MD5`` hash implements the ``HashFunction`` protocol to produce an
|
||||
/// MD5 digest (``MD5Digest``).
|
||||
///
|
||||
/// You can compute the digest by calling the static ``hash(data:)`` method
|
||||
/// once. Alternatively, if the data that you want to hash is too large to
|
||||
/// fit in memory, you can compute the digest iteratively by creating a new
|
||||
/// hash instance, calling the ``update(data:)`` method repeatedly with
|
||||
/// blocks of data, and then calling the ``finalize()`` method to get the
|
||||
/// result.
|
||||
///
|
||||
/// - Important: This hash algorithm isn’t considered cryptographically
|
||||
/// secure, but is provided for backward compatibility with older services
|
||||
/// that require it. For new services, prefer one of the secure hashes, like
|
||||
/// ``SHA512``.
|
||||
public struct MD5: HashFunctionImplementationDetails {
|
||||
/// The number of bytes that represents the hash function’s internal
|
||||
/// state.
|
||||
public static var blockByteCount: Int {
|
||||
get { 64 }
|
||||
|
||||
set { fatalError("Cannot set MD5.blockByteCount") }
|
||||
}
|
||||
/// The number of bytes in an MD5 digest.
|
||||
public static var byteCount: Int {
|
||||
get { 16 }
|
||||
|
||||
set { fatalError("Cannot set MD5.byteCount") }
|
||||
}
|
||||
|
||||
/// The digest type for a MD5 hash function.
|
||||
public typealias Digest = Insecure.MD5Digest
|
||||
var impl: DigestImpl<MD5>
|
||||
|
||||
/// Initializes the hash function instance.
|
||||
/// Creates a MD5 hash function.
|
||||
///
|
||||
/// Initialize a new hash function by calling this method if you want to
|
||||
/// hash the data iteratively, such as when you don’t have a buffer
|
||||
/// large enough to hold all the data at once. Provide data blocks to
|
||||
/// the hash function using the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After providing all the data,
|
||||
/// call ``finalize()`` to get the digest.
|
||||
///
|
||||
/// If your data fits into a single buffer, you can use the
|
||||
/// ``hash(data:)`` method instead, to compute the digest in a single
|
||||
/// call.
|
||||
public init() {
|
||||
impl = DigestImpl()
|
||||
}
|
||||
|
||||
/// Incrementally updates the hash function with the contents of the
|
||||
/// buffer.
|
||||
///
|
||||
/// Call this method one or more times to provide data to the hash
|
||||
/// function in blocks. After providing the last block of data, call the
|
||||
/// ``finalize()`` method to get the computed digest. Don’t call the
|
||||
/// update method again after finalizing the hash function.
|
||||
///
|
||||
/// - Note: Typically, it’s safer to use an instance of
|
||||
/// <doc://com.apple.documentation/documentation/foundation/data>, or
|
||||
/// some other type that conforms to the
|
||||
/// <doc://com.apple.documentation/documentation/foundation/dataprotocol>,
|
||||
/// to hold your data. When possible, use the ``update(data:)`` method
|
||||
/// instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bufferPointer: A pointer to the next block of data for the ongoing
|
||||
/// digest calculation.
|
||||
public mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
impl.update(data: bufferPointer)
|
||||
}
|
||||
|
||||
/// Returns the digest from the data input in the hash function instance.
|
||||
/// Finalizes the hash function and returns the computed digest.
|
||||
///
|
||||
/// - Returns: The digest of the inputted data
|
||||
/// Call this method after you provide the hash function with all the
|
||||
/// data to hash by making one or more calls to the ``update(data:)`` or
|
||||
/// ``update(bufferPointer:)`` method. After finalizing the hash
|
||||
/// function, discard it. To compute a new digest, create a new hash
|
||||
/// function with a call to the ``init()`` method.
|
||||
///
|
||||
/// - Returns: The computed digest of the data.
|
||||
public func finalize() -> Self.Digest {
|
||||
return impl.finalize()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A Key Encapsulation Mechanism
|
||||
public enum KEM {
|
||||
/// The result of an encapsulation operation
|
||||
public struct EncapsulationResult {
|
||||
/// The shared secret
|
||||
public let sharedSecret: SymmetricKey
|
||||
/// The encapsulated secret
|
||||
public let encapsulated: Data
|
||||
|
||||
public init(sharedSecret: SymmetricKey, encapsulated: Data) {
|
||||
self.sharedSecret = sharedSecret
|
||||
self.encapsulated = encapsulated
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Key Encapsulation Mechanism's Public Key
|
||||
public protocol KEMPublicKey {
|
||||
/// Encapsulates the generated shared secret
|
||||
/// - Returns: The shared secret and its encapsulated version
|
||||
func encapsulate() throws -> KEM.EncapsulationResult
|
||||
}
|
||||
|
||||
/// A Key Encapsulation Mechanism's Private Key
|
||||
public protocol KEMPrivateKey {
|
||||
associatedtype PublicKey: KEMPublicKey
|
||||
|
||||
/// Generate a new random Private Key
|
||||
/// - Returns: The generated private key
|
||||
static func generate() throws -> Self
|
||||
|
||||
/// Decapsulates the encapsulated shared secret
|
||||
/// - Parameter encapsulated: The encapsulated shared secret
|
||||
/// - Returns: The decapsulated shared secret
|
||||
func decapsulate(_ encapsulated: Data) throws -> SymmetricKey
|
||||
|
||||
/// Returns the associated public key
|
||||
var publicKey: PublicKey { get }
|
||||
}
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -17,34 +17,60 @@
|
||||
import Foundation
|
||||
|
||||
/// A Diffie-Hellman Key Agreement Key
|
||||
protocol DiffieHellmanKeyAgreement {
|
||||
public protocol DiffieHellmanKeyAgreement {
|
||||
/// The public key share type to perform the DH Key Agreement
|
||||
associatedtype P
|
||||
var publicKey: P { get }
|
||||
associatedtype PublicKey
|
||||
var publicKey: PublicKey { get }
|
||||
|
||||
/// Performs a Diffie-Hellman Key Agreement
|
||||
/// Performs a Diffie-Hellman Key Agreement.
|
||||
///
|
||||
/// - Parameter publicKeyShare: The public key share
|
||||
/// - Returns: The resulting key agreement result
|
||||
func sharedSecretFromKeyAgreement(with publicKeyShare: P) throws -> SharedSecret
|
||||
/// - Parameters:
|
||||
/// - publicKeyShare: The public key share.
|
||||
/// - Returns: The resulting key agreement result.
|
||||
func sharedSecretFromKeyAgreement(with publicKeyShare: PublicKey) throws -> SharedSecret
|
||||
}
|
||||
|
||||
/// A Key Agreement Result
|
||||
/// A SharedSecret has to go through a Key Derivation Function before being able to use by a symmetric key operation.
|
||||
/// A key agreement result from which you can derive a symmetric cryptographic
|
||||
/// key.
|
||||
///
|
||||
/// Generate a shared secret by calling your private key’s
|
||||
/// `sharedSecretFromKeyAgreement(publicKeyShare:)` method with the public key
|
||||
/// from another party. The other party computes the same secret by passing your
|
||||
/// public key to the equivalent method on their own private key.
|
||||
///
|
||||
/// The shared secret isn’t suitable as a symmetric cryptographic key
|
||||
/// (``SymmetricKey``) by itself. However, you use it to generate a key by
|
||||
/// calling either the
|
||||
/// ``hkdfDerivedSymmetricKey(using:salt:sharedInfo:outputByteCount:)`` or
|
||||
/// ``x963DerivedSymmetricKey(using:sharedInfo:outputByteCount:)`` method of the
|
||||
/// shared secret. After the other party does the same, then you both share a
|
||||
/// symmetric key suitable for creating a message authentication code like
|
||||
/// ``HMAC``, or for opening and closing a sealed box with a cipher like
|
||||
/// ``ChaChaPoly`` or ``AES``.
|
||||
public struct SharedSecret: ContiguousBytes {
|
||||
var ss: SecureBytes
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes
|
||||
/// of the shared secret.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the
|
||||
/// shared secret and returns the shared secret.
|
||||
///
|
||||
/// - Returns: The shared secret, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try ss.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
/// Derives a symmetric encryption key using X9.63 key derivation.
|
||||
/// Derives a symmetric encryption key from the secret using x9.63 key
|
||||
/// derivation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hashFunction: The Hash Function to use for key derivation.
|
||||
/// - sharedInfo: The Shared Info to use for key derivation.
|
||||
/// - hashFunction: The hash function to use for key derivation.
|
||||
/// - sharedInfo: The shared information to use for key derivation.
|
||||
/// - outputByteCount: The length in bytes of resulting symmetric key.
|
||||
/// - Returns: The derived symmetric key
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public func x963DerivedSymmetricKey<H: HashFunction, SI: DataProtocol>(using hashFunction: H.Type, sharedInfo: SI, outputByteCount: Int) -> SymmetricKey {
|
||||
// SEC1 defines 3 inputs to the KDF:
|
||||
//
|
||||
@@ -99,14 +125,16 @@ public struct SharedSecret: ContiguousBytes {
|
||||
return SymmetricKey(data: key)
|
||||
}
|
||||
|
||||
/// Derives a symmetric encryption key using HKDF key derivation.
|
||||
/// Derives a symmetric encryption key from the secret using HKDF key
|
||||
/// derivation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hashFunction: The Hash Function to use for key derivation.
|
||||
/// - hashFunction: The hash function to use for key derivation.
|
||||
/// - salt: The salt to use for key derivation.
|
||||
/// - sharedInfo: The Shared Info to use for key derivation.
|
||||
/// - sharedInfo: The shared information to use for key derivation.
|
||||
/// - outputByteCount: The length in bytes of resulting symmetric key.
|
||||
/// - Returns: The derived symmetric key
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public func hkdfDerivedSymmetricKey<H: HashFunction, Salt: DataProtocol, SI: DataProtocol>(using hashFunction: H.Type, salt: Salt, sharedInfo: SI, outputByteCount: Int) -> SymmetricKey {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -128,6 +156,15 @@ extension SharedSecret: CustomStringConvertible, Equatable {
|
||||
return safeCompare(lhs, rhs)
|
||||
}
|
||||
|
||||
/// Determines whether a shared secret is equivalent to a collection of
|
||||
/// contiguous bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lhs: The shared secret to compare.
|
||||
/// - rhs: A collection of contiguous bytes to compare.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` if the shared secret and the
|
||||
/// collection of binary data are equivalent.
|
||||
public static func == <D: DataProtocol>(lhs: Self, rhs: D) -> Bool {
|
||||
if rhs.regions.count != 1 {
|
||||
let rhsContiguous = Data(rhs)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -33,30 +33,74 @@ import Foundation
|
||||
CURVES_FUNC = ["Signing", "KeyAgreement"]
|
||||
}%
|
||||
% for CURVE in NIST_CURVES:
|
||||
%{ DISPLAY_CURVE = CURVE[:1] + "-" + CURVE[1:] }%
|
||||
% for FUNC in CURVES_FUNC:
|
||||
// MARK: - ${CURVE} + ${FUNC}
|
||||
extension ${CURVE} {
|
||||
public enum ${FUNC} {
|
||||
|
||||
% if FUNC == "Signing":
|
||||
/// A mechanism used to create or verify a cryptographic signature using
|
||||
/// the NIST ${DISPLAY_CURVE} elliptic curve digital signature algorithm (ECDSA).
|
||||
% else:
|
||||
/// A mechanism used to create a shared secret between two users by
|
||||
/// performing NIST ${DISPLAY_CURVE} elliptic curve Diffie Hellman (ECDH) key
|
||||
/// exchange.
|
||||
% end
|
||||
public enum ${FUNC} {
|
||||
|
||||
% if FUNC == "Signing":
|
||||
%{ READABLE_FUNC = "signing" }%
|
||||
/// A ${DISPLAY_CURVE} public key used to verify cryptographic signatures.
|
||||
% else:
|
||||
%{ READABLE_FUNC = "key agreement" }%
|
||||
/// A ${DISPLAY_CURVE} public key used for key agreement.
|
||||
% end
|
||||
public struct PublicKey: NISTECPublicKey {
|
||||
var impl: NISTCurvePublicKeyImpl<${CURVE}>
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a collection of bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
impl = try NISTCurvePublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compact
|
||||
/// representation of the key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - compactRepresentation: A compact representation of the key
|
||||
/// as a collection of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compactRepresentation: Bytes) throws {
|
||||
impl = try NISTCurvePublicKeyImpl(compactRepresentation: compactRepresentation)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from an ANSI x9.63
|
||||
/// representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a compressed representation of
|
||||
/// the key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - compressedRepresentation: A compressed representation of the key as a collection
|
||||
/// of contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(compressedRepresentation: Bytes) throws {
|
||||
impl = try NISTCurvePublicKeyImpl(compressedRepresentation: compressedRepresentation)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Privacy-Enhanced Mail
|
||||
/// (PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
guard pem.type == "PUBLIC KEY" else {
|
||||
@@ -65,6 +109,11 @@ extension ${CURVE} {
|
||||
self = try .init(derRepresentation: pem.derBytes)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} public key for ${READABLE_FUNC} from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
let bytes = Array(derRepresentation)
|
||||
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
|
||||
@@ -75,12 +124,19 @@ extension ${CURVE} {
|
||||
self.impl = impl
|
||||
}
|
||||
|
||||
/// A compact representation of the public key.
|
||||
public var compactRepresentation: Data? { impl.compactRepresentation }
|
||||
|
||||
/// A full representation of the public key.
|
||||
public var rawRepresentation: Data { impl.rawRepresentation }
|
||||
|
||||
/// An ANSI x9.63 representation of the public key.
|
||||
public var x963Representation: Data { impl.x963Representation }
|
||||
|
||||
/// A compressed representation of the public key.
|
||||
public var compressedRepresentation: Data { impl.compressedRepresentation }
|
||||
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of the public key.
|
||||
public var derRepresentation: Data {
|
||||
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsa${CURVE}, key: Array(self.x963Representation))
|
||||
var serializer = ASN1.Serializer()
|
||||
@@ -90,27 +146,57 @@ extension ${CURVE} {
|
||||
return Data(serializer.serializedBytes)
|
||||
}
|
||||
|
||||
/// A Privacy-Enhanced Mail (PEM) representation of the public key.
|
||||
public var pemRepresentation: String {
|
||||
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
|
||||
return pemDocument.pemString
|
||||
}
|
||||
}
|
||||
|
||||
% if FUNC == "Signing":
|
||||
/// A ${DISPLAY_CURVE} private key used to create cryptographic signatures.
|
||||
% else:
|
||||
/// A ${DISPLAY_CURVE} private key used for key agreement.
|
||||
% end
|
||||
public struct PrivateKey: NISTECPrivateKey {
|
||||
let impl: NISTCurvePrivateKeyImpl<${CURVE}>
|
||||
|
||||
/// Creates a random ${DISPLAY_CURVE} private key for ${READABLE_FUNC}.
|
||||
///
|
||||
/// Keys that use a compact point encoding enable shorter public keys, but aren’t
|
||||
/// compliant with FIPS certification. If your app requires FIPS certification,
|
||||
/// create a key with ``init(rawRepresentation:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - compactRepresentable: A Boolean value that indicates whether CryptoKit
|
||||
/// creates the key with the structure to enable compact point encoding.
|
||||
public init(compactRepresentable: Bool = true) {
|
||||
impl = NISTCurvePrivateKeyImpl(compactRepresentable: compactRepresentable)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from an ANSI x9.63
|
||||
/// representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x963Representation: An ANSI x9.63 representation of the key.
|
||||
public init<Bytes: ContiguousBytes>(x963Representation: Bytes) throws {
|
||||
impl = try NISTCurvePrivateKeyImpl(x963: x963Representation)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a collection of bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a collection of
|
||||
/// contiguous bytes.
|
||||
public init<Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws {
|
||||
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Privacy-Enhanced Mail
|
||||
/// PEM) representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pemRepresentation: A PEM representation of the key.
|
||||
public init(pemRepresentation: String) throws {
|
||||
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
|
||||
|
||||
@@ -126,6 +212,11 @@ extension ${CURVE} {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a ${DISPLAY_CURVE} private key for ${READABLE_FUNC} from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: A DER-encoded representation of the key.
|
||||
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
|
||||
let bytes = Array(derRepresentation)
|
||||
|
||||
@@ -145,13 +236,18 @@ extension ${CURVE} {
|
||||
self.impl = impl
|
||||
}
|
||||
|
||||
/// The corresponding public key.
|
||||
public var publicKey: ${CURVE}.${FUNC}.PublicKey {
|
||||
return PublicKey(impl: impl.publicKey())
|
||||
}
|
||||
|
||||
/// A data representation of the private key.
|
||||
public var rawRepresentation: Data { impl.rawRepresentation }
|
||||
|
||||
/// An ANSI x9.63 representation of the private key.
|
||||
public var x963Representation: Data { impl.x963Representation }
|
||||
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of the private key.
|
||||
public var derRepresentation: Data {
|
||||
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsa${CURVE}, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
|
||||
var serializer = ASN1.Serializer()
|
||||
@@ -161,6 +257,7 @@ extension ${CURVE} {
|
||||
return Data(serializer.serializedBytes)
|
||||
}
|
||||
|
||||
/// A Privacy-Enhanced Mail (PEM) representation of the private key.
|
||||
public var pemRepresentation: String {
|
||||
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
|
||||
return pemDocument.pemString
|
||||
@@ -174,11 +271,12 @@ extension ${CURVE} {
|
||||
% for CURVE in NIST_CURVES:
|
||||
// MARK: - ${CURVE} + DH
|
||||
extension ${CURVE}.KeyAgreement.PrivateKey: DiffieHellmanKeyAgreement {
|
||||
/// Performs a key agreement with provided public key share.
|
||||
/// Computes a shared secret with the provided public key from another party.
|
||||
///
|
||||
/// - Parameter publicKeyShare: The public key to perform the ECDH with.
|
||||
/// - Returns: Returns a shared secret
|
||||
/// - Throws: An error occurred while computing the shared secret
|
||||
/// - Parameters:
|
||||
/// - publicKeyShare: The public key from another party to be combined with the private
|
||||
/// key from this user to create the shared secret.
|
||||
/// - Returns: The computed shared secret.
|
||||
public func sharedSecretFromKeyAgreement(with publicKeyShare: ${CURVE}.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return try self.coreCryptoSharedSecretFromKeyAgreement(with: publicKeyShare)
|
||||
|
||||
@@ -16,17 +16,33 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// The HMAC-based Extract-and-Expand Key Derivation Function (IETF RFC 5869)
|
||||
/// https://tools.ietf.org/html/rfc5869
|
||||
/// A standards-based implementation of an HMAC-based Key Derivation Function
|
||||
/// (HKDF).
|
||||
///
|
||||
/// The key derivation functions allow you to derive one or more secrets of the
|
||||
/// size of your choice from a main key or passcode. The key derivation function
|
||||
/// is compliant with IETF RFC 5869. Use one of the `deriveKey` functions, such
|
||||
/// as ``deriveKey(inputKeyMaterial:outputByteCount:)`` or
|
||||
/// ``deriveKey(inputKeyMaterial:salt:info:outputByteCount:)``, to derive a key
|
||||
/// from a main secret or passcode in a single function.
|
||||
///
|
||||
/// To derive a key with more fine-grained control, use
|
||||
/// ``extract(inputKeyMaterial:salt:)`` to create cryptographically strong key
|
||||
/// material in the form of a hashed authentication code, then call
|
||||
/// ``expand(pseudoRandomKey:info:outputByteCount:)`` using that key material to
|
||||
/// generate a symmetric key of the length you specify.
|
||||
public struct HKDF<H: HashFunction> {
|
||||
/// Derives a symmetric key using the HKDF algorithm.
|
||||
/// Derives a symmetric encryption key from a main key or passcode using
|
||||
/// HKDF key derivation with information and salt you specify.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputKeyMaterial: Input key material.
|
||||
/// - salt: A non-secret random value.
|
||||
/// - info: Context and application specific information.
|
||||
/// - outputByteCount: The desired number of output bytes.
|
||||
/// - Returns: The derived key
|
||||
/// - inputKeyMaterial: The main key or passcode the derivation function
|
||||
/// uses to derive a key.
|
||||
/// - salt: The salt to use for key derivation.
|
||||
/// - info: The shared information to use for key derivation.
|
||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public static func deriveKey<Salt: DataProtocol, Info: DataProtocol>(inputKeyMaterial: SymmetricKey,
|
||||
salt: Salt,
|
||||
info: Info,
|
||||
@@ -34,51 +50,66 @@ public struct HKDF<H: HashFunction> {
|
||||
return expand(pseudoRandomKey: extract(inputKeyMaterial: inputKeyMaterial, salt: salt), info: info, outputByteCount: outputByteCount)
|
||||
}
|
||||
|
||||
/// Derives a symmetric key using the HKDF algorithm.
|
||||
/// Derives a symmetric encryption key from a main key or passcode using
|
||||
/// HKDF key derivation with information you specify.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputKeyMaterial: Input key material.
|
||||
/// - info: Context and application specific information.
|
||||
/// - outputByteCount: The desired number of output bytes.
|
||||
/// - Returns: The derived key
|
||||
/// - inputKeyMaterial: The main key or passcode the derivation function
|
||||
/// uses to derive a key.
|
||||
/// - info: The shared information to use for key derivation.
|
||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public static func deriveKey<Info: DataProtocol>(inputKeyMaterial: SymmetricKey,
|
||||
info: Info,
|
||||
outputByteCount: Int) -> SymmetricKey {
|
||||
return deriveKey(inputKeyMaterial: inputKeyMaterial, salt: [UInt8](), info: info, outputByteCount: outputByteCount)
|
||||
}
|
||||
|
||||
/// Derives a symmetric key using the HKDF algorithm.
|
||||
/// Derives a symmetric encryption key from a main key or passcode using
|
||||
/// HKDF key derivation with salt that you specify.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputKeyMaterial: Input key material.
|
||||
/// - salt: A non-secret random value.
|
||||
/// - outputByteCount: The desired number of output bytes.
|
||||
/// - Returns: The derived key
|
||||
/// - inputKeyMaterial: The main key or passcode the derivation function
|
||||
/// uses to derive a key.
|
||||
/// - salt: The salt to use for key derivation.
|
||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public static func deriveKey<Salt: DataProtocol>(inputKeyMaterial: SymmetricKey,
|
||||
salt: Salt,
|
||||
outputByteCount: Int) -> SymmetricKey {
|
||||
return deriveKey(inputKeyMaterial: inputKeyMaterial, salt: salt, info: [UInt8](), outputByteCount: outputByteCount)
|
||||
}
|
||||
|
||||
/// Derives a symmetric key using the HKDF algorithm.
|
||||
/// Derives a symmetric encryption key from a main key or passcode using
|
||||
/// HKDF key derivation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputKeyMaterial: Input key material.
|
||||
/// - outputByteCount: The desired number of output bytes.
|
||||
/// - Returns: The derived key
|
||||
/// - inputKeyMaterial: The main key or passcode the derivation function
|
||||
/// uses to derive a key.
|
||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public static func deriveKey(inputKeyMaterial: SymmetricKey,
|
||||
outputByteCount: Int) -> SymmetricKey {
|
||||
return deriveKey(inputKeyMaterial: inputKeyMaterial, salt: [UInt8](), info: [UInt8](), outputByteCount: outputByteCount)
|
||||
}
|
||||
|
||||
/// The extract function as defined by specification.
|
||||
/// The goal of the extract function is to "concentrate" the possibly dispersed entropy of the input keying material into a short, but cryptographically strong, pseudorandom key.
|
||||
/// Unless required by a specification, it is recommended to use the one-shot "deriveKey" API instead that performs both extraction and expansion.
|
||||
/// Creates cryptographically strong key material from a main key or
|
||||
/// passcode that you specify.
|
||||
///
|
||||
/// Generate a derived symmetric key from the cryptographically strong key
|
||||
/// material this function creates by calling
|
||||
/// ``expand(pseudoRandomKey:info:outputByteCount:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputKeyMaterial: Input key material.
|
||||
/// - salt: A non-secret random value.
|
||||
/// - Returns: The resulting secret
|
||||
/// - inputKeyMaterial: The main key or passcode the derivation function
|
||||
/// uses to derive a key.
|
||||
/// - salt: The salt to use for key derivation.
|
||||
///
|
||||
/// - Returns: A pseudorandom, cryptographically strong key in the form of a
|
||||
/// hashed authentication code.
|
||||
public static func extract<Salt: DataProtocol>(inputKeyMaterial: SymmetricKey, salt: Salt?) -> HashedAuthenticationCode<H> {
|
||||
let key: SymmetricKey
|
||||
if let salt = salt {
|
||||
@@ -97,15 +128,19 @@ public struct HKDF<H: HashFunction> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The expand function as defined by the specification.
|
||||
/// The goal of the expand function is to expand the pseudorandom key to the desired length.
|
||||
/// Unless required by a specification, it is recommended to use the one-shot "deriveKey" API instead that performs both extraction and expansion.
|
||||
/// Expands cryptographically strong key material into a derived symmetric
|
||||
/// key.
|
||||
///
|
||||
/// Generate cryptographically strong key material to use with this function
|
||||
/// by calling ``extract(inputKeyMaterial:salt:)``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pseudoRandomKey: The extracted pseudorandom key. This value is expected to be a high-entropy secret. In the HKDF specification it is obtained from the input key material and the salt using the extract method.
|
||||
/// - info: Context and application specific information.
|
||||
/// - outputByteCount: The desired number of output bytes.
|
||||
/// - Returns: The expanded key bytes.
|
||||
/// - prk: A pseudorandom, cryptographically strong key generated from the
|
||||
/// ``extract(inputKeyMaterial:salt:)`` function.
|
||||
/// - info: The shared information to use for key derivation.
|
||||
/// - outputByteCount: The length in bytes of the resulting symmetric key.
|
||||
///
|
||||
/// - Returns: The derived symmetric key.
|
||||
public static func expand<PRK: ContiguousBytes, Info: DataProtocol>(pseudoRandomKey prk: PRK, info: Info?, outputByteCount: Int) -> SymmetricKey {
|
||||
let iterations: UInt8 = UInt8(ceil((Float(outputByteCount) / Float(H.Digest.byteCount))))
|
||||
var output = SecureBytes()
|
||||
|
||||
@@ -23,24 +23,34 @@ typealias AESWRAPImpl = BoringSSLAESWRAPImpl
|
||||
#endif
|
||||
|
||||
extension AES {
|
||||
/// The Key Wrapping module provides AES Key Wrapping, according to the IETF RFC 3394 specification.
|
||||
/// An implementation of AES Key Wrapping in accordance with the IETF RFC
|
||||
/// 3394 specification.
|
||||
public enum KeyWrap {
|
||||
/// Wraps a key with AES wrap (RFC 3394), according to the IETF RFC 3394 specification.
|
||||
/// Wraps a key using the AES wrap algorithm.
|
||||
///
|
||||
/// Wrap is an implementation of the AES key wrap algorithm as specified
|
||||
/// in IETF RFC 3394.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyToWrap: The key to wrap
|
||||
/// - kek: The Key Encryption Key
|
||||
/// - Returns: The wrapped key
|
||||
/// - keyToWrap: The key to wrap.
|
||||
/// - kek: The key encryption key.
|
||||
///
|
||||
/// - Returns: The wrapped key.
|
||||
public static func wrap(_ keyToWrap: SymmetricKey, using kek: SymmetricKey) throws -> Data {
|
||||
return try AESWRAPImpl.wrap(key: kek, keyToWrap: keyToWrap)
|
||||
}
|
||||
|
||||
/// Unwraps a key with AES wrap, according to the IETF RFC 3394 specification.
|
||||
/// Unwraps a key using the AES wrap algorithm.
|
||||
///
|
||||
/// Wrap is an implementation of the AES key wrap algorithm as specified
|
||||
/// in IETF RFC 3394. The method throws an error is the key was
|
||||
/// incorrectly wrapped.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - wrappedKey: The wrapped key
|
||||
/// - kek: The key encryption key
|
||||
/// - Returns: The unwrapped key, the method will throw if the payload was incorrectly wrapped.
|
||||
/// - wrappedKey: The key to unwrap.
|
||||
/// - kek: The key encryption key.
|
||||
///
|
||||
/// - Returns: The unwrapped key.
|
||||
public static func unwrap<WrappedKey: DataProtocol>(_ wrappedKey: WrappedKey, using kek: SymmetricKey) throws -> SymmetricKey {
|
||||
return try AESWRAPImpl.unwrap(key: kek, wrappedKey: wrappedKey)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,6 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// The Curve25519 Elliptic Curve.
|
||||
/// An elliptic curve that enables X25519 key agreement and Ed25519 signatures.
|
||||
public enum Curve25519 {}
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -16,8 +16,15 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension Curve25519.Signing {
|
||||
static var keyByteCount: Int {
|
||||
return 32
|
||||
}
|
||||
}
|
||||
|
||||
extension Curve25519 {
|
||||
/// Signing operations on Curve25519
|
||||
/// A mechanism used to create or verify a cryptographic signature using
|
||||
/// Ed25519.
|
||||
public enum Signing {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
typealias Curve25519PrivateKeyImpl = Curve25519.Signing.CoreCryptoCurve25519PrivateKeyImpl
|
||||
@@ -27,27 +34,32 @@ extension Curve25519 {
|
||||
typealias Curve25519PublicKeyImpl = Curve25519.Signing.OpenSSLCurve25519PublicKeyImpl
|
||||
#endif
|
||||
|
||||
/// A Private Key for signing
|
||||
/// A Curve25519 private key used to create cryptographic signatures.
|
||||
public struct PrivateKey: ECPrivateKey {
|
||||
private var baseKey: Curve25519.Signing.Curve25519PrivateKeyImpl
|
||||
|
||||
/// Generates a Curve25519 Signing Key.
|
||||
/// Creates a random Curve25519 private key for signing.
|
||||
public init() {
|
||||
self.baseKey = Curve25519.Signing.Curve25519PrivateKeyImpl()
|
||||
}
|
||||
|
||||
/// The associated public key for verifying signatures done with this private key.
|
||||
///
|
||||
/// - Returns: The associated public key
|
||||
/// The corresponding public key.
|
||||
public var publicKey: PublicKey {
|
||||
return PublicKey(baseKey: self.baseKey.publicKey)
|
||||
}
|
||||
|
||||
/// Creates a Curve25519 private key for signing from a data
|
||||
/// representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: A representation of the key as contiguous bytes from
|
||||
/// which to create the key.
|
||||
public init<D: ContiguousBytes>(rawRepresentation data: D) throws {
|
||||
self.baseKey = try Curve25519.Signing.Curve25519PrivateKeyImpl(rawRepresentation: data)
|
||||
}
|
||||
|
||||
/// A data representation of the private key
|
||||
/// The raw representation of the key as a collection of contiguous
|
||||
/// bytes.
|
||||
public var rawRepresentation: Data {
|
||||
return self.baseKey.rawRepresentation
|
||||
}
|
||||
@@ -57,9 +69,15 @@ extension Curve25519 {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Curve25519 public key used to verify cryptographic signatures.
|
||||
public struct PublicKey {
|
||||
private var baseKey: Curve25519.Signing.Curve25519PublicKeyImpl
|
||||
|
||||
/// Creates a Curve25519 public key from a data representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A representation of the key as contiguous
|
||||
/// bytes from which to create the key.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
self.baseKey = try Curve25519.Signing.Curve25519PublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
@@ -68,6 +86,7 @@ extension Curve25519 {
|
||||
self.baseKey = baseKey
|
||||
}
|
||||
|
||||
/// A representation of the public key.
|
||||
public var rawRepresentation: Data {
|
||||
return self.baseKey.rawRepresentation
|
||||
}
|
||||
@@ -28,8 +28,8 @@ protocol ECPublicKey {
|
||||
}
|
||||
|
||||
protocol ECPrivateKey {
|
||||
associatedtype PublicKey
|
||||
var publicKey: PublicKey { get }
|
||||
associatedtype PK
|
||||
var publicKey: PK { get }
|
||||
}
|
||||
|
||||
protocol NISTECPublicKey: ECPublicKey {
|
||||
@@ -41,17 +41,17 @@ protocol NISTECPublicKey: ECPublicKey {
|
||||
var x963Representation: Data { get }
|
||||
}
|
||||
|
||||
protocol NISTECPrivateKey: ECPrivateKey where PublicKey: NISTECPublicKey {
|
||||
protocol NISTECPrivateKey: ECPrivateKey where PK: NISTECPublicKey {
|
||||
init <Bytes: ContiguousBytes>(rawRepresentation: Bytes) throws
|
||||
var rawRepresentation: Data { get }
|
||||
}
|
||||
|
||||
/// The NIST P-256 Elliptic Curve.
|
||||
/// An elliptic curve that enables NIST P-256 signatures and key agreement.
|
||||
public enum P256 { }
|
||||
|
||||
/// The NIST P-384 Elliptic Curve.
|
||||
/// An elliptic curve that enables NIST P-384 signatures and key agreement.
|
||||
public enum P384 { }
|
||||
|
||||
/// The NIST P-521 Elliptic Curve.
|
||||
/// An elliptic curve that enables NIST P-521 signatures and key agreement.
|
||||
public enum P521 { }
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -16,7 +16,15 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
extension Curve25519.KeyAgreement {
|
||||
static var keyByteCount: Int {
|
||||
return 32
|
||||
}
|
||||
}
|
||||
|
||||
extension Curve25519 {
|
||||
/// A mechanism used to create a shared secret between two users by
|
||||
/// performing X25519 key agreement.
|
||||
public enum KeyAgreement {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
typealias Curve25519PrivateKeyImpl = Curve25519.KeyAgreement.CoreCryptoCurve25519PrivateKeyImpl
|
||||
@@ -26,14 +34,16 @@ extension Curve25519 {
|
||||
typealias Curve25519PublicKeyImpl = Curve25519.KeyAgreement.OpenSSLCurve25519PublicKeyImpl
|
||||
#endif
|
||||
|
||||
/// A Curve25519 public key used for key agreement.
|
||||
public struct PublicKey: ECPublicKey {
|
||||
fileprivate var baseKey: Curve25519PublicKeyImpl
|
||||
|
||||
/// Initializes a Curve25519 Key for Key Agreement.
|
||||
/// Creates a Curve25519 public key for key agreement from a
|
||||
/// collection of bytes.
|
||||
///
|
||||
/// - Parameter rawRepresentation: The data representation of the key
|
||||
/// - Returns: An initialized key if the data is valid.
|
||||
/// - Throws: Throws if the data is not a valid key.
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a
|
||||
/// collection of contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
self.baseKey = try Curve25519PublicKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
@@ -42,7 +52,8 @@ extension Curve25519 {
|
||||
self.baseKey = baseKey
|
||||
}
|
||||
|
||||
/// A data representation of the public key
|
||||
/// A representation of the Curve25519 public key as a collection of
|
||||
/// bytes.
|
||||
public var rawRepresentation: Data {
|
||||
return self.baseKey.rawRepresentation
|
||||
}
|
||||
@@ -56,38 +67,45 @@ extension Curve25519 {
|
||||
}
|
||||
}
|
||||
|
||||
public struct PrivateKey: ECPrivateKey, DiffieHellmanKeyAgreement {
|
||||
/// A Curve25519 private key used for key agreement.
|
||||
public struct PrivateKey: DiffieHellmanKeyAgreement {
|
||||
fileprivate var baseKey: Curve25519PrivateKeyImpl
|
||||
|
||||
/// Generates a new X25519 private key.
|
||||
/// Creates a random Curve25519 private key for key agreement.
|
||||
public init() {
|
||||
self.baseKey = Curve25519PrivateKeyImpl()
|
||||
}
|
||||
|
||||
/// Returns the associated X25519 public key.
|
||||
///
|
||||
/// - Returns: The public key
|
||||
public var publicKey: PublicKey {
|
||||
/// The corresponding public key.
|
||||
public var publicKey: Curve25519.KeyAgreement.PublicKey {
|
||||
return PublicKey(baseKey: self.baseKey.publicKey)
|
||||
}
|
||||
|
||||
/// Initializes the key with data.
|
||||
/// Creates a Curve25519 private key for key agreement from a
|
||||
/// collection of bytes.
|
||||
///
|
||||
/// - Parameter data: The 32-bytes representation of the private key.
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the key as a
|
||||
/// collection of contiguous bytes.
|
||||
public init<D: ContiguousBytes>(rawRepresentation: D) throws {
|
||||
self.baseKey = try Curve25519PrivateKeyImpl(rawRepresentation: rawRepresentation)
|
||||
}
|
||||
|
||||
/// Performs an elliptic curve Diffie-Hellmann key agreement over X25519.
|
||||
/// Computes a shared secret with the provided public key from
|
||||
/// another party.
|
||||
///
|
||||
/// - Parameter publicKeyShare: The public key share to perform the key agreement with.
|
||||
/// - Returns: The shared secret
|
||||
/// - Throws: Throws if the operation failed to be performed.
|
||||
public func sharedSecretFromKeyAgreement(with publicKeyShare: PublicKey) throws -> SharedSecret {
|
||||
/// - Parameters:
|
||||
/// - publicKeyShare: The public key from another party to be
|
||||
/// combined with the private key from this user to create the
|
||||
/// shared secret.
|
||||
///
|
||||
/// - Returns: The computed shared secret.
|
||||
public func sharedSecretFromKeyAgreement(with publicKeyShare: Curve25519.KeyAgreement.PublicKey) throws -> SharedSecret {
|
||||
return try self.baseKey.sharedSecretFromKeyAgreement(with: publicKeyShare.baseKey)
|
||||
}
|
||||
|
||||
/// A data representation of the private key
|
||||
/// The raw representation of the key as a collection of contiguous
|
||||
/// bytes.
|
||||
public var rawRepresentation: Data {
|
||||
return self.baseKey.rawRepresentation
|
||||
}
|
||||
|
||||
@@ -16,51 +16,83 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// The size of a symmetric key
|
||||
/// The sizes that a symmetric cryptographic key can take.
|
||||
///
|
||||
/// When creating a new ``SymmetricKey`` instance with a call to its
|
||||
/// ``SymmetricKey/init(size:)`` initializer, you typically use one of the
|
||||
/// standard key sizes, like ``bits128``, ``bits192``, or ``bits256``. When you
|
||||
/// need a key with a non-standard length, use the ``init(bitCount:)``
|
||||
/// initializer to create a `SymmetricKeySize` instance with a custom bit count.
|
||||
public struct SymmetricKeySize {
|
||||
/// The number of bits in the key.
|
||||
public let bitCount: Int
|
||||
|
||||
/// Symmetric key size of 128 bits
|
||||
/// A size of 128 bits.
|
||||
public static var bits128: SymmetricKeySize {
|
||||
return self.init(bitCount: 128)
|
||||
}
|
||||
|
||||
/// Symmetric key size of 192 bits
|
||||
/// A size of 192 bits.
|
||||
public static var bits192: SymmetricKeySize {
|
||||
return self.init(bitCount: 192)
|
||||
}
|
||||
|
||||
/// Symmetric key size of 256 bits
|
||||
/// A size of 256 bits.
|
||||
public static var bits256: SymmetricKeySize {
|
||||
return self.init(bitCount: 256)
|
||||
}
|
||||
|
||||
/// Symmetric key size with a custom number of bits.
|
||||
/// Creates a new key size of the given length.
|
||||
///
|
||||
/// Params:
|
||||
/// - bitsCount: Positive integer that is a multiple of 8.
|
||||
/// In most cases, you can use one of the standard key sizes, like bits256.
|
||||
/// If instead you need a key with a non-standard size, use the
|
||||
/// ``init(bitCount:)`` initializer to create a custom key size.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bitCount: The number of bits in the key size.
|
||||
public init(bitCount: Int) {
|
||||
precondition(bitCount > 0 && bitCount % 8 == 0)
|
||||
self.bitCount = bitCount
|
||||
}
|
||||
}
|
||||
|
||||
/// A symmetric key for use with software implementations of cryptographic algorithms.
|
||||
/// A symmetric cryptographic key.
|
||||
///
|
||||
/// You typically derive a symmetric key from an instance of a shared secret
|
||||
/// (``SharedSecret``) that you obtain through key agreement. You use a
|
||||
/// symmetric key to compute a message authentication code like ``HMAC``, or to
|
||||
/// open and close a sealed box (``ChaChaPoly/SealedBox`` or
|
||||
/// ``AES/GCM/SealedBox``) using a cipher like ``ChaChaPoly`` or ``AES``.
|
||||
public struct SymmetricKey: ContiguousBytes {
|
||||
let sb: SecureBytes
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes
|
||||
/// of the key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the
|
||||
/// key and returns the key.
|
||||
///
|
||||
/// - Returns: The key, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try sb.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
/// Initializes a key with data
|
||||
/// Creates a key from the given data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: The contiguous bytes from which to create the key.
|
||||
public init<D: ContiguousBytes>(data: D) {
|
||||
self.init(key: SecureBytes(bytes: data))
|
||||
}
|
||||
|
||||
/// Generates a key of the provided key size
|
||||
/// Generates a new random key of the given size.
|
||||
///
|
||||
/// - Parameter size: The key size
|
||||
/// - Parameters:
|
||||
/// - size: The size of the key to generate. You can use one of the standard
|
||||
/// sizes, like ``SymmetricKeySize/bits256``, or you can create a key of
|
||||
/// custom length by initializing a ``SymmetricKeySize`` instance with a
|
||||
/// non-standard value.
|
||||
public init(size: SymmetricKeySize) {
|
||||
self.init(key: SecureBytes(count: Int(size.bitCount / 8)))
|
||||
}
|
||||
@@ -74,7 +106,7 @@ public struct SymmetricKey: ContiguousBytes {
|
||||
self.init(key: data)
|
||||
}
|
||||
|
||||
/// The key size in bits
|
||||
/// The number of bits in the key.
|
||||
public var bitCount: Int {
|
||||
return self.byteCount * 8
|
||||
}
|
||||
|
||||
@@ -16,28 +16,46 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// Performs HMAC - Keyed-Hashing for Message Authentication
|
||||
/// Reference: https://tools.ietf.org/html/rfc2104
|
||||
/// A hash-based message authentication algorithm.
|
||||
///
|
||||
/// Use hash-based message authentication to create a code with a value that’s
|
||||
/// dependent on both a block of data and a symmetric cryptographic key. Another
|
||||
/// party with access to the data and the same secret key can compute the code
|
||||
/// again and compare it to the original to detect whether the data changed.
|
||||
/// This serves a purpose similar to digital signing and verification, but
|
||||
/// depends on a shared symmetric key instead of public-key cryptography.
|
||||
///
|
||||
/// As with digital signing, the data isn’t hidden by this process. When you
|
||||
/// need to encrypt the data as well as authenticate it, use a cipher like
|
||||
/// ``AES`` or ``ChaChaPoly`` to put the data into a sealed box (an instance of
|
||||
/// ``AES/GCM/SealedBox`` or ``ChaChaPoly/SealedBox``).
|
||||
public struct HMAC<H: HashFunction>: MACAlgorithm {
|
||||
/// An alias for the symmetric key type used to compute or verify a message
|
||||
/// authentication code.
|
||||
public typealias Key = SymmetricKey
|
||||
/// An alias for a hash-based message authentication code.
|
||||
public typealias MAC = HashedAuthenticationCode<H>
|
||||
var outerHasher: H
|
||||
var innerHasher: H
|
||||
|
||||
/// Verifies a tag of a Message Authentication Code. The comparison is done in constant-time.
|
||||
/// Returns a Boolean value indicating whether the given message
|
||||
/// authentication code is valid for a block of data stored in a buffer.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - key: The key used to authenticate the data
|
||||
/// - data: The data to authenticate
|
||||
/// - mac: The MAC to verify
|
||||
/// - Returns: Returns true if the MAC is valid. False otherwise.
|
||||
/// - mac: The authentication code to compare.
|
||||
/// - bufferPointer: A pointer to the block of data to compare.
|
||||
/// - key: The symmetric key for the authentication code.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||||
/// code is valid for the data within the specified buffer.
|
||||
public static func isValidAuthenticationCode(_ mac: MAC, authenticating bufferPointer: UnsafeRawBufferPointer, using key: SymmetricKey) -> Bool {
|
||||
return isValidAuthenticationCode(authenticationCodeBytes: mac, authenticatedData: bufferPointer, key: key)
|
||||
}
|
||||
|
||||
/// Initializes an incremental HMAC
|
||||
/// Creates a message authentication code generator.
|
||||
///
|
||||
/// - Parameter key: The key to use for HMAC.
|
||||
/// - Parameters:
|
||||
/// - key: The symmetric key used to secure the computation.
|
||||
public init(key: SymmetricKey) {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -81,45 +99,55 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Computes a Message Authentication Code.
|
||||
/// Computes a message authentication code for the given data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - key: The key used to authenticate the data
|
||||
/// - data: The data to authenticate
|
||||
/// - Returns: A Message Authentication Code
|
||||
/// - data: The data for which to compute the authentication code.
|
||||
/// - key: The symmetric key used to secure the computation.
|
||||
///
|
||||
/// - Returns: The message authentication code.
|
||||
public static func authenticationCode<D: DataProtocol>(for data: D, using key: SymmetricKey) -> MAC {
|
||||
var authenticator = Self(key: key)
|
||||
authenticator.update(data: data)
|
||||
return authenticator.finalize()
|
||||
}
|
||||
|
||||
/// Verifies a Message Authentication Code. The comparison is done in constant-time.
|
||||
/// Returns a Boolean value indicating whether the given message
|
||||
/// authentication code is valid for a block of data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - authenticationCode: The authentication code
|
||||
/// - authenticatedData: Authenticated Data
|
||||
/// - key: The key to authenticate the data with
|
||||
/// - Returns: Returns true if the MAC is valid. False otherwise.
|
||||
/// - authenticationCode: The authentication code to compare.
|
||||
/// - authenticatedData: The block of data to compare.
|
||||
/// - key: The symmetric key for the authentication code.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||||
/// code is valid for the specified block of data.
|
||||
public static func isValidAuthenticationCode<D: DataProtocol>(_ authenticationCode: MAC, authenticating authenticatedData: D, using key: SymmetricKey) -> Bool {
|
||||
return isValidAuthenticationCode(authenticationCodeBytes: authenticationCode, authenticatedData: authenticatedData, key: key)
|
||||
}
|
||||
|
||||
/// Verifies a Message Authentication Code. The comparison is done in constant-time.
|
||||
/// Returns a Boolean value indicating whether the given message
|
||||
/// authentication code represented as contiguous bytes is valid for a block
|
||||
/// of data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - authenticationCode: The authentication code
|
||||
/// - authenticatedData: Authenticated Data
|
||||
/// - key: The key to authenticate the data with
|
||||
/// - Returns: Returns true if the MAC is valid. False otherwise.
|
||||
/// - authenticationCode: The authentication code to compare.
|
||||
/// - authenticatedData: The block of data to compare.
|
||||
/// - key: The symmetric key for the authentication code.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||||
/// code is valid for the specified block of data.
|
||||
public static func isValidAuthenticationCode<C: ContiguousBytes, D: DataProtocol>(_ authenticationCode: C,
|
||||
authenticating authenticatedData: D,
|
||||
using key: SymmetricKey) -> Bool {
|
||||
return isValidAuthenticationCode(authenticationCodeBytes: authenticationCode, authenticatedData: authenticatedData, key: key)
|
||||
}
|
||||
|
||||
/// Updates the MAC with data.
|
||||
/// Updates the message authentication code computation with a block of
|
||||
/// data.
|
||||
///
|
||||
/// - Parameter data: The data to update the MAC
|
||||
/// - Parameters:
|
||||
/// - data: The data for which to compute the authentication code.
|
||||
public mutating func update<D: DataProtocol>(data: D) {
|
||||
data.regions.forEach { (memoryRegion) in
|
||||
memoryRegion.withUnsafeBytes({ (bp) in
|
||||
@@ -128,10 +156,10 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the Message Authentication Code (MAC) from the data inputted into the MAC.
|
||||
/// Finalizes the message authentication computation and returns the
|
||||
/// computed code.
|
||||
///
|
||||
/// - Returns: The Message Authentication Code
|
||||
/// - Throws: Throws if the MAC has already been finalized
|
||||
/// - Returns: The message authentication code.
|
||||
public func finalize() -> MAC {
|
||||
let innerHash = innerHasher.finalize()
|
||||
var outerHashForFinalization = outerHasher
|
||||
@@ -146,8 +174,9 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
|
||||
|
||||
/// Adds data to be authenticated by MAC function. This can be called one or more times to append additional data.
|
||||
///
|
||||
/// - Parameter data: The data to be authenticated
|
||||
/// - Throws: Throws if the HMAC has already been finalized
|
||||
/// - Parameters:
|
||||
/// - data: The data to be authenticated.
|
||||
/// - Throws: Throws if the HMAC has already been finalized.
|
||||
mutating func update(bufferPointer: UnsafeRawBufferPointer) {
|
||||
innerHasher.update(bufferPointer: bufferPointer)
|
||||
}
|
||||
@@ -163,18 +192,28 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
|
||||
}
|
||||
}
|
||||
|
||||
/// A structure that contains a Message Authentication Code that was computed from a Hash Function using HMAC.
|
||||
/// A hash-based message authentication code.
|
||||
public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCode {
|
||||
let digest: H.Digest
|
||||
|
||||
/// The number of bytes in the message authentication code.
|
||||
public var byteCount: Int {
|
||||
return H.Digest.byteCount
|
||||
}
|
||||
|
||||
/// A human-readable description of the code.
|
||||
public var description: String {
|
||||
return "HMAC with \(H.self): \(Array(digest).hexString)"
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw bytes
|
||||
/// of the code.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: A closure that takes a raw buffer pointer to the bytes of the
|
||||
/// code and returns the code.
|
||||
///
|
||||
/// - Returns: The code, as returned from the body closure.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
return try digest.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
@@ -16,16 +16,35 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
/// A protocol defining requirements for Message Authentication Codes
|
||||
/// A type that represents a message authentication code.
|
||||
public protocol MessageAuthenticationCode: Hashable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
|
||||
/// The number of bytes in the message authentication code.
|
||||
var byteCount: Int { get }
|
||||
}
|
||||
|
||||
extension MessageAuthenticationCode {
|
||||
/// Returns a Boolean value indicating whether two message authentication
|
||||
/// codes are equal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lhs: The first message authentication code to compare.
|
||||
/// - rhs: The second message authentication code to compare.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||||
/// codes are equivalent.
|
||||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
return safeCompare(lhs, rhs)
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether a message authentication code
|
||||
/// is equivalent to a collection of binary data.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lhs: A message authentication code to compare.
|
||||
/// - rhs: A collection of binary data to compare.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` if the message authentication
|
||||
/// code and the collection of binary data are equivalent.
|
||||
public static func == <D: DataProtocol>(lhs: Self, rhs: D) -> Bool {
|
||||
if rhs.regions.count != 1 {
|
||||
let rhsContiguous = Data(rhs)
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@_exported import CryptoKit
|
||||
#else
|
||||
/// The Advanced Encryption Standard (AES)
|
||||
/// A container for Advanced Encryption Standard (AES) ciphers.
|
||||
public enum AES {
|
||||
static let blockSizeByteCount = 16
|
||||
}
|
||||
|
||||
@@ -21,11 +21,11 @@ import Foundation
|
||||
extension Curve25519.Signing.PublicKey {
|
||||
// We do this to enable inlinability on these methods.
|
||||
@usableFromInline
|
||||
static let signatureLength = Curve25519.Signing.signatureLength
|
||||
static let signatureByteCount = Curve25519.Signing.signatureByteCount
|
||||
|
||||
@inlinable
|
||||
func openSSLIsValidSignature<S: DataProtocol, D: DataProtocol>(_ signature: S, for data: D) -> Bool {
|
||||
if signature.count != Curve25519.Signing.PublicKey.signatureLength {
|
||||
if signature.count != Curve25519.Signing.PublicKey.signatureByteCount {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ 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 {
|
||||
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureLength)
|
||||
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,
|
||||
@@ -90,11 +90,11 @@ extension Curve25519.Signing.PrivateKey {
|
||||
|
||||
@usableFromInline
|
||||
func openSSLSignature(forDataPointer dataPointer: UnsafeRawBufferPointer) throws -> Data {
|
||||
var signature = Data(repeating: 0, count: Curve25519.Signing.PublicKey.signatureLength)
|
||||
var signature = Data(repeating: 0, count: Curve25519.Signing.PublicKey.signatureByteCount)
|
||||
|
||||
let rc: CInt = signature.withUnsafeMutableBytes { signaturePointer in
|
||||
self.key.withUnsafeBytes { keyPointer in
|
||||
precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureLength)
|
||||
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)
|
||||
|
||||
@@ -33,16 +33,19 @@ protocol NISTSigning {
|
||||
}
|
||||
|
||||
// MARK: - P256 + Signing
|
||||
/// An ECDSA (Elliptic Curve Digital Signature Algorithm) Signature
|
||||
extension P256.Signing {
|
||||
|
||||
/// A P-256 elliptic curve digital signature algorithm (ECDSA) signature.
|
||||
public struct ECDSASignature: ContiguousBytes, NISTECDSASignature {
|
||||
/// Returns the raw signature.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
|
||||
/// A raw data representation of a P-256 digital signature.
|
||||
public var rawRepresentation: Data
|
||||
|
||||
/// Initializes ECDSASignature from the raw representation.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
/// As defined in https://tools.ietf.org/html/rfc4754
|
||||
/// Creates a P-256 digital signature from a raw representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the signature as a
|
||||
/// collection of contiguous bytes.
|
||||
public init<D: DataProtocol>(rawRepresentation: D) throws {
|
||||
guard rawRepresentation.count == 2 * P256.coordinateByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
@@ -66,7 +69,12 @@ extension P256.Signing {
|
||||
return (combined.prefix(upTo: half), combined.suffix(from: half))
|
||||
}
|
||||
|
||||
/// Initializes ECDSASignature from the DER representation.
|
||||
/// Creates a P-256 digital signature from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: The DER-encoded representation of the
|
||||
/// signature.
|
||||
public init<D: DataProtocol>(derRepresentation: D) throws {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -93,11 +101,14 @@ extension P256.Signing {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw
|
||||
/// bytes of the signature.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
try self.rawRepresentation.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
/// A DER-encoded representation of the signature
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of a
|
||||
/// P-256 digital signature.
|
||||
public var derRepresentation: Data {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -120,11 +131,14 @@ extension P256.Signing: NISTSigning {}
|
||||
|
||||
// MARK: - P256 + PrivateKey
|
||||
extension P256.Signing.PrivateKey: DigestSigner {
|
||||
/// Generates an ECDSA signature over the P256 elliptic curve.
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the digest you provide over the P-256 elliptic curve.
|
||||
///
|
||||
/// - Parameter digest: The digest to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature
|
||||
/// - Parameters:
|
||||
/// - digest: The digest of the data to sign.
|
||||
/// - Returns: The signature corresponding to the digest. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: Digest>(for digest: D) throws -> P256.Signing.ECDSASignature {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return try self.coreCryptoSignature(for: digest)
|
||||
@@ -134,24 +148,30 @@ extension P256.Signing.PrivateKey: DigestSigner {
|
||||
}
|
||||
}
|
||||
|
||||
extension P256.Signing.PrivateKey: Signer {
|
||||
/// Generates an ECDSA signature over the P256 elliptic curve.
|
||||
/// SHA256 is used as the hash function.
|
||||
extension P256.Signing.PrivateKey: Signer {
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the data you provide over the P-256 elliptic curve,
|
||||
/// using SHA-256 as the hash function.
|
||||
///
|
||||
/// - Parameter data: The data to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature.
|
||||
/// - Parameters:
|
||||
/// - data: The data to sign.
|
||||
/// - Returns: The signature corresponding to the data. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: DataProtocol>(for data: D) throws -> P256.Signing.ECDSASignature {
|
||||
return try self.signature(for: SHA256.hash(data: data))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension P256.Signing.PublicKey: DigestValidator {
|
||||
/// Verifies an ECDSA signature over the P256 elliptic curve.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a digest over the P-256 elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - digest: The digest that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - digest: The signed digest.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given digest; otherwise, `false`.
|
||||
public func isValidSignature<D: Digest>(_ signature: P256.Signing.ECDSASignature, for digest: D) -> Bool {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return self.coreCryptoIsValidSignature(signature, for: digest)
|
||||
@@ -162,29 +182,33 @@ extension P256.Signing.PublicKey: DigestValidator {
|
||||
}
|
||||
|
||||
extension P256.Signing.PublicKey: DataValidator {
|
||||
/// Verifies an ECDSA signature over the P256 elliptic curve.
|
||||
/// SHA256 is used as the hash function.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a block of data over the P-256 elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - data: The data that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - data: The signed data.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given data; otherwise, `false`.
|
||||
public func isValidSignature<D: DataProtocol>(_ signature: P256.Signing.ECDSASignature, for data: D) -> Bool {
|
||||
return self.isValidSignature(signature, for: SHA256.hash(data: data))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - P384 + Signing
|
||||
/// An ECDSA (Elliptic Curve Digital Signature Algorithm) Signature
|
||||
extension P384.Signing {
|
||||
|
||||
/// A P-384 elliptic curve digital signature algorithm (ECDSA) signature.
|
||||
public struct ECDSASignature: ContiguousBytes, NISTECDSASignature {
|
||||
/// Returns the raw signature.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
|
||||
/// A raw data representation of a P-384 digital signature.
|
||||
public var rawRepresentation: Data
|
||||
|
||||
/// Initializes ECDSASignature from the raw representation.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
/// As defined in https://tools.ietf.org/html/rfc4754
|
||||
/// Creates a P-384 digital signature from a raw representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the signature as a
|
||||
/// collection of contiguous bytes.
|
||||
public init<D: DataProtocol>(rawRepresentation: D) throws {
|
||||
guard rawRepresentation.count == 2 * P384.coordinateByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
@@ -208,7 +232,12 @@ extension P384.Signing {
|
||||
return (combined.prefix(upTo: half), combined.suffix(from: half))
|
||||
}
|
||||
|
||||
/// Initializes ECDSASignature from the DER representation.
|
||||
/// Creates a P-384 digital signature from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: The DER-encoded representation of the
|
||||
/// signature.
|
||||
public init<D: DataProtocol>(derRepresentation: D) throws {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -235,11 +264,14 @@ extension P384.Signing {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw
|
||||
/// bytes of the signature.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
try self.rawRepresentation.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
/// A DER-encoded representation of the signature
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of a
|
||||
/// P-384 digital signature.
|
||||
public var derRepresentation: Data {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -262,11 +294,14 @@ extension P384.Signing: NISTSigning {}
|
||||
|
||||
// MARK: - P384 + PrivateKey
|
||||
extension P384.Signing.PrivateKey: DigestSigner {
|
||||
/// Generates an ECDSA signature over the P384 elliptic curve.
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the digest you provide over the P-384 elliptic curve.
|
||||
///
|
||||
/// - Parameter digest: The digest to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature
|
||||
/// - Parameters:
|
||||
/// - digest: The digest of the data to sign.
|
||||
/// - Returns: The signature corresponding to the digest. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: Digest>(for digest: D) throws -> P384.Signing.ECDSASignature {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return try self.coreCryptoSignature(for: digest)
|
||||
@@ -276,24 +311,30 @@ extension P384.Signing.PrivateKey: DigestSigner {
|
||||
}
|
||||
}
|
||||
|
||||
extension P384.Signing.PrivateKey: Signer {
|
||||
/// Generates an ECDSA signature over the P384 elliptic curve.
|
||||
/// SHA384 is used as the hash function.
|
||||
extension P384.Signing.PrivateKey: Signer {
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the data you provide over the P-384 elliptic curve,
|
||||
/// using SHA-384 as the hash function.
|
||||
///
|
||||
/// - Parameter data: The data to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature.
|
||||
/// - Parameters:
|
||||
/// - data: The data to sign.
|
||||
/// - Returns: The signature corresponding to the data. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: DataProtocol>(for data: D) throws -> P384.Signing.ECDSASignature {
|
||||
return try self.signature(for: SHA384.hash(data: data))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension P384.Signing.PublicKey: DigestValidator {
|
||||
/// Verifies an ECDSA signature over the P384 elliptic curve.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a digest over the P-384 elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - digest: The digest that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - digest: The signed digest.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given digest; otherwise, `false`.
|
||||
public func isValidSignature<D: Digest>(_ signature: P384.Signing.ECDSASignature, for digest: D) -> Bool {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return self.coreCryptoIsValidSignature(signature, for: digest)
|
||||
@@ -304,29 +345,33 @@ extension P384.Signing.PublicKey: DigestValidator {
|
||||
}
|
||||
|
||||
extension P384.Signing.PublicKey: DataValidator {
|
||||
/// Verifies an ECDSA signature over the P384 elliptic curve.
|
||||
/// SHA384 is used as the hash function.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a block of data over the P-384 elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - data: The data that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - data: The signed data.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given data; otherwise, `false`.
|
||||
public func isValidSignature<D: DataProtocol>(_ signature: P384.Signing.ECDSASignature, for data: D) -> Bool {
|
||||
return self.isValidSignature(signature, for: SHA384.hash(data: data))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - P521 + Signing
|
||||
/// An ECDSA (Elliptic Curve Digital Signature Algorithm) Signature
|
||||
extension P521.Signing {
|
||||
|
||||
/// A P-521 elliptic curve digital signature algorithm (ECDSA) signature.
|
||||
public struct ECDSASignature: ContiguousBytes, NISTECDSASignature {
|
||||
/// Returns the raw signature.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
|
||||
/// A raw data representation of a P-521 digital signature.
|
||||
public var rawRepresentation: Data
|
||||
|
||||
/// Initializes ECDSASignature from the raw representation.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
/// As defined in https://tools.ietf.org/html/rfc4754
|
||||
/// Creates a P-521 digital signature from a raw representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the signature as a
|
||||
/// collection of contiguous bytes.
|
||||
public init<D: DataProtocol>(rawRepresentation: D) throws {
|
||||
guard rawRepresentation.count == 2 * P521.coordinateByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
@@ -350,7 +395,12 @@ extension P521.Signing {
|
||||
return (combined.prefix(upTo: half), combined.suffix(from: half))
|
||||
}
|
||||
|
||||
/// Initializes ECDSASignature from the DER representation.
|
||||
/// Creates a P-521 digital signature from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: The DER-encoded representation of the
|
||||
/// signature.
|
||||
public init<D: DataProtocol>(derRepresentation: D) throws {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -377,11 +427,14 @@ extension P521.Signing {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw
|
||||
/// bytes of the signature.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
try self.rawRepresentation.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
/// A DER-encoded representation of the signature
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of a
|
||||
/// P-521 digital signature.
|
||||
public var derRepresentation: Data {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -404,11 +457,14 @@ extension P521.Signing: NISTSigning {}
|
||||
|
||||
// MARK: - P521 + PrivateKey
|
||||
extension P521.Signing.PrivateKey: DigestSigner {
|
||||
/// Generates an ECDSA signature over the P521 elliptic curve.
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the digest you provide over the P-521 elliptic curve.
|
||||
///
|
||||
/// - Parameter digest: The digest to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature
|
||||
/// - Parameters:
|
||||
/// - digest: The digest of the data to sign.
|
||||
/// - Returns: The signature corresponding to the digest. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: Digest>(for digest: D) throws -> P521.Signing.ECDSASignature {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return try self.coreCryptoSignature(for: digest)
|
||||
@@ -418,24 +474,30 @@ extension P521.Signing.PrivateKey: DigestSigner {
|
||||
}
|
||||
}
|
||||
|
||||
extension P521.Signing.PrivateKey: Signer {
|
||||
/// Generates an ECDSA signature over the P521 elliptic curve.
|
||||
/// SHA512 is used as the hash function.
|
||||
extension P521.Signing.PrivateKey: Signer {
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the data you provide over the P-521 elliptic curve,
|
||||
/// using SHA-512 as the hash function.
|
||||
///
|
||||
/// - Parameter data: The data to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature.
|
||||
/// - Parameters:
|
||||
/// - data: The data to sign.
|
||||
/// - Returns: The signature corresponding to the data. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: DataProtocol>(for data: D) throws -> P521.Signing.ECDSASignature {
|
||||
return try self.signature(for: SHA512.hash(data: data))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension P521.Signing.PublicKey: DigestValidator {
|
||||
/// Verifies an ECDSA signature over the P521 elliptic curve.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a digest over the P-521 elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - digest: The digest that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - digest: The signed digest.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given digest; otherwise, `false`.
|
||||
public func isValidSignature<D: Digest>(_ signature: P521.Signing.ECDSASignature, for digest: D) -> Bool {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return self.coreCryptoIsValidSignature(signature, for: digest)
|
||||
@@ -446,13 +508,14 @@ extension P521.Signing.PublicKey: DigestValidator {
|
||||
}
|
||||
|
||||
extension P521.Signing.PublicKey: DataValidator {
|
||||
/// Verifies an ECDSA signature over the P521 elliptic curve.
|
||||
/// SHA512 is used as the hash function.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a block of data over the P-521 elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - data: The data that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - data: The signed data.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given data; otherwise, `false`.
|
||||
public func isValidSignature<D: DataProtocol>(_ signature: P521.Signing.ECDSASignature, for data: D) -> Bool {
|
||||
return self.isValidSignature(signature, for: SHA512.hash(data: data))
|
||||
}
|
||||
|
||||
@@ -37,20 +37,25 @@ protocol NISTSigning {
|
||||
|
||||
% for CURVE_AND_HF in NIST_CURVES_AND_HF:
|
||||
%{
|
||||
CURVE = CURVE_AND_HF["curve"]
|
||||
HF = CURVE_AND_HF["hf"]
|
||||
CURVE = CURVE_AND_HF["curve"]
|
||||
HF = CURVE_AND_HF["hf"]
|
||||
DISPLAY_CURVE = CURVE[:1] + "-" + CURVE[1:]
|
||||
DISPLAY_HF = HF[:3] + "-" + HF[3:]
|
||||
}%
|
||||
// MARK: - ${CURVE} + Signing
|
||||
/// An ECDSA (Elliptic Curve Digital Signature Algorithm) Signature
|
||||
extension ${CURVE}.Signing {
|
||||
|
||||
/// A ${DISPLAY_CURVE} elliptic curve digital signature algorithm (ECDSA) signature.
|
||||
public struct ECDSASignature: ContiguousBytes, NISTECDSASignature {
|
||||
/// Returns the raw signature.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
|
||||
/// A raw data representation of a ${DISPLAY_CURVE} digital signature.
|
||||
public var rawRepresentation: Data
|
||||
|
||||
/// Initializes ECDSASignature from the raw representation.
|
||||
/// The raw signature format for ECDSA is r || s
|
||||
/// As defined in https://tools.ietf.org/html/rfc4754
|
||||
/// Creates a ${DISPLAY_CURVE} digital signature from a raw representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawRepresentation: A raw representation of the signature as a
|
||||
/// collection of contiguous bytes.
|
||||
public init<D: DataProtocol>(rawRepresentation: D) throws {
|
||||
guard rawRepresentation.count == 2 * ${CURVE}.coordinateByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
@@ -74,7 +79,12 @@ extension ${CURVE}.Signing {
|
||||
return (combined.prefix(upTo: half), combined.suffix(from: half))
|
||||
}
|
||||
|
||||
/// Initializes ECDSASignature from the DER representation.
|
||||
/// Creates a ${DISPLAY_CURVE} digital signature from a Distinguished Encoding
|
||||
/// Rules (DER) encoded representation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - derRepresentation: The DER-encoded representation of the
|
||||
/// signature.
|
||||
public init<D: DataProtocol>(derRepresentation: D) throws {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -101,11 +111,14 @@ extension ${CURVE}.Signing {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Invokes the given closure with a buffer pointer covering the raw
|
||||
/// bytes of the signature.
|
||||
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
|
||||
try self.rawRepresentation.withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
/// A DER-encoded representation of the signature
|
||||
/// A Distinguished Encoding Rules (DER) encoded representation of a
|
||||
/// ${DISPLAY_CURVE} digital signature.
|
||||
public var derRepresentation: Data {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
@@ -128,11 +141,14 @@ extension ${CURVE}.Signing: NISTSigning {}
|
||||
|
||||
// MARK: - ${CURVE} + PrivateKey
|
||||
extension ${CURVE}.Signing.PrivateKey: DigestSigner {
|
||||
/// Generates an ECDSA signature over the ${CURVE} elliptic curve.
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the digest you provide over the ${DISPLAY_CURVE} elliptic curve.
|
||||
///
|
||||
/// - Parameter digest: The digest to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature
|
||||
/// - Parameters:
|
||||
/// - digest: The digest of the data to sign.
|
||||
/// - Returns: The signature corresponding to the digest. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: Digest>(for digest: D) throws -> ${CURVE}.Signing.ECDSASignature {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return try self.coreCryptoSignature(for: digest)
|
||||
@@ -142,24 +158,30 @@ extension ${CURVE}.Signing.PrivateKey: DigestSigner {
|
||||
}
|
||||
}
|
||||
|
||||
extension ${CURVE}.Signing.PrivateKey: Signer {
|
||||
/// Generates an ECDSA signature over the ${CURVE} elliptic curve.
|
||||
/// ${HF} is used as the hash function.
|
||||
extension ${CURVE}.Signing.PrivateKey: Signer {
|
||||
/// Generates an Elliptic Curve Digital Signature Algorithm (ECDSA)
|
||||
/// signature of the data you provide over the ${DISPLAY_CURVE} elliptic curve,
|
||||
/// using ${DISPLAY_HF} as the hash function.
|
||||
///
|
||||
/// - Parameter data: The data to sign.
|
||||
/// - Returns: The ECDSA Signature.
|
||||
/// - Throws: If there is a failure producing the signature.
|
||||
/// - Parameters:
|
||||
/// - data: The data to sign.
|
||||
/// - Returns: The signature corresponding to the data. The signing
|
||||
/// algorithm employs randomization to generate a different signature on
|
||||
/// every call, even for the same data and key.
|
||||
public func signature<D: DataProtocol>(for data: D) throws -> ${CURVE}.Signing.ECDSASignature {
|
||||
return try self.signature(for: ${HF}.hash(data: data))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ${CURVE}.Signing.PublicKey: DigestValidator {
|
||||
/// Verifies an ECDSA signature over the ${CURVE} elliptic curve.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a digest over the ${DISPLAY_CURVE} elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - digest: The digest that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - digest: The signed digest.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given digest; otherwise, `false`.
|
||||
public func isValidSignature<D: Digest>(_ signature: ${CURVE}.Signing.ECDSASignature, for digest: D) -> Bool {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return self.coreCryptoIsValidSignature(signature, for: digest)
|
||||
@@ -170,13 +192,14 @@ extension ${CURVE}.Signing.PublicKey: DigestValidator {
|
||||
}
|
||||
|
||||
extension ${CURVE}.Signing.PublicKey: DataValidator {
|
||||
/// Verifies an ECDSA signature over the ${CURVE} elliptic curve.
|
||||
/// ${HF} is used as the hash function.
|
||||
/// Verifies an elliptic curve digital signature algorithm (ECDSA)
|
||||
/// signature on a block of data over the ${DISPLAY_CURVE} elliptic curve.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to verify
|
||||
/// - data: The data that was signed.
|
||||
/// - Returns: True if the signature is valid, false otherwise.
|
||||
/// - signature: The signature to verify.
|
||||
/// - data: The signed data.
|
||||
/// - Returns: A Boolean value that’s `true` if the signature is valid for
|
||||
/// the given data; otherwise, `false`.
|
||||
public func isValidSignature<D: DataProtocol>(_ signature: ${CURVE}.Signing.ECDSASignature, for data: D) -> Bool {
|
||||
return self.isValidSignature(signature, for: ${HF}.hash(data: data))
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ protocol DataValidator {
|
||||
}
|
||||
|
||||
extension Curve25519.Signing {
|
||||
static var signatureLength: Int {
|
||||
static var signatureByteCount: Int {
|
||||
return 64
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,11 @@ extension Curve25519.Signing.PublicKey: DataValidator {
|
||||
/// Verifies an EdDSA signature over Curve25519.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The 64-bytes signature to verify.
|
||||
/// - data: The digest that was signed.
|
||||
/// - Returns: True if the signature is valid. False otherwise.
|
||||
/// - signature: The signature to check against the given data.
|
||||
/// - data: The data covered by the signature.
|
||||
///
|
||||
/// - Returns: A Boolean value that’s `true` when the signature is valid for
|
||||
/// the given data.
|
||||
public func isValidSignature<S: DataProtocol, D: DataProtocol>(_ signature: S, for data: D) -> Bool {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return self.coreCryptoIsValidSignature(signature, for: data)
|
||||
@@ -53,9 +55,15 @@ extension Curve25519.Signing.PublicKey: DataValidator {
|
||||
extension Curve25519.Signing.PrivateKey: Signer {
|
||||
/// Generates an EdDSA signature over Curve25519.
|
||||
///
|
||||
/// - Parameter data: The data to sign.
|
||||
/// - Returns: The 64-bytes signature.
|
||||
/// - Throws: If there is a failure producing the signature.
|
||||
/// - Parameters:
|
||||
/// - data: The data to sign.
|
||||
///
|
||||
/// - Returns: The signature for the data. Although not required by [RFC
|
||||
/// 8032](https://tools.ietf.org/html/rfc8032), which describes the
|
||||
/// Edwards-Curve Digital Signature Algorithm (EdDSA), the CryptoKit
|
||||
/// implementation of the algorithm employs randomization to generate a
|
||||
/// different signature on every call, even for the same data and key, to
|
||||
/// guard against side-channel attacks.
|
||||
public func signature<D: DataProtocol>(for data: D) throws -> Data {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
return try self.coreCryptoSignature(for: data)
|
||||
@@ -16,6 +16,8 @@
|
||||
#else
|
||||
import Foundation
|
||||
|
||||
private let emptyStorage:SecureBytes.Backing = SecureBytes.Backing.createEmpty()
|
||||
|
||||
struct SecureBytes {
|
||||
@usableFromInline
|
||||
var backing: Backing
|
||||
@@ -27,7 +29,11 @@ struct SecureBytes {
|
||||
|
||||
@usableFromInline
|
||||
init(count: Int) {
|
||||
self.backing = SecureBytes.Backing.create(randomBytes: count)
|
||||
if count == 0 {
|
||||
self.backing = emptyStorage
|
||||
} else {
|
||||
self.backing = SecureBytes.Backing.create(randomBytes: count)
|
||||
}
|
||||
}
|
||||
|
||||
init<D: ContiguousBytes>(bytes: D) {
|
||||
@@ -161,6 +167,20 @@ extension SecureBytes: RangeReplaceableCollection {
|
||||
self.backing.replaceSubrangeFittingWithinCapacity(offsetRange, with: newElements)
|
||||
}
|
||||
}
|
||||
|
||||
// The default implementation of this from RangeReplaceableCollection can't take advantage of `ContiguousBytes`, so we override it here
|
||||
@inlinable
|
||||
public mutating func append<Elements: Sequence>(contentsOf newElements: Elements) where Elements.Element == UInt8 {
|
||||
let done:Void? = newElements.withContiguousStorageIfAvailable {
|
||||
replaceSubrange(endIndex..<endIndex, with: $0)
|
||||
}
|
||||
|
||||
if done == nil {
|
||||
for element in newElements {
|
||||
append(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ContiguousBytes conformance
|
||||
@@ -178,6 +198,11 @@ extension SecureBytes: ContiguousBytes {
|
||||
|
||||
return try self.backing.withUnsafeMutableBytes(body)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<UInt8>) throws -> R) rethrows -> R? {
|
||||
return try self.backing.withContiguousStorageIfAvailable(body)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DataProtocol conformance
|
||||
@@ -223,6 +248,12 @@ extension SecureBytes {
|
||||
|
||||
@usableFromInline
|
||||
internal class Backing: ManagedBuffer<BackingHeader, UInt8> {
|
||||
|
||||
@usableFromInline
|
||||
class func createEmpty() -> Backing {
|
||||
return Backing.create(minimumCapacity: 0, makingHeaderWith: { _ in BackingHeader(count: 0, capacity: 0) }) as! Backing
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
class func create(capacity: Int) -> Backing {
|
||||
let capacity = Int(UInt32(capacity).nextPowerOf2ClampedToMax())
|
||||
@@ -414,6 +445,14 @@ extension SecureBytes.Backing: ContiguousBytes {
|
||||
return try body(UnsafeMutableRawBufferPointer(start: elementsPtr, count: capacity))
|
||||
}
|
||||
}
|
||||
|
||||
func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<UInt8>) throws -> R) rethrows -> R? {
|
||||
let count = self.count
|
||||
|
||||
return try self.withUnsafeMutablePointerToElements { elementsPtr in
|
||||
return try body(UnsafeBufferPointer(start: elementsPtr, count: count))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UInt32 {
|
||||
|
||||
@@ -28,6 +28,12 @@ extension UnsafeMutablePointer: Zeroization {
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawBufferPointer: Zeroization {
|
||||
func zeroize() {
|
||||
memset_s(self.baseAddress, self.count, 0, self.count)
|
||||
}
|
||||
}
|
||||
|
||||
extension Array: Zeroization where Element == UInt8 {
|
||||
/// Zeroizes the array
|
||||
mutating func zeroize() {
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2023 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import Foundation
|
||||
|
||||
extension AES {
|
||||
/// The Advanced Encryption Standard (AES) Cipher Block Chaining (CBC) cipher
|
||||
/// suite.
|
||||
public enum _CBC {
|
||||
private static var blockSize: Int { 16 }
|
||||
|
||||
private static func encryptBlockInPlace(
|
||||
_ plaintext: inout Block,
|
||||
priorCiphertextBlock: Block,
|
||||
using key: SymmetricKey
|
||||
) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
plaintext ^= priorCiphertextBlock
|
||||
try AES.permute(&plaintext, key: key)
|
||||
}
|
||||
|
||||
/// Encrypts data using AES-CBC.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - plaintext: The message to encrypt.
|
||||
/// - key: A encryption key.
|
||||
/// - iv: The initialization vector.
|
||||
/// - Returns: The encrypted ciphertext.
|
||||
public static func encrypt<Plaintext: DataProtocol>(_ plaintext: Plaintext, using key: SymmetricKey, iv: AES._CBC.IV) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
let requiresFullPaddingBlock = (plaintext.count % AES._CBC.blockSize) == 0
|
||||
|
||||
var ciphertext = Data()
|
||||
ciphertext.reserveCapacity(plaintext.count + Self.blockSize) // Room for padding.
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var plaintext = plaintext[...]
|
||||
|
||||
while plaintext.count > 0 {
|
||||
var block = Block(blockBytes: plaintext.prefix(Self.blockSize))
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
previousBlock = block
|
||||
plaintext = plaintext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
if requiresFullPaddingBlock {
|
||||
var block = Block.paddingBlock
|
||||
try Self.encryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
ciphertext.append(contentsOf: block)
|
||||
}
|
||||
|
||||
return ciphertext
|
||||
}
|
||||
|
||||
private static func decryptBlockInPlace(_ ciphertext: inout Block, priorCiphertextBlock: Block, using key: SymmetricKey) throws {
|
||||
assert([128, 192, 256].contains(key.bitCount))
|
||||
|
||||
try AES.inversePermute(&ciphertext, key: key)
|
||||
ciphertext ^= priorCiphertextBlock
|
||||
}
|
||||
|
||||
/// Decrypts data using AES-CBC.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ciphertext: The encrypted ciphertext.
|
||||
/// - key: A decryption key.
|
||||
/// - iv: The initialization vector.
|
||||
/// - Returns: The decrypted message.
|
||||
public static func decrypt<Ciphertext: DataProtocol>(_ ciphertext: Ciphertext, using key: SymmetricKey, iv: AES._CBC.IV) throws -> Data {
|
||||
guard [128, 192, 256].contains(key.bitCount) else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
var plaintext = Data()
|
||||
plaintext.reserveCapacity(ciphertext.count)
|
||||
|
||||
var previousBlock = Block(iv)
|
||||
var ciphertext = ciphertext[...]
|
||||
|
||||
while ciphertext.count > 0 {
|
||||
let ctBlock = Block(blockBytes: ciphertext.prefix(Self.blockSize))
|
||||
var block = ctBlock
|
||||
try Self.decryptBlockInPlace(&block, priorCiphertextBlock: previousBlock, using: key)
|
||||
plaintext.append(contentsOf: block)
|
||||
previousBlock = ctBlock
|
||||
ciphertext = ciphertext.dropFirst(Self.blockSize)
|
||||
}
|
||||
|
||||
try plaintext.trimPadding()
|
||||
return plaintext
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AES._CBC {
|
||||
/// An initialization vector.
|
||||
public struct IV {
|
||||
// AES CBC uses a 128-bit IV.
|
||||
var ivBytes: (
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
|
||||
)
|
||||
|
||||
public init() {
|
||||
var rng = SystemRandomNumberGenerator()
|
||||
let (first, second) = (rng.next(), rng.next())
|
||||
|
||||
self.ivBytes = (
|
||||
UInt8(truncatingIfNeeded: first),
|
||||
UInt8(truncatingIfNeeded: first >> 8),
|
||||
UInt8(truncatingIfNeeded: first >> 16),
|
||||
UInt8(truncatingIfNeeded: first >> 24),
|
||||
UInt8(truncatingIfNeeded: first >> 32),
|
||||
UInt8(truncatingIfNeeded: first >> 40),
|
||||
UInt8(truncatingIfNeeded: first >> 48),
|
||||
UInt8(truncatingIfNeeded: first >> 56),
|
||||
UInt8(truncatingIfNeeded: second),
|
||||
UInt8(truncatingIfNeeded: second >> 8),
|
||||
UInt8(truncatingIfNeeded: second >> 16),
|
||||
UInt8(truncatingIfNeeded: second >> 24),
|
||||
UInt8(truncatingIfNeeded: second >> 32),
|
||||
UInt8(truncatingIfNeeded: second >> 40),
|
||||
UInt8(truncatingIfNeeded: second >> 48),
|
||||
UInt8(truncatingIfNeeded: second >> 56)
|
||||
)
|
||||
}
|
||||
|
||||
public init<IVBytes: Collection>(ivBytes: IVBytes) throws where IVBytes.Element == UInt8 {
|
||||
// We support a 128-bit IV.
|
||||
guard ivBytes.count == 16 else {
|
||||
throw CryptoKitError.incorrectKeySize
|
||||
}
|
||||
|
||||
self.ivBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
withUnsafeMutableBytes(of: &self.ivBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: ivBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Data {
|
||||
fileprivate mutating func trimPadding() throws {
|
||||
guard let paddingBytes = self.last else {
|
||||
// Degenerate case, empty string. This is forbidden:
|
||||
// we must always pad.
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
guard paddingBytes > 0 &&
|
||||
self.count >= paddingBytes &&
|
||||
self.suffix(Int(paddingBytes)).allSatisfy({ $0 == paddingBytes }) else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
self = self.dropLast(Int(paddingBytes))
|
||||
}
|
||||
}
|
||||
@@ -58,9 +58,9 @@ extension AES.GCM {
|
||||
/// - sealedBox: The sealed box to authenticate and decrypt
|
||||
/// - key: An encryption key of 128 or 256 bits
|
||||
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
|
||||
/// - authenticatedData: Data that was authenticated as part of the seal
|
||||
/// - authenticatedData: Data that was authenticated as part of the seal
|
||||
/// - Returns: The ciphertext if opening was successful
|
||||
/// - Throws: CipherError errors. If the authentication of the sealedbox failed, incorrectTag is thrown.
|
||||
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
|
||||
public static func open<AuthenticatedData: DataProtocol>
|
||||
(_ sealedBox: SealedBox, using key: SymmetricKey, authenticating authenticatedData: AuthenticatedData) throws -> Data {
|
||||
return try OpenSSLAESGCMSIVImpl.open(key: key, sealedBox: sealedBox, authenticatedData: authenticatedData)
|
||||
@@ -73,7 +73,7 @@ extension AES.GCM {
|
||||
/// - key: An encryption key of 128 or 256 bits
|
||||
/// - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
|
||||
/// - Returns: The ciphertext if opening was successful
|
||||
/// - Throws: CipherError errors. If the authentication of the sealedbox failed, incorrectTag is thrown.
|
||||
/// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
|
||||
public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
|
||||
return try OpenSSLAESGCMSIVImpl.open(key: key, sealedBox: sealedBox, authenticatedData: Data?.none)
|
||||
}
|
||||
|
||||
@@ -62,7 +62,8 @@ extension AES {
|
||||
} ?? true
|
||||
|
||||
if requiresSlowPath {
|
||||
try AES.Block.withStackStorage { blockBytes in
|
||||
var block = AES.Block()
|
||||
try block.withUnsafeMutableBytes { blockBytes in
|
||||
precondition(blockBytes.count == payload.count)
|
||||
|
||||
blockBytes.copyBytes(from: payload)
|
||||
@@ -109,25 +110,87 @@ extension AES {
|
||||
}
|
||||
}
|
||||
|
||||
private struct Block {
|
||||
private var storage: (UInt64, UInt64)
|
||||
struct Block {
|
||||
private static var blockSize: Int { 16 }
|
||||
|
||||
private init() {
|
||||
assert(MemoryLayout<Self>.size == Int(AES.blockSize))
|
||||
self.storage = (0, 0)
|
||||
typealias BlockBytes = (
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8
|
||||
)
|
||||
|
||||
// 128-bit block size
|
||||
private var blockBytes: BlockBytes
|
||||
|
||||
fileprivate init() {
|
||||
self.blockBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
}
|
||||
|
||||
private mutating func withUnsafeMutableBytes<ReturnType>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType
|
||||
) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.storage, body)
|
||||
init(_ blockBytes: BlockBytes) {
|
||||
self.blockBytes = blockBytes
|
||||
}
|
||||
|
||||
static func withStackStorage<ReturnType>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType
|
||||
) rethrows -> ReturnType {
|
||||
var storage = Self()
|
||||
return try storage.withUnsafeMutableBytes(body)
|
||||
init(_ iv: AES._CBC.IV) {
|
||||
self.blockBytes = iv.ivBytes
|
||||
}
|
||||
|
||||
init<BlockBytes: Collection>(blockBytes: BlockBytes) where BlockBytes.Element == UInt8 {
|
||||
// The block size is always 16. Pad out past there.
|
||||
precondition(blockBytes.count <= Self.blockSize)
|
||||
|
||||
self.blockBytes = (
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0
|
||||
)
|
||||
|
||||
Swift.withUnsafeMutableBytes(of: &self.blockBytes) { bytesPtr in
|
||||
bytesPtr.copyBytes(from: blockBytes)
|
||||
|
||||
// Early exit here.
|
||||
if blockBytes.count == Self.blockSize {
|
||||
return
|
||||
}
|
||||
|
||||
var remainingBytes = bytesPtr.dropFirst(blockBytes.count)
|
||||
let padByte = UInt8(remainingBytes.count)
|
||||
|
||||
for index in remainingBytes.indices {
|
||||
remainingBytes[index] = padByte
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static var paddingBlock: Block {
|
||||
// The padding block is a full block of value blocksize.
|
||||
let value = UInt8(truncatingIfNeeded: Self.blockSize)
|
||||
return Block((
|
||||
value, value, value, value, value, value, value, value,
|
||||
value, value, value, value, value, value, value, value
|
||||
))
|
||||
}
|
||||
|
||||
func withUnsafeBytes<ReturnType>(_ body: (UnsafeRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeBytes(of: self.blockBytes, body)
|
||||
}
|
||||
|
||||
mutating func withUnsafeMutableBytes<ReturnType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ReturnType) rethrows -> ReturnType {
|
||||
return try Swift.withUnsafeMutableBytes(of: &self.blockBytes, body)
|
||||
}
|
||||
|
||||
static func ^= (lhs: inout Block, rhs: Block) {
|
||||
// Ideally we'd not use raw pointers for this.
|
||||
lhs.withUnsafeMutableBytes { lhsPtr in
|
||||
rhs.withUnsafeBytes { rhsPtr in
|
||||
assert(lhsPtr.count == Self.blockSize)
|
||||
assert(rhsPtr.count == Self.blockSize)
|
||||
|
||||
for index in 0..<Self.blockSize {
|
||||
lhsPtr[index] ^= rhsPtr[index]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,3 +204,50 @@ extension AES {
|
||||
}
|
||||
}
|
||||
|
||||
extension AES.Block: RandomAccessCollection, MutableCollection {
|
||||
var startIndex: Int {
|
||||
0
|
||||
}
|
||||
|
||||
var endIndex: Int {
|
||||
Self.blockSize
|
||||
}
|
||||
|
||||
subscript(position: Int) -> UInt8 {
|
||||
get {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
return self.withUnsafeBytes { $0[position] }
|
||||
}
|
||||
|
||||
set {
|
||||
precondition(position >= 0)
|
||||
precondition(position < Self.blockSize)
|
||||
|
||||
self.withUnsafeMutableBytes { $0[position] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
func withContiguousStorageIfAvailable<ReturnValue>(
|
||||
_ body: (UnsafeBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafePointer(to: self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
let bufferised = UnsafeBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(bufferised)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func withContiguousMutableStorageIfAvailable<ReturnValue>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<UInt8>) throws -> ReturnValue)
|
||||
rethrows -> ReturnValue? {
|
||||
return try withUnsafeMutablePointer(to: &self.blockBytes) { tuplePtr in
|
||||
// Homogeneous tuples are always bound to the element type as well as to their own type.
|
||||
let retyped = UnsafeMutableRawPointer(tuplePtr).assumingMemoryBound(to: UInt8.self)
|
||||
var bufferised = UnsafeMutableBufferPointer(start: retyped, count: Self.blockSize)
|
||||
return try body(&bufferised)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ extension _RSA.Signing {
|
||||
public init(pemRepresentation: String) throws {
|
||||
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
|
||||
|
||||
if self.keySizeInBits < 1024 || self.keySizeInBits % 8 != 0 {
|
||||
guard self.keySizeInBits >= 1024 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ extension _RSA.Signing {
|
||||
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
|
||||
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
|
||||
|
||||
if self.keySizeInBits < 1024 || self.keySizeInBits % 8 != 0 {
|
||||
guard self.keySizeInBits >= 1024 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,7 @@ extension _RSA.Signing {
|
||||
public init(pemRepresentation: String) throws {
|
||||
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
|
||||
|
||||
if self.keySizeInBits < 1024 || self.keySizeInBits % 8 != 0 {
|
||||
guard self.keySizeInBits >= 1024 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ extension _RSA.Signing {
|
||||
public init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
|
||||
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
|
||||
|
||||
if self.keySizeInBits < 1024 || self.keySizeInBits % 8 != 0 {
|
||||
guard self.keySizeInBits >= 1024 else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
}
|
||||
@@ -226,7 +226,7 @@ extension _RSA.Signing.PrivateKey {
|
||||
return try self.signature(for: SHA256.hash(data: data), padding: .PSS)
|
||||
}
|
||||
|
||||
/// Generates an RSA signature with the given key.
|
||||
/// Generates an RSA signature with the given key.
|
||||
///
|
||||
/// - Parameter digest: The digest to sign.
|
||||
/// - Parameter padding: The padding to use.
|
||||
|
||||
@@ -61,8 +61,7 @@ internal struct SecurityRSAPublicKey {
|
||||
}
|
||||
|
||||
var keySizeInBits: Int {
|
||||
let attributes = SecKeyCopyAttributes(self.backing)! as NSDictionary
|
||||
return (attributes[kSecAttrKeySizeInBits]! as! NSNumber).intValue
|
||||
SecKeyGetBlockSize(self.backing) * 8
|
||||
}
|
||||
|
||||
fileprivate init(_ backing: SecKey) {
|
||||
@@ -146,8 +145,7 @@ internal struct SecurityRSAPrivateKey {
|
||||
}
|
||||
|
||||
var keySizeInBits: Int {
|
||||
let attributes = SecKeyCopyAttributes(self.backing)! as NSDictionary
|
||||
return (attributes[kSecAttrKeySizeInBits]! as! NSNumber).intValue
|
||||
SecKeyGetBlockSize(self.backing) * 8
|
||||
}
|
||||
|
||||
var publicKey: SecurityRSAPublicKey {
|
||||
|
||||
@@ -39,7 +39,7 @@ final class GeneralizedTimeTests: XCTestCase {
|
||||
("19920622123421Z", try .init(year: 1992, month: 6, day: 22, hours: 12, minutes: 34, seconds: 21, fractionalSeconds: 0)),
|
||||
("19920722132100.3Z", try .init(year: 1992, month: 7, day: 22, hours: 13, minutes: 21, seconds: 0, fractionalSeconds: 0.3)),
|
||||
("19851106210627.3Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.3)),
|
||||
("19851106210627.14159Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.141_59)),
|
||||
("19851106210627.14159Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.14159)),
|
||||
("20210131000000Z", try .init(year: 2021, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in January
|
||||
("20210228000000Z", try .init(year: 2021, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 28 days in February 2021
|
||||
("20200229000000Z", try .init(year: 2020, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 29 days in February 2020
|
||||
|
||||
@@ -29,14 +29,14 @@ extension NISTECDHTests {
|
||||
for testVector in group.tests {
|
||||
do {
|
||||
let pkBytes = try Array(hexString: testVector.publicKey)
|
||||
let publicKey = try PrivKey.PublicKey(derBytes: pkBytes, curve: Curve.self)
|
||||
let publicKey = try PrivKey.PK(derBytes: pkBytes, curve: Curve.self)
|
||||
|
||||
var privateBytes = [UInt8]()
|
||||
privateBytes = try padKeyIfNecessary(curve: curve, vector: testVector.privateKey)
|
||||
|
||||
let privateKey = try PrivKey(rawRepresentation: privateBytes)
|
||||
|
||||
let agreement = try unwrap(publicKey as? PrivKey.P, file: file, line: line)
|
||||
let agreement = try unwrap(publicKey as? PrivKey.PublicKey, file: file, line: line)
|
||||
let result = try privateKey.sharedSecretFromKeyAgreement(with: agreement)
|
||||
|
||||
let expectedResult = try Array(hexString: testVector.shared)
|
||||
@@ -58,12 +58,12 @@ extension NISTECDHTests {
|
||||
for testVector in group.tests {
|
||||
do {
|
||||
let pkBytes = try Array(hexString: testVector.publicKey)
|
||||
let publicKey: PrivKey.PublicKey
|
||||
let publicKey: PrivKey.PK
|
||||
|
||||
if testVector.flags.contains("CompressedPoint") {
|
||||
publicKey = try PrivKey.PublicKey(compressedRepresentation: pkBytes)
|
||||
publicKey = try PrivKey.PK(compressedRepresentation: pkBytes)
|
||||
} else {
|
||||
publicKey = try PrivKey.PublicKey(x963Representation: pkBytes)
|
||||
publicKey = try PrivKey.PK(x963Representation: pkBytes)
|
||||
}
|
||||
|
||||
var privateBytes = [UInt8]()
|
||||
@@ -71,7 +71,7 @@ extension NISTECDHTests {
|
||||
|
||||
let privateKey = try PrivKey(rawRepresentation: privateBytes)
|
||||
|
||||
let agreement = try unwrap(publicKey as? PrivKey.P, file: file, line: line)
|
||||
let agreement = try unwrap(publicKey as? PrivKey.PublicKey, file: file, line: line)
|
||||
let result = try privateKey.sharedSecretFromKeyAgreement(with: agreement)
|
||||
|
||||
let expectedResult = try Array(hexString: testVector.shared)
|
||||
|
||||
@@ -190,7 +190,12 @@ class X25519Tests: XCTestCase {
|
||||
|
||||
let testSharedSecret = try Array(privateKey.sharedSecretFromKeyAgreement(with: publicKey).ss)
|
||||
XCTAssertEqual(testSharedSecret, expectedSharedSecret)
|
||||
XCTAssert(testVector.result == "valid" || testVector.result == "acceptable")
|
||||
} catch {
|
||||
if testVector.flags.contains("LowOrderPublic") {
|
||||
XCTAssertEqual(testVector.result, "acceptable")
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(testVector.result, "invalid")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ class ECKeyEncodingsTests: XCTestCase {
|
||||
let p521KeyKA_x963 = p521KeyKA.x963Representation
|
||||
XCTAssertNoThrow(try P521.KeyAgreement.PrivateKey(rawRepresentation: p521KeyKA_raw))
|
||||
XCTAssertNoThrow(try P521.KeyAgreement.PrivateKey(x963Representation: p521KeyKA_x963))
|
||||
|
||||
|
||||
// Curve25519 does not have an x963 representation.
|
||||
let x25519KeyKA = Curve25519.KeyAgreement.PrivateKey()
|
||||
let x25519KeyKA_raw = x25519KeyKA.rawRepresentation
|
||||
@@ -66,84 +66,121 @@ class ECKeyEncodingsTests: XCTestCase {
|
||||
let p521KeyKA_x963 = p521KeyKA.x963Representation
|
||||
XCTAssertNoThrow(try P521.Signing.PrivateKey(rawRepresentation: p521KeyKA_raw))
|
||||
XCTAssertNoThrow(try P521.Signing.PrivateKey(x963Representation: p521KeyKA_x963))
|
||||
|
||||
|
||||
let x25519KeyKA = Curve25519.Signing.PrivateKey()
|
||||
let x25519KeyKA_raw = x25519KeyKA.rawRepresentation
|
||||
XCTAssertNoThrow(try Curve25519.Signing.PrivateKey(rawRepresentation: x25519KeyKA_raw))
|
||||
}
|
||||
|
||||
|
||||
func testEncodingsKeyAgreementPublicKeys() {
|
||||
let p256KeyKA = P256.KeyAgreement.PrivateKey().publicKey
|
||||
let p256KeyKA_raw = p256KeyKA.rawRepresentation
|
||||
let p256KeyKA_x963 = p256KeyKA.x963Representation
|
||||
let p256KeyKA_compressed = p256KeyKA.compressedRepresentation
|
||||
XCTAssertNoThrow(try P256.KeyAgreement.PublicKey(rawRepresentation: p256KeyKA_raw))
|
||||
XCTAssertNoThrow(try P256.KeyAgreement.PublicKey(x963Representation: p256KeyKA_x963))
|
||||
|
||||
XCTAssertNoThrow(try P256.KeyAgreement.PublicKey(compressedRepresentation: p256KeyKA_compressed))
|
||||
XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(compressedRepresentation: p256KeyKA_x963)) { error in
|
||||
XCTAssertTrue(error is CryptoKitError)
|
||||
XCTAssertEqual(error as? CryptoKitError, .incorrectParameterSize)
|
||||
}
|
||||
|
||||
let p384KeyKA = P384.KeyAgreement.PrivateKey().publicKey
|
||||
let p384KeyKA_raw = p384KeyKA.rawRepresentation
|
||||
let p384KeyKA_x963 = p384KeyKA.x963Representation
|
||||
let p384KeyKA_compressed = p384KeyKA.compressedRepresentation
|
||||
XCTAssertNoThrow(try P384.KeyAgreement.PublicKey(rawRepresentation: p384KeyKA_raw))
|
||||
XCTAssertNoThrow(try P384.KeyAgreement.PublicKey(x963Representation: p384KeyKA_x963))
|
||||
|
||||
XCTAssertNoThrow(try P384.KeyAgreement.PublicKey(compressedRepresentation: p384KeyKA_compressed))
|
||||
XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(compressedRepresentation: p384KeyKA_x963)) { error in
|
||||
XCTAssertTrue(error is CryptoKitError)
|
||||
XCTAssertEqual(error as? CryptoKitError, .incorrectParameterSize)
|
||||
}
|
||||
|
||||
let p521KeyKA = P521.KeyAgreement.PrivateKey().publicKey
|
||||
let p521KeyKA_raw = p521KeyKA.rawRepresentation
|
||||
let p521KeyKA_x963 = p521KeyKA.x963Representation
|
||||
let p521KeyKA_compressed = p521KeyKA.compressedRepresentation
|
||||
XCTAssertNoThrow(try P521.KeyAgreement.PublicKey(rawRepresentation: p521KeyKA_raw))
|
||||
XCTAssertNoThrow(try P521.KeyAgreement.PublicKey(x963Representation: p521KeyKA_x963))
|
||||
|
||||
XCTAssertNoThrow(try P521.KeyAgreement.PublicKey(compressedRepresentation: p521KeyKA_compressed))
|
||||
XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(compressedRepresentation: p521KeyKA_x963)) { error in
|
||||
XCTAssertTrue(error is CryptoKitError)
|
||||
XCTAssertEqual(error as? CryptoKitError, .incorrectParameterSize)
|
||||
}
|
||||
|
||||
// Curve25519 does not have an x963 representation.
|
||||
let x25519KeyKA = Curve25519.KeyAgreement.PrivateKey().publicKey
|
||||
let x25519KeyKA_raw = x25519KeyKA.rawRepresentation
|
||||
XCTAssertNoThrow(try Curve25519.KeyAgreement.PublicKey(rawRepresentation: x25519KeyKA_raw))
|
||||
}
|
||||
|
||||
|
||||
func testEncodingsSigningKeyPublicKeys() {
|
||||
let p256KeyKA = P256.Signing.PrivateKey().publicKey
|
||||
let p256KeyKA_raw = p256KeyKA.rawRepresentation
|
||||
let p256KeyKA_x963 = p256KeyKA.x963Representation
|
||||
let p256KeyKA_compressed = p256KeyKA.compressedRepresentation
|
||||
|
||||
XCTAssertNoThrow(try P256.Signing.PublicKey(rawRepresentation: p256KeyKA_raw))
|
||||
XCTAssertNoThrow(try P256.Signing.PublicKey(x963Representation: p256KeyKA_x963))
|
||||
|
||||
XCTAssertNoThrow(try P256.KeyAgreement.PublicKey(compressedRepresentation: p256KeyKA_compressed))
|
||||
XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(compressedRepresentation: p256KeyKA_x963)) { error in
|
||||
XCTAssertTrue(error is CryptoKitError)
|
||||
XCTAssertEqual(error as? CryptoKitError, .incorrectParameterSize)
|
||||
}
|
||||
|
||||
let p384KeyKA = P384.Signing.PrivateKey().publicKey
|
||||
let p384KeyKA_raw = p384KeyKA.rawRepresentation
|
||||
let p384KeyKA_x963 = p384KeyKA.x963Representation
|
||||
let p384KeyKA_compressed = p384KeyKA.compressedRepresentation
|
||||
XCTAssertNoThrow(try P384.Signing.PublicKey(rawRepresentation: p384KeyKA_raw))
|
||||
XCTAssertNoThrow(try P384.Signing.PublicKey(x963Representation: p384KeyKA_x963))
|
||||
|
||||
XCTAssertNoThrow(try P384.KeyAgreement.PublicKey(compressedRepresentation: p384KeyKA_compressed))
|
||||
XCTAssertThrowsError(try P384.KeyAgreement.PublicKey(compressedRepresentation: p384KeyKA_x963)) { error in
|
||||
XCTAssertTrue(error is CryptoKitError)
|
||||
XCTAssertEqual(error as? CryptoKitError, .incorrectParameterSize)
|
||||
}
|
||||
|
||||
let p521KeyKA = P521.Signing.PrivateKey().publicKey
|
||||
let p521KeyKA_raw = p521KeyKA.rawRepresentation
|
||||
let p521KeyKA_x963 = p521KeyKA.x963Representation
|
||||
let p521KeyKA_compressed = p521KeyKA.compressedRepresentation
|
||||
XCTAssertNoThrow(try P521.Signing.PublicKey(rawRepresentation: p521KeyKA_raw))
|
||||
XCTAssertNoThrow(try P521.Signing.PublicKey(x963Representation: p521KeyKA_x963))
|
||||
|
||||
XCTAssertNoThrow(try P521.KeyAgreement.PublicKey(compressedRepresentation: p521KeyKA_compressed))
|
||||
XCTAssertThrowsError(try P521.KeyAgreement.PublicKey(compressedRepresentation: p521KeyKA_x963)) { error in
|
||||
XCTAssertTrue(error is CryptoKitError)
|
||||
XCTAssertEqual(error as? CryptoKitError, .incorrectParameterSize)
|
||||
}
|
||||
|
||||
let x25519KeyKA = Curve25519.Signing.PrivateKey().publicKey
|
||||
let x25519KeyKA_raw = x25519KeyKA.rawRepresentation
|
||||
XCTAssertNoThrow(try Curve25519.Signing.PublicKey(rawRepresentation: x25519KeyKA_raw))
|
||||
}
|
||||
|
||||
|
||||
func testEncodingsKeyAgreementCompactRepresentation() {
|
||||
let p256KeyKA = P256.KeyAgreement.PrivateKey(compactRepresentable: true).publicKey
|
||||
let p256KeyKA_compact = p256KeyKA.compactRepresentation!
|
||||
XCTAssertNoThrow(try P256.KeyAgreement.PublicKey(compactRepresentation: p256KeyKA_compact))
|
||||
|
||||
|
||||
let p384KeyKA = P384.KeyAgreement.PrivateKey(compactRepresentable: true).publicKey
|
||||
let p384KeyKA_compact = p384KeyKA.compactRepresentation!
|
||||
XCTAssertNoThrow(try P384.KeyAgreement.PublicKey(compactRepresentation: p384KeyKA_compact))
|
||||
|
||||
|
||||
let p521KeyKA = P521.KeyAgreement.PrivateKey(compactRepresentable: true).publicKey
|
||||
let p521KeyKA_compact = p521KeyKA.compactRepresentation!
|
||||
XCTAssertNoThrow(try P521.KeyAgreement.PublicKey(compactRepresentation: p521KeyKA_compact))
|
||||
}
|
||||
|
||||
|
||||
func testEncodingsSigningCompactRepresentation() {
|
||||
let p256KeyKA = P256.Signing.PrivateKey(compactRepresentable: true).publicKey
|
||||
let p256KeyKA_compact = p256KeyKA.compactRepresentation!
|
||||
XCTAssertNoThrow(try P256.Signing.PublicKey(compactRepresentation: p256KeyKA_compact))
|
||||
|
||||
|
||||
let p384KeyKA = P384.Signing.PrivateKey(compactRepresentable: true).publicKey
|
||||
let p384KeyKA_compact = p384KeyKA.compactRepresentation!
|
||||
XCTAssertNoThrow(try P384.Signing.PublicKey(compactRepresentation: p384KeyKA_compact))
|
||||
|
||||
|
||||
let p521KeyKA = P521.Signing.PrivateKey(compactRepresentable: true).publicKey
|
||||
let p521KeyKA_compact = p521KeyKA.compactRepresentation!
|
||||
XCTAssertNoThrow(try P521.Signing.PublicKey(compactRepresentation: p521KeyKA_compact))
|
||||
@@ -1081,5 +1118,16 @@ class ECKeyEncodingsTests: XCTestCase {
|
||||
XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: derPrivateKey))
|
||||
XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: derPrivateKey))
|
||||
}
|
||||
|
||||
func testRejectX963CompressedRepresentation() throws {
|
||||
let privateKey = P256.KeyAgreement.PrivateKey()
|
||||
let publicKey = privateKey.publicKey
|
||||
|
||||
try XCTAssertNoThrow(P256.KeyAgreement.PublicKey(x963Representation: publicKey.x963Representation))
|
||||
try XCTAssertThrowsError(P256.KeyAgreement.PublicKey(x963Representation: publicKey.compressedRepresentation)) { error in
|
||||
XCTAssertTrue(error is CryptoKitError)
|
||||
XCTAssertEqual(error as? CryptoKitError, .incorrectParameterSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
@@ -0,0 +1,196 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
// Skip tests that require @testable imports of CryptoKit.
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@testable import CryptoKit
|
||||
#else
|
||||
@testable import Crypto
|
||||
#endif
|
||||
|
||||
// Curve448 is not supported on our platforms
|
||||
var unsupportedKEMs: [UInt16] = [0x0021]
|
||||
|
||||
struct HPKETestEncryption: Codable {
|
||||
let aad: String
|
||||
let ct: String
|
||||
let nonce: String
|
||||
let pt: String
|
||||
}
|
||||
|
||||
struct HPKETestVector: Codable {
|
||||
let mode: UInt8
|
||||
let kem_id: UInt16
|
||||
let kdf_id: UInt16
|
||||
let aead_id: UInt16
|
||||
|
||||
let info: String
|
||||
let enc: String
|
||||
|
||||
let skEm: String
|
||||
let skRm: String
|
||||
|
||||
let pkEm: String
|
||||
let pkRm: String
|
||||
|
||||
let pkSm: String?
|
||||
|
||||
let psk: String?
|
||||
let psk_id: String?
|
||||
|
||||
let shared_secret: String
|
||||
let secret: String
|
||||
|
||||
let exporter_secret: String
|
||||
|
||||
let encryptions: [HPKETestEncryption]
|
||||
}
|
||||
|
||||
class HPKETestVectors: XCTestCase {
|
||||
|
||||
func testVectors() throws {
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
let bundle = Bundle(for: type(of: self))
|
||||
#else
|
||||
let bundle = Bundle.module
|
||||
#endif
|
||||
let fileURL = bundle.url(forResource: "hpke-test-vectors", withExtension: "json")!
|
||||
let data = try orFail { try Data(contentsOf: fileURL) }
|
||||
let decoder = JSONDecoder()
|
||||
let testVectors = try orFail { try decoder.decode([HPKETestVector].self, from: data) }
|
||||
testVectors.forEach { validateTestVector($0) }
|
||||
}
|
||||
|
||||
func validateTestVector(_ tv: HPKETestVector) {
|
||||
guard let ciphersuite = ciphersuiteFromValues(kemValue: tv.kem_id, kdfValue: tv.kdf_id, aeadValue: tv.aead_id) else {
|
||||
if unsupportedKEMs.contains(tv.kem_id) {
|
||||
print("Skipping unsupported KEM: \(tv.kem_id)")
|
||||
} else {
|
||||
XCTFail("Ciphersuite coulnd't be configured from input values kem:\(tv.kem_id) kdf:\(tv.kdf_id) aead: \(tv.aead_id)")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let skRBytes = try! Data(hexString: tv.skRm)
|
||||
|
||||
switch ciphersuite.kem {
|
||||
case .P256_HKDF_SHA256:
|
||||
XCTAssertNoThrow(try testWithKEM(tv, ciphersuite: ciphersuite, skR: P256.KeyAgreement.PrivateKey(rawRepresentation: skRBytes)))
|
||||
case .P384_HKDF_SHA384:
|
||||
XCTAssertNoThrow(try testWithKEM(tv, ciphersuite: ciphersuite, skR: P384.KeyAgreement.PrivateKey(rawRepresentation: skRBytes)))
|
||||
case .P521_HKDF_SHA512:
|
||||
XCTAssertNoThrow(try testWithKEM(tv, ciphersuite: ciphersuite, skR: P521.KeyAgreement.PrivateKey(rawRepresentation: skRBytes)))
|
||||
case .Curve25519_HKDF_SHA256:
|
||||
XCTAssertNoThrow(try testWithKEM(tv, ciphersuite: ciphersuite, skR: Curve25519.KeyAgreement.PrivateKey(rawRepresentation: skRBytes)))
|
||||
}
|
||||
}
|
||||
|
||||
func testWithKEM<SK: HPKEDiffieHellmanPrivateKey>(_ tv: HPKETestVector, ciphersuite: HPKE.Ciphersuite, skR: SK) throws {
|
||||
let encapsulated = try Data(hexString: tv.enc)
|
||||
|
||||
switch tv.mode {
|
||||
case HPKE.Mode.base.value, HPKE.Mode.psk.value: do {
|
||||
try testUnauthenticatedModesWithKeys(tv, ciphersuite: ciphersuite, skR: skR, encapsulated: encapsulated)
|
||||
}
|
||||
case HPKE.Mode.auth.value, HPKE.Mode.auth_psk.value: do {
|
||||
let pkSBytes = try Data(hexString: tv.pkSm!)
|
||||
let pkS = try SK.PublicKey(pkSBytes, kem: ciphersuite.kem)
|
||||
|
||||
try testAuthenticatedModesWithKeys(tv, ciphersuite: ciphersuite, skR: skR, encapsulated: encapsulated, pkS: pkS)
|
||||
}
|
||||
default:
|
||||
XCTFail("Test vectors contain an unsupported mode.")
|
||||
}
|
||||
}
|
||||
|
||||
func testUnauthenticatedModesWithKeys<PrivateKey: HPKEDiffieHellmanPrivateKey>(_ tv: HPKETestVector, ciphersuite: HPKE.Ciphersuite, skR: PrivateKey, encapsulated: Data) throws {
|
||||
let infoBytes = try Data(hexString: tv.info)
|
||||
|
||||
var recipient: HPKE.Recipient
|
||||
if tv.mode == HPKE.Mode.base.value {
|
||||
print(try skR.publicKey.hpkeRepresentation(kem: ciphersuite.kem).hexString)
|
||||
recipient = try! HPKE.Recipient(privateKey: skR, ciphersuite: ciphersuite, info: infoBytes, encapsulatedKey: encapsulated)
|
||||
} else {
|
||||
let psk = try SymmetricKey(data: Data(hexString: tv.psk!))
|
||||
let psk_id = try Data(hexString: tv.psk_id!)
|
||||
recipient = try! HPKE.Recipient(privateKey: skR, ciphersuite: ciphersuite, info: infoBytes, encapsulatedKey: encapsulated, presharedKey: psk, presharedKeyIdentifier: psk_id)
|
||||
}
|
||||
|
||||
XCTAssertEqual(recipient.exporterSecret.withUnsafeBytes { Data($0) }.hexString, tv.exporter_secret)
|
||||
try testEncryptions(tv.encryptions, with: &recipient)
|
||||
}
|
||||
|
||||
func testAuthenticatedModesWithKeys<SK: HPKEDiffieHellmanPrivateKey>(_ tv: HPKETestVector, ciphersuite: HPKE.Ciphersuite, skR: SK, encapsulated: Data, pkS: SK.PublicKey) throws {
|
||||
let infoBytes = try Data(hexString: tv.info)
|
||||
|
||||
var recipient: HPKE.Recipient
|
||||
if tv.mode == HPKE.Mode.auth.value {
|
||||
recipient = try! HPKE.Recipient(privateKey: skR, ciphersuite: ciphersuite, info: infoBytes, encapsulatedKey: encapsulated, authenticatedBy: pkS)
|
||||
} else {
|
||||
let psk = try SymmetricKey(data: Data(hexString: tv.psk!))
|
||||
let psk_id = try Data(hexString: tv.psk_id!)
|
||||
recipient = try! HPKE.Recipient(privateKey: skR, ciphersuite: ciphersuite, info: infoBytes, encapsulatedKey: encapsulated, authenticatedBy: pkS, presharedKey: psk, presharedKeyIdentifier: psk_id)
|
||||
}
|
||||
|
||||
XCTAssertEqual(recipient.exporterSecret.withUnsafeBytes { Data($0) }.hexString, tv.exporter_secret)
|
||||
try testEncryptions(tv.encryptions, with: &recipient)
|
||||
}
|
||||
|
||||
func testEncryptions(_ encryptions: [HPKETestEncryption], with recipient: inout HPKE.Recipient) throws {
|
||||
for encryption in encryptions {
|
||||
let ct = try Data(hexString: encryption.ct)
|
||||
let aad = try Data(hexString: encryption.aad)
|
||||
let pt = try Data(hexString: encryption.pt)
|
||||
|
||||
XCTAssertEqual(try recipient.open(ct, authenticating: aad), pt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func ciphersuiteFromValues(kemValue: UInt16,
|
||||
kdfValue: UInt16,
|
||||
aeadValue: UInt16) -> HPKE.Ciphersuite? {
|
||||
let kem = kemFromValue(value: kemValue)
|
||||
let kdf = kdfFromValue(value: kdfValue)
|
||||
let aead = aeadFromValue(value: aeadValue)
|
||||
|
||||
if kem != nil && kdf != nil && aead != nil {
|
||||
return HPKE.Ciphersuite(kem: kem!, kdf: kdf!, aead: aead!)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func kemFromValue(value: UInt16) -> HPKE.KEM? {
|
||||
var kemValues = HPKE.KEM.allCases
|
||||
kemValues = kemValues.filter { value == $0.value }
|
||||
return kemValues.first
|
||||
}
|
||||
|
||||
private func kdfFromValue(value: UInt16) -> HPKE.KDF? {
|
||||
var kdfValues = HPKE.KDF.allCases
|
||||
kdfValues = kdfValues.filter { value == $0.value }
|
||||
return kdfValues.first
|
||||
}
|
||||
|
||||
private func aeadFromValue(value: UInt16) -> HPKE.AEAD? {
|
||||
var aeadValues = HPKE.AEAD.allCases
|
||||
aeadValues = aeadValues.filter { value == $0.value }
|
||||
return aeadValues.first
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
@@ -0,0 +1,108 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
// Skip tests that require @testable imports of CryptoKit.
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@testable import CryptoKit
|
||||
#else
|
||||
@testable import Crypto
|
||||
#endif
|
||||
|
||||
class HPKETests: XCTestCase {
|
||||
func testCases() throws {
|
||||
let ciphersuitesToTest = [HPKE.Ciphersuite.P256_SHA256_AES_GCM_256, .P384_SHA384_AES_GCM_256, .P521_SHA512_AES_GCM_256, .Curve25519_SHA256_ChachaPoly]
|
||||
|
||||
for ciphersuite in ciphersuitesToTest {
|
||||
try testCiphersuite(ciphersuite)
|
||||
}
|
||||
}
|
||||
|
||||
func testMismatchedKEM() {
|
||||
let skR = P256.KeyAgreement.PrivateKey()
|
||||
XCTAssertThrowsError(try HPKE.Sender(recipientKey: skR.publicKey, ciphersuite: .P384_SHA384_AES_GCM_256, info: Data()))
|
||||
}
|
||||
|
||||
func testCiphersuite(_ ciphersuite: HPKE.Ciphersuite) throws {
|
||||
switch ciphersuite.kem {
|
||||
case .P256_HKDF_SHA256:
|
||||
try testCiphersuite(ciphersuite, withKeys: P256.KeyAgreement.PrivateKey.self)
|
||||
case .P384_HKDF_SHA384:
|
||||
try testCiphersuite(ciphersuite, withKeys: P384.KeyAgreement.PrivateKey.self)
|
||||
case .P521_HKDF_SHA512:
|
||||
try testCiphersuite(ciphersuite, withKeys: P521.KeyAgreement.PrivateKey.self)
|
||||
case .Curve25519_HKDF_SHA256:
|
||||
try testCiphersuite(ciphersuite, withKeys: Curve25519.KeyAgreement.PrivateKey.self)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func testCiphersuite<SK: HPKEDiffieHellmanPrivateKey>(_ c: HPKE.Ciphersuite, withKeys: SK.Type) throws {
|
||||
let skS = SK.PublicKey.EphemeralPrivateKey()
|
||||
let skR = SK.PublicKey.EphemeralPrivateKey()
|
||||
let info = Data("Some Test Data".utf8)
|
||||
|
||||
let psk = SymmetricKey(size: .bits256)
|
||||
let pskID = Data(SHA256.hash(data: info))
|
||||
|
||||
// Testing base mode
|
||||
var sender = try HPKE.Sender(recipientKey: skR.publicKey, ciphersuite: c, info: info)
|
||||
var recipient = try HPKE.Recipient(privateKey: skR, ciphersuite: c, info: info, encapsulatedKey: sender.encapsulatedKey)
|
||||
XCTAssertNoThrow(try testSenderRecipient(sender: &sender, recipient: &recipient))
|
||||
|
||||
// Testing auth mode
|
||||
sender = try HPKE.Sender(recipientKey: skR.publicKey, ciphersuite: c, info: info, authenticatedBy: skS)
|
||||
recipient = try HPKE.Recipient(privateKey: skR, ciphersuite: c, info: info, encapsulatedKey: sender.encapsulatedKey, authenticatedBy: skS.publicKey)
|
||||
XCTAssertNoThrow(try testSenderRecipient(sender: &sender, recipient: &recipient))
|
||||
|
||||
// Testing psk mode
|
||||
sender = try HPKE.Sender(recipientKey: skR.publicKey, ciphersuite: c, info: info, presharedKey: psk, presharedKeyIdentifier: pskID)
|
||||
recipient = try HPKE.Recipient(privateKey: skR, ciphersuite: c, info: info, encapsulatedKey: sender.encapsulatedKey, presharedKey: psk, presharedKeyIdentifier: pskID)
|
||||
XCTAssertNoThrow(try testSenderRecipient(sender: &sender, recipient: &recipient))
|
||||
|
||||
// Testing auth_psk mod
|
||||
sender = try HPKE.Sender(recipientKey: skR.publicKey, ciphersuite: c, info: info, authenticatedBy: skS, presharedKey: psk, presharedKeyIdentifier: pskID)
|
||||
recipient = try HPKE.Recipient(privateKey: skR, ciphersuite: c, info: info, encapsulatedKey: sender.encapsulatedKey, authenticatedBy: skS.publicKey, presharedKey: psk, presharedKeyIdentifier: pskID)
|
||||
XCTAssertNoThrow(try testSenderRecipient(sender: &sender, recipient: &recipient))
|
||||
}
|
||||
|
||||
func testSenderRecipient(sender: inout HPKE.Sender, recipient: inout HPKE.Recipient) throws {
|
||||
let msg = Data("Some Other Data".utf8)
|
||||
let aad = Data("Some Authenticated Data".utf8)
|
||||
XCTAssertEqual(sender.exporterSecret, recipient.exporterSecret)
|
||||
|
||||
for _ in 0...100 {
|
||||
let ct = try sender.seal(msg, authenticating: msg)
|
||||
let pt = try recipient.open(ct, authenticating: msg)
|
||||
XCTAssertEqual(pt, msg)
|
||||
}
|
||||
|
||||
var ct = try sender.seal(msg, authenticating: aad)
|
||||
XCTAssertEqual(try recipient.open(ct, authenticating: aad), msg)
|
||||
XCTAssertThrowsError(try recipient.open(ct, authenticating: aad))
|
||||
|
||||
ct = try sender.seal(msg, authenticating: aad)
|
||||
XCTAssertEqual(try recipient.open(ct, authenticating: aad), msg)
|
||||
|
||||
let aad2 = Data("inconsistentAAD".utf8)
|
||||
ct = try sender.seal(msg, authenticating: aad2)
|
||||
XCTAssertThrowsError(try recipient.open(ct, authenticating: aad))
|
||||
XCTAssertEqual(try recipient.open(ct, authenticating: aad2), msg)
|
||||
}
|
||||
}
|
||||
|
||||
#endif // CRYPTO_IN_SWIFTPM
|
||||
@@ -0,0 +1 @@
|
||||
[{"mode":0,"kem_id":32,"kdf_id":1,"aead_id":1,"info":"4f6465206f6e2061204772656369616e2055726e","ikmR":"6db9df30aa07dd42ee5e8181afdb977e538f5e1fec8a06223f33f7013e525037","ikmE":"7268600d403fce431561aef583ee1613527cff655c1343f29812e66706df3234","skRm":"4612c550263fc8ad58375df3f557aac531d26850903e55a9f23f21d8534e8ac8","skEm":"52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736","pkRm":"3948cfe0ad1ddb695d780e59077195da6c56506b027329794ab02bca80815c4d","pkEm":"37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431","enc":"37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431","shared_secret":"fe0e18c9f024ce43799ae393c7e8fe8fce9d218875e8227b0187c04e7d2ea1fc","key_schedule_context":"00725611c9d98c07c03f60095cd32d400d8347d45ed67097bbad50fc56da742d07cb6cffde367bb0565ba28bb02c90744a20f5ef37f30523526106f637abb05449","secret":"12fff91991e93b48de37e7daddb52981084bd8aa64289c3788471d9a9712f397","key":"4531685d41d65f03dc48f6b8302c05b0","base_nonce":"56d890e5accaaf011cff4b7d","exporter_secret":"45ff1c2e220db587171952c0592d5f5ebe103f1561a2614e38f2ffd47e99e3f8","encryptions":[{"aad":"436f756e742d30","ct":"f938558b5d72f1a23810b4be2ab4f84331acc02fc97babc53a52ae8218a355a96d8770ac83d07bea87e13c512a","nonce":"56d890e5accaaf011cff4b7d","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d31","ct":"af2d7e9ac9ae7e270f46ba1f975be53c09f8d875bdc8535458c2494e8a6eab251c03d0c22a56b8ca42c2063b84","nonce":"56d890e5accaaf011cff4b7c","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d32","ct":"498dfcabd92e8acedc281e85af1cb4e3e31c7dc394a1ca20e173cb72516491588d96a19ad4a683518973dcc180","nonce":"56d890e5accaaf011cff4b7f","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d33","ct":"6b0f4cd351730cd25993d8ad0f11bff1ef2c3a957cb4d8694bb06c60a2937385da1b47a11595dd7a9a28f76c26","nonce":"56d890e5accaaf011cff4b7e","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d34","ct":"583bd32bc67a5994bb8ceaca813d369bca7b2a42408cddef5e22f880b631215a09fc0012bc69fccaa251c0246d","nonce":"56d890e5accaaf011cff4b79","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d35","ct":"23aff4f784452e70b6c2adc5c84237dae34a91246460f497b753822086fc8ae5fdd770f3c1637086e860535864","nonce":"56d890e5accaaf011cff4b78","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d36","ct":"b101f7842383ab460f22dcf919e4bcc3f1004246db7b64a40e7add713838bda69c601c4287d351fc075de3f965","nonce":"56d890e5accaaf011cff4b7b","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d37","ct":"b46b92359b09f5b77efad33bd96c0068212a7652bb3db182c0e40cac71fdbae0ff213047384c969df46100c3ce","nonce":"56d890e5accaaf011cff4b7a","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d38","ct":"49d450f5d0bdb3d8850cc9fe1ca5ffece5075280d3aea7b1a309d0ef2dbc71f7a3a4e32205e5c53a14ffbd7524","nonce":"56d890e5accaaf011cff4b75","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d39","ct":"2f8a3cbe444213a1fad01ad1b328e464f03edee81243bfdd5f1e67ca41ce14fbb0c00ae9a3f5c4dfe20e1a7bf9","nonce":"56d890e5accaaf011cff4b74","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3130","ct":"f5575c1560c23ba23ea1d919776cbe6e42829097d918dbff28583ecd2bcbbb7fb2a035ea1038eb435812e8bece","nonce":"56d890e5accaaf011cff4b77","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3131","ct":"7809bff8c8f0122f1ac5f179443983ad0486ec3a3420353a6d91eae9ae3dd67f871c99a46054e04b96dd220fe2","nonce":"56d890e5accaaf011cff4b76","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3132","ct":"a5dadd95ac76b59aa9d2cfcace5c19eefa20ea4f9ae98f86bd1373fe19c930c2a9c31ee7fa7f96ff92885dfecf","nonce":"56d890e5accaaf011cff4b71","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3133","ct":"eecfbd7cc0ff49800c25b9dc9f0881893b275b7654c8560048a2a982663ced5860aeecde40e7e99c5512947ec5","nonce":"56d890e5accaaf011cff4b70","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3134","ct":"9325ba3d4ae25b7494432993a1feec051f20d60afe19953c7f41463774b154be00e52fb29e25566a32358fd9d9","nonce":"56d890e5accaaf011cff4b73","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3135","ct":"cb93b418d2070cb290a01565c413fff6f206d70c7e85512c35d109486f8e28950b1951f8d420ff1c58464afbce","nonce":"56d890e5accaaf011cff4b72","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3136","ct":"1d565b4c9b6fae2b7513a5a8ebb5285a8865734ce3f02cd7691449c60b1157c9a5b0d1c4b3ab8bf252a764a4f3","nonce":"56d890e5accaaf011cff4b6d","pt":"4265617574792069732074727574682c20747275746820626561757479"},{"aad":"436f756e742d3137","ct":"a376dd08d1fcfc7d2fcc1bcb519cf9e10b62Line truncated
|
||||
@@ -0,0 +1,47 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
// Skip tests that require @testable imports of CryptoKit.
|
||||
#else
|
||||
#if !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
|
||||
@testable import CryptoKit
|
||||
#else
|
||||
@testable import Crypto
|
||||
#endif
|
||||
|
||||
extension CryptoKitError: Equatable {
|
||||
public static func == (lhs: CryptoKitError, rhs: CryptoKitError) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.incorrectKeySize, .incorrectKeySize):
|
||||
return true
|
||||
case (.incorrectParameterSize, .incorrectParameterSize):
|
||||
return true
|
||||
case (.authenticationFailure, .authenticationFailure):
|
||||
return true
|
||||
case (.wrapFailure, .wrapFailure):
|
||||
return true
|
||||
case (.unwrapFailure, .unwrapFailure):
|
||||
return true
|
||||
case (.underlyingCoreCryptoError(let lhsError), .underlyingCoreCryptoError(let rhsError)):
|
||||
return lhsError == rhsError
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // Linux or !SwiftPM
|
||||
@@ -41,29 +41,9 @@ struct SignatureTestVector: Codable {
|
||||
let tcId: Int
|
||||
}
|
||||
|
||||
struct EdDSATestGroup: Codable {
|
||||
let tests: [SignatureTestVector]
|
||||
let publicKey: EdDSAPublicKey
|
||||
}
|
||||
|
||||
struct EdDSAPublicKey: Codable {
|
||||
let pk: String
|
||||
}
|
||||
|
||||
class SignatureTests: XCTestCase {
|
||||
let data = "Testing Signatures".data(using: String.Encoding.utf8)!
|
||||
|
||||
func testWycheproofEdDSA() throws {
|
||||
try orFail {
|
||||
try wycheproofTest(
|
||||
bundleType: self,
|
||||
jsonName: "ed25519_test",
|
||||
testFunction: { (group: EdDSATestGroup) in
|
||||
try orFail { try testEdGroup(group: group) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testWycheproofP256DER() throws {
|
||||
try orFail {
|
||||
try wycheproofTest(
|
||||
@@ -113,7 +93,7 @@ class SignatureTests: XCTestCase {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testWycheproofP256P1363() throws {
|
||||
try orFail {
|
||||
try wycheproofTest(
|
||||
@@ -123,7 +103,7 @@ class SignatureTests: XCTestCase {
|
||||
try orFail { try testGroup(group: group, curve: P256.Signing.self, hashFunction: SHA256.self, deserializeSignature: P256.Signing.ECDSASignature.init(rawRepresentation:)) }
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
try orFail {
|
||||
try wycheproofTest(
|
||||
bundleType: self,
|
||||
@@ -133,7 +113,7 @@ class SignatureTests: XCTestCase {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testWycheproofP384P1363() throws {
|
||||
try orFail {
|
||||
try wycheproofTest(
|
||||
@@ -152,7 +132,7 @@ class SignatureTests: XCTestCase {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testWycheproofP521P1363() throws {
|
||||
try orFail {
|
||||
try wycheproofTest(
|
||||
@@ -164,41 +144,6 @@ class SignatureTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testEdGroup(group: EdDSATestGroup, file: StaticString = #file, line: UInt = #line) throws {
|
||||
let keyBytes = try orFail { try Array(hexString: group.publicKey.pk) }
|
||||
let key = try orFail { try Curve25519.Signing.PublicKey(rawRepresentation: keyBytes) }
|
||||
|
||||
for testVector in group.tests {
|
||||
var isValid = false
|
||||
|
||||
do {
|
||||
let sig = try Data(hexString: testVector.sig)
|
||||
|
||||
let msg: Data
|
||||
if testVector.msg.count > 0 {
|
||||
msg = try Data(hexString: testVector.msg)
|
||||
} else {
|
||||
msg = Data()
|
||||
}
|
||||
|
||||
isValid = key.isValidSignature(sig, for: msg)
|
||||
} catch {
|
||||
XCTAssert(testVector.result == "invalid" || testVector.result == "acceptable", "Test ID: \(testVector.tcId) is valid, but failed \(error.localizedDescription).")
|
||||
continue
|
||||
}
|
||||
|
||||
switch testVector.result {
|
||||
case "valid": XCTAssert(isValid, "Test vector is valid, but is rejected \(testVector.tcId)")
|
||||
case "acceptable": do {
|
||||
XCTAssert(isValid)
|
||||
}
|
||||
case "invalid": XCTAssert(!isValid, "Test ID: \(testVector.tcId) is valid, but failed.")
|
||||
default:
|
||||
XCTFail("Unhandled test vector")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testGroup<C: NISTSigning, HF: HashFunction>(group: ECDSATestGroup, curve: C.Type, hashFunction: HF.Type, deserializeSignature: (Data) throws -> C.ECDSASignature, file: StaticString = #file, line: UInt = #line) throws where C.ECDSASignature == C.PublicKey.Signature {
|
||||
let keyBytes = try orFail(file: file, line: line) { try Array(hexString: group.publicKey.uncompressed) }
|
||||
let key = try orFail(file: file, line: line) { try C.PublicKey(x963Representation: keyBytes) }
|
||||
|
||||
+65
-1
@@ -21,7 +21,25 @@ import CryptoKit
|
||||
import Crypto
|
||||
#endif
|
||||
|
||||
class EdDSATests: XCTestCase {
|
||||
struct Ed25519TestGroup: Codable {
|
||||
let tests: [Ed25519TestVector]
|
||||
let publicKey: Ed25519PublicKey
|
||||
}
|
||||
|
||||
struct Ed25519PublicKey: Codable {
|
||||
let pk: String
|
||||
}
|
||||
|
||||
struct Ed25519TestVector: Codable {
|
||||
let comment: String
|
||||
let msg: String
|
||||
let sig: String
|
||||
let result: String
|
||||
let flags: [String]
|
||||
let tcId: Int
|
||||
}
|
||||
|
||||
class Ed25519Tests: XCTestCase {
|
||||
func testExample() throws {
|
||||
let privateKey = Curve25519.Signing.PrivateKey()
|
||||
let publicKey = privateKey.publicKey
|
||||
@@ -75,4 +93,50 @@ class EdDSATests: XCTestCase {
|
||||
// This signature should be invalid
|
||||
XCTAssertFalse(privateKey.publicKey.isValidSignature(DispatchData.empty, for: DispatchData.empty))
|
||||
}
|
||||
|
||||
func testWycheProof() throws {
|
||||
try orFail {
|
||||
try wycheproofTest(
|
||||
bundleType: self,
|
||||
jsonName: "ed25519_test",
|
||||
testFunction: { (group: Ed25519TestGroup) in
|
||||
try orFail { try testGroup(group: group) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testGroup(group: Ed25519TestGroup, file: StaticString = #file, line: UInt = #line) throws {
|
||||
let keyBytes = try orFail { try Array(hexString: group.publicKey.pk) }
|
||||
let key = try orFail { try Curve25519.Signing.PublicKey(rawRepresentation: keyBytes) }
|
||||
|
||||
for testVector in group.tests {
|
||||
var isValid = false
|
||||
|
||||
do {
|
||||
let sig = try Data(hexString: testVector.sig)
|
||||
|
||||
let msg: Data
|
||||
if testVector.msg.count > 0 {
|
||||
msg = try Data(hexString: testVector.msg)
|
||||
} else {
|
||||
msg = Data()
|
||||
}
|
||||
|
||||
isValid = key.isValidSignature(sig, for: msg)
|
||||
} catch {
|
||||
XCTAssert(testVector.result == "invalid" || testVector.result == "acceptable", "Test ID: \(testVector.tcId) is valid, but failed \(error.localizedDescription).")
|
||||
continue
|
||||
}
|
||||
|
||||
switch testVector.result {
|
||||
case "valid": XCTAssert(isValid, "Test vector is valid, but is rejected \(testVector.tcId)")
|
||||
case "acceptable": do {
|
||||
XCTAssert(isValid)
|
||||
}
|
||||
case "invalid": XCTAssert(!isValid, "Test ID: \(testVector.tcId) is valid, but failed.")
|
||||
default:
|
||||
XCTFail("Unhandled test vector")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ struct AESGCMTestVector: Codable {
|
||||
let result: String
|
||||
}
|
||||
|
||||
class AESGCMSIVTests: XCTestCase {
|
||||
final class AESGCMSIVTests: XCTestCase {
|
||||
func testPropertiesStayTheSameAfterFailedOpening() throws {
|
||||
let message = Data("this is a message".utf8)
|
||||
let sealed = try AES.GCM._SIV.seal(message, using: SymmetricKey(size: .bits128))
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2023 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Crypto
|
||||
import Foundation
|
||||
import _CryptoExtras
|
||||
import XCTest
|
||||
|
||||
final class CBCTests: XCTestCase {
|
||||
func testWycheproofDecrypt() throws {
|
||||
try wycheproofTest(
|
||||
jsonName: "aes_cbc_pkcs5_test",
|
||||
testFunction: { (group: AESCBCTestGroup) in
|
||||
for test in group.tests {
|
||||
do {
|
||||
let decrypted = try AES._CBC.decrypt(
|
||||
test.computedCt, using: test.computedKey, iv: test.computedIv
|
||||
)
|
||||
|
||||
switch test.result {
|
||||
case "valid":
|
||||
XCTAssertTrue(decrypted == test.computedMsg, "Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
case "invalid":
|
||||
XCTAssertFalse(decrypted != test.computedMsg, "Unexpected valid test \(test.tcId) (\(test.comment))")
|
||||
default:
|
||||
fatalError("Unexpected result type")
|
||||
}
|
||||
} catch {
|
||||
XCTAssertTrue(test.result == "invalid", "Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func testWycheproofEncrypt() throws {
|
||||
try wycheproofTest(
|
||||
jsonName: "aes_cbc_pkcs5_test",
|
||||
testFunction: { (group: AESCBCTestGroup) in
|
||||
for test in group.tests {
|
||||
if test.result == "invalid" { continue }
|
||||
|
||||
do {
|
||||
let encrypted = try AES._CBC.encrypt(
|
||||
test.computedMsg, using: test.computedKey, iv: test.computedIv
|
||||
)
|
||||
XCTAssertEqual(encrypted, test.computedCt, "Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
} catch {
|
||||
XCTFail("Unexpected invalid test \(test.tcId) (\(test.comment))")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct AESCBCTestGroup: Codable {
|
||||
var keySize: Int
|
||||
var ivSize: Int
|
||||
var type: String
|
||||
var tests: [AESCBCTest]
|
||||
}
|
||||
|
||||
struct AESCBCTest: Codable {
|
||||
var tcId: Int
|
||||
var comment: String
|
||||
var key: String
|
||||
var msg: String
|
||||
var iv: String
|
||||
var ct: String
|
||||
var result: String
|
||||
var flags: [String]
|
||||
|
||||
var computedKey: SymmetricKey {
|
||||
SymmetricKey(hexEncoded: self.key)
|
||||
}
|
||||
|
||||
var computedMsg: Data {
|
||||
try! Data(hexString: self.msg)
|
||||
}
|
||||
|
||||
var computedIv: AES._CBC.IV {
|
||||
try! AES._CBC.IV(ivBytes: Array(hexString: self.iv))
|
||||
}
|
||||
|
||||
var computedCt: Data {
|
||||
try! Data(hexString: self.ct)
|
||||
}
|
||||
}
|
||||
|
||||
extension SymmetricKey {
|
||||
init(hexEncoded: String) {
|
||||
let keyBytes = try! Array(hexString: hexEncoded)
|
||||
self = SymmetricKey(data: keyBytes)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,21 +0,0 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-crypto:20.04-5.6
|
||||
build:
|
||||
args:
|
||||
ubuntu_version: "focal"
|
||||
swift_version: "5.6"
|
||||
|
||||
test:
|
||||
image: swift-crypto:20.04-5.6
|
||||
environment: []
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
cmake:
|
||||
image: swift-crypto:20.04-5.6
|
||||
|
||||
shell:
|
||||
image: swift-crypto:20.04-5.6
|
||||
@@ -0,0 +1,21 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
|
||||
runtime-setup:
|
||||
image: swift-crypto:22.04-5.10
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-5.10-jammy"
|
||||
|
||||
test:
|
||||
image: swift-crypto:22.04-5.10
|
||||
environment:
|
||||
- IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error
|
||||
#- SANITIZER_ARG=--sanitize=thread
|
||||
|
||||
cmake:
|
||||
image: swift-crypto:22.04-5.10
|
||||
|
||||
shell:
|
||||
image: swift-crypto:22.04-5.10
|
||||
@@ -6,7 +6,8 @@ services:
|
||||
image: swift-crypto:22.04-5.9
|
||||
build:
|
||||
args:
|
||||
base_image: "swiftlang/swift:nightly-5.9-jammy"
|
||||
ubuntu_version: "jammy"
|
||||
swift_version: "5.9"
|
||||
|
||||
test:
|
||||
image: swift-crypto:22.04-5.9
|
||||
|
||||
Reference in new issue
Block a user