mirror of
https://github.com/apple/swift-crypto
synced 2026-11-22 04:30:39 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8fad2f95a | ||
|
|
6ff0a3b147 | ||
|
|
ab0beab369 | ||
|
|
57de8e7cb8 | ||
|
|
6a032cf17d | ||
|
|
404c818e35 | ||
|
|
47df2f1f6d | ||
|
|
c2cbadd726 |
No files matched your search
@@ -14,6 +14,7 @@ jobs:
|
||||
with:
|
||||
license_header_check_project_name: "SwiftCrypto"
|
||||
docs_check_enabled: false
|
||||
format_check_container_image: "swift:latest"
|
||||
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
|
||||
@@ -21,7 +21,7 @@ import FoundationEssentials
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
let benchmarks = {
|
||||
let benchmarks: @Sendable () -> Void = {
|
||||
let defaultMetrics: [BenchmarkMetric] = [.mallocCountTotal, .cpuTotal]
|
||||
|
||||
Benchmark(
|
||||
@@ -208,4 +208,145 @@ let benchmarks = {
|
||||
blackHole(try key1.sharedSecretFromKeyAgreement(with: key2.publicKey))
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"hmac-sha256-authenticate",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .mega,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 5
|
||||
)
|
||||
) { benchmark in
|
||||
let key = SymmetricKey(size: .bits256)
|
||||
let message = Data(repeating: 0x41, count: 1024)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(HMAC<SHA256>.authenticationCode(for: message, using: key))
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"hkdf-sha256-derive",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 10
|
||||
)
|
||||
) { benchmark in
|
||||
let inputKeyMaterial = SymmetricKey(size: .bits256)
|
||||
let salt = Data("benchmark salt".utf8)
|
||||
let info = Data("benchmark info".utf8)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(
|
||||
HKDF<SHA256>.deriveKey(
|
||||
inputKeyMaterial: inputKeyMaterial,
|
||||
salt: salt,
|
||||
info: info,
|
||||
outputByteCount: 1024
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"aes-keywrap-unwrap",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .mega,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 5
|
||||
)
|
||||
) { benchmark in
|
||||
let kek = SymmetricKey(size: .bits256)
|
||||
let wrapped = try AES.KeyWrap.wrap(SymmetricKey(size: .bits256), using: kek)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(try AES.KeyWrap.unwrap(wrapped, using: kek))
|
||||
}
|
||||
}
|
||||
|
||||
if #available(macOS 26.0, *) {
|
||||
Benchmark(
|
||||
"mlkem768-decapsulate",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 10
|
||||
)
|
||||
) { benchmark in
|
||||
let privateKey = try MLKEM768.PrivateKey()
|
||||
let encapsulated = try privateKey.publicKey.encapsulate().encapsulated
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(try privateKey.decapsulate(encapsulated))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"pbkdf2-sha256-derive",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 10
|
||||
)
|
||||
) { benchmark in
|
||||
let password = Data("benchmark password".utf8)
|
||||
let salt = Data("benchmark salt".utf8)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(
|
||||
try KDF.Insecure.PBKDF2.deriveKey(
|
||||
from: password,
|
||||
salt: salt,
|
||||
using: .sha256,
|
||||
outputByteCount: 32,
|
||||
unsafeUncheckedRounds: 1_000
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Benchmark(
|
||||
"scrypt-derive",
|
||||
configuration: Benchmark.Configuration(
|
||||
metrics: defaultMetrics,
|
||||
scalingFactor: .kilo,
|
||||
maxDuration: .seconds(10_000_000),
|
||||
maxIterations: 3
|
||||
)
|
||||
) { benchmark in
|
||||
let password = Data("benchmark password".utf8)
|
||||
let salt = Data("benchmark salt".utf8)
|
||||
|
||||
benchmark.startMeasurement()
|
||||
|
||||
for _ in benchmark.scaledIterations {
|
||||
blackHole(
|
||||
try KDF.Scrypt.deriveKey(
|
||||
from: password,
|
||||
salt: salt,
|
||||
outputByteCount: 32,
|
||||
rounds: 1 << 10,
|
||||
blockSize: 8,
|
||||
parallelism: 1
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,6 +98,7 @@ add_library(Crypto
|
||||
"Signatures/MLDSA.swift"
|
||||
"Signatures/Signature.swift"
|
||||
"Util/ArraySpanHelpers.swift"
|
||||
"Util/Backports.swift"
|
||||
"Util/BoringSSL/CryptoKitErrors_boring.swift"
|
||||
"Util/BoringSSL/InlineArray+withBytes_boring.swift"
|
||||
"Util/BoringSSL/Optional+withUnsafeBytes_boring.swift"
|
||||
|
||||
@@ -33,7 +33,6 @@ import Foundation
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768 {
|
||||
/// A ML-KEM-768 private key.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
|
||||
private var backing: Backing
|
||||
|
||||
@@ -150,14 +149,14 @@ extension MLKEM768 {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
||||
|
||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
||||
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||
symmetricKeyDataPtr,
|
||||
count in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM768_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
@@ -165,13 +164,13 @@ extension MLKEM768 {
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
return SymmetricKey(data: symmetricKeyData)
|
||||
count = MLKEM.sharedSecretByteCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,7 +179,6 @@ extension MLKEM768 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM768 {
|
||||
/// A ML-KEM-768 public key.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
|
||||
private var backing: Backing
|
||||
|
||||
@@ -302,7 +300,6 @@ extension MLKEM768 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024 {
|
||||
/// A ML-KEM-1024 private key.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct InternalPrivateKey: @unchecked Sendable, KEMPrivateKey {
|
||||
private var backing: Backing
|
||||
|
||||
@@ -419,14 +416,14 @@ extension MLKEM1024 {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
||||
|
||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
||||
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||
symmetricKeyDataPtr,
|
||||
count in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM1024_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
@@ -434,13 +431,13 @@ extension MLKEM1024 {
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
return SymmetricKey(data: symmetricKeyData)
|
||||
count = MLKEM.sharedSecretByteCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -449,7 +446,6 @@ extension MLKEM1024 {
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
extension MLKEM1024 {
|
||||
/// A ML-KEM-1024 public key.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
struct InternalPublicKey: @unchecked Sendable, KEMPublicKey {
|
||||
private var backing: Backing
|
||||
|
||||
@@ -568,7 +564,6 @@ extension MLKEM1024 {
|
||||
private static let ciphertextByteCount = Int(MLKEM1024_CIPHERTEXT_BYTES)
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
enum MLKEM {
|
||||
/// The size of the seed in bytes.
|
||||
static let seedByteCount = 64
|
||||
|
||||
@@ -153,14 +153,14 @@ extension MLKEM${parameter_set} {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var symmetricKeyData = Data(repeating: 0, count: MLKEM.sharedSecretByteCount)
|
||||
|
||||
let rc: CInt = symmetricKeyData.withUnsafeMutableBytes { symmetricKeyDataPtr in
|
||||
return try SymmetricKey(unsafeUninitializedCapacity: MLKEM.sharedSecretByteCount) {
|
||||
symmetricKeyDataPtr,
|
||||
count in
|
||||
let bytes: ContiguousBytes =
|
||||
encapsulated.regions.count == 1
|
||||
? encapsulated.regions.first!
|
||||
: Array(encapsulated)
|
||||
return bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
let rc: CInt = bytes.withUnsafeBytes { encapsulatedPtr in
|
||||
CCryptoBoringSSL_MLKEM${parameter_set}_decap(
|
||||
symmetricKeyDataPtr.baseAddress,
|
||||
encapsulatedPtr.baseAddress,
|
||||
@@ -168,13 +168,13 @@ extension MLKEM${parameter_set} {
|
||||
&self.key
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
guard rc == 1 else {
|
||||
throw CryptoKitError.internalBoringSSLError()
|
||||
}
|
||||
|
||||
return SymmetricKey(data: symmetricKeyData)
|
||||
count = MLKEM.sharedSecretByteCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,6 +189,9 @@ extension P256 {
|
||||
self = try .init(rawRepresentation: parsed.privateKey)
|
||||
case "PRIVATE KEY":
|
||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||
guard parsed.algorithm == .ecdsaP256 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
@@ -209,6 +212,9 @@ extension P256 {
|
||||
|
||||
do {
|
||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||
guard key.algorithm == .ecdsaP256 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||
} catch {
|
||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||
@@ -413,6 +419,9 @@ extension P256 {
|
||||
self = try .init(rawRepresentation: parsed.privateKey)
|
||||
case "PRIVATE KEY":
|
||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||
guard parsed.algorithm == .ecdsaP256 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
@@ -433,6 +442,9 @@ extension P256 {
|
||||
|
||||
do {
|
||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||
guard key.algorithm == .ecdsaP256 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||
} catch {
|
||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||
@@ -636,6 +648,9 @@ extension P384 {
|
||||
self = try .init(rawRepresentation: parsed.privateKey)
|
||||
case "PRIVATE KEY":
|
||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||
guard parsed.algorithm == .ecdsaP384 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
@@ -656,6 +671,9 @@ extension P384 {
|
||||
|
||||
do {
|
||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||
guard key.algorithm == .ecdsaP384 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||
} catch {
|
||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||
@@ -860,6 +878,9 @@ extension P384 {
|
||||
self = try .init(rawRepresentation: parsed.privateKey)
|
||||
case "PRIVATE KEY":
|
||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||
guard parsed.algorithm == .ecdsaP384 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
@@ -880,6 +901,9 @@ extension P384 {
|
||||
|
||||
do {
|
||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||
guard key.algorithm == .ecdsaP384 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||
} catch {
|
||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||
@@ -1083,6 +1107,9 @@ extension P521 {
|
||||
self = try .init(rawRepresentation: parsed.privateKey)
|
||||
case "PRIVATE KEY":
|
||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||
guard parsed.algorithm == .ecdsaP521 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
@@ -1103,6 +1130,9 @@ extension P521 {
|
||||
|
||||
do {
|
||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||
guard key.algorithm == .ecdsaP521 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||
} catch {
|
||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||
@@ -1307,6 +1337,9 @@ extension P521 {
|
||||
self = try .init(rawRepresentation: parsed.privateKey)
|
||||
case "PRIVATE KEY":
|
||||
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
|
||||
guard parsed.algorithm == .ecdsaP521 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
|
||||
default:
|
||||
throw CryptoKitASN1Error.invalidPEMDocument
|
||||
@@ -1327,6 +1360,9 @@ extension P521 {
|
||||
|
||||
do {
|
||||
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
|
||||
guard key.algorithm == .ecdsaP521 else {
|
||||
throw CryptoKitASN1Error.invalidASN1Object
|
||||
}
|
||||
self = try .init(rawRepresentation: key.privateKey.privateKey)
|
||||
} catch {
|
||||
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
|
||||
|
||||
@@ -72,8 +72,8 @@ enum BoringSSLAESWRAPImpl {
|
||||
key: SymmetricKey,
|
||||
contiguousWrappedKey: WrappedKey
|
||||
) throws -> SymmetricKey {
|
||||
let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in
|
||||
try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
|
||||
try contiguousWrappedKey.withUnsafeBytes { inPtr in
|
||||
try SymmetricKey(unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in
|
||||
let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in
|
||||
CCryptoBoringSSL_AES_unwrap_key(
|
||||
aesKey,
|
||||
@@ -93,8 +93,6 @@ enum BoringSSLAESWRAPImpl {
|
||||
count = Int(rc)
|
||||
}
|
||||
}
|
||||
|
||||
return SymmetricKey(data: unwrapped)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,34 +65,24 @@ public struct HMAC<H: HashFunction>: MACAlgorithm, Sendable {
|
||||
#if os(iOS) && (arch(arm) || arch(i386))
|
||||
fatalError("Unsupported architecture")
|
||||
#else
|
||||
var innerKey = SecureBytes(capacity: H.blockByteCount) { keyOutput in
|
||||
if key.byteCount <= keyOutput.freeCapacity {
|
||||
keyOutput.append(contentsOf: key.bytes)
|
||||
} else if key.byteCount > H.blockByteCount {
|
||||
let hash = H.hash(bytes: key.bytes)
|
||||
hash.withUnsafeBytes {
|
||||
keyOutput.append(contentsOf: $0.bytes)
|
||||
}
|
||||
}
|
||||
keyOutput.append(repeating: 0, count: keyOutput.freeCapacity, as: UInt8.self)
|
||||
}
|
||||
var outerKey = innerKey
|
||||
|
||||
// HMAC(K, m) = H((K0 ^ opad) || H((K0 ^ ipad) || m)), where K0 is the
|
||||
// key normalized to the hash block size (RFC 2104).
|
||||
self.innerHasher = H()
|
||||
innerKey.withUnsafeMutableBytes {
|
||||
for i in 0 ..< $0.count {
|
||||
$0[i] ^= 0x36
|
||||
}
|
||||
}
|
||||
innerHasher.update(bytes: innerKey.bytes)
|
||||
|
||||
self.outerHasher = H()
|
||||
outerKey.withUnsafeMutableBytes {
|
||||
for i in 0 ..< $0.count {
|
||||
$0[i] ^= 0x5c
|
||||
withTemporaryZeroingAllocation(byteCount: H.blockByteCount, alignment: 1) { keyBlock in
|
||||
if key.byteCount <= keyBlock.freeCapacity {
|
||||
keyBlock.append(contentsOf: key.bytes)
|
||||
} else if key.byteCount > H.blockByteCount {
|
||||
H.hash(bytes: key.bytes).withBytes { keyBlock.append(contentsOf: $0) }
|
||||
}
|
||||
keyBlock.append(repeating: 0, count: keyBlock.freeCapacity, as: UInt8.self)
|
||||
|
||||
var k0 = keyBlock.mutableBytes
|
||||
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 } // apply ipad
|
||||
self.innerHasher.update(bytes: k0.bytes)
|
||||
for i in 0 ..< k0.byteCount { k0[i] ^= 0x36 ^ 0x5c } // undo ipad, apply opad
|
||||
self.outerHasher.update(bytes: k0.bytes)
|
||||
}
|
||||
outerHasher.update(data: outerKey)
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2026 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
#if compiler(<6.4)
|
||||
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
|
||||
extension ContiguousBytes {
|
||||
func withBytes<R>(_ body: (RawSpan) throws -> R) rethrows -> R {
|
||||
try withUnsafeBytes { try body(RawSpan(_unsafeBytes: $0)) }
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
|
||||
extension MutableRawSpan {
|
||||
subscript(_ byteOffset: Int) -> UInt8 {
|
||||
get { unsafeLoad(fromByteOffset: byteOffset, as: UInt8.self) }
|
||||
@_lifetime(self: copy self)
|
||||
set { storeBytes(of: newValue, toByteOffset: byteOffset, as: UInt8.self) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -28,7 +28,7 @@ protocol Zeroization {
|
||||
extension UnsafeMutablePointer: Zeroization {
|
||||
/// Zeroizes the pointee
|
||||
func zeroize() {
|
||||
let size = MemoryLayout.size(ofValue: Pointee.self)
|
||||
let size = MemoryLayout<Pointee>.size
|
||||
memset_s(self, size, 0, size)
|
||||
}
|
||||
}
|
||||
@@ -54,4 +54,26 @@ extension Data: Zeroization {
|
||||
}
|
||||
}
|
||||
|
||||
func withUnsafeTemporaryZeroingAllocation<R>(
|
||||
byteCount: Int,
|
||||
alignment: Int,
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in
|
||||
defer { buffer.zeroize() }
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
func withTemporaryZeroingAllocation<R>(
|
||||
byteCount: Int,
|
||||
alignment: Int,
|
||||
_ body: (inout OutputRawSpan) throws -> R
|
||||
) rethrows -> R {
|
||||
try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in
|
||||
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
|
||||
return try body(&output)
|
||||
}
|
||||
}
|
||||
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -77,10 +77,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.multiply(by: rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
@usableFromInline
|
||||
package consuming func multiplying(
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
@@ -90,18 +86,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.multiply(by: rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#else
|
||||
@usableFromInline
|
||||
package func multiplying(
|
||||
by rhs: ArbitraryPrecisionInteger,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
var `self` = self
|
||||
try self.multiply(by: rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#endif
|
||||
|
||||
@usableFromInline
|
||||
package static func multiplying(
|
||||
@@ -134,10 +118,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.add(rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
@usableFromInline
|
||||
package consuming func adding(
|
||||
_ rhs: consuming EllipticCurvePoint,
|
||||
@@ -147,23 +127,7 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.add(rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#else
|
||||
@usableFromInline
|
||||
package func adding(
|
||||
_ rhs: consuming EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
var `self` = self
|
||||
try self.add(rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#endif
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
@usableFromInline
|
||||
package static func adding(
|
||||
_ lhs: consuming EllipticCurvePoint,
|
||||
@@ -174,19 +138,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try lhs.add(rhs, on: group, context: context)
|
||||
return lhs
|
||||
}
|
||||
#else
|
||||
@usableFromInline
|
||||
package static func adding(
|
||||
_ lhs: EllipticCurvePoint,
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
var lhs = lhs
|
||||
try lhs.add(rhs, on: group, context: context)
|
||||
return lhs
|
||||
}
|
||||
#endif
|
||||
|
||||
@usableFromInline
|
||||
package mutating func invert(
|
||||
@@ -207,10 +158,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.invert(on: group, context: context)
|
||||
}
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
@usableFromInline
|
||||
package consuming func inverting(
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
@@ -219,22 +166,7 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.invert(on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#else
|
||||
@usableFromInline
|
||||
package func inverting(
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
var `self` = self
|
||||
try self.invert(on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#endif
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
@usableFromInline
|
||||
package static func inverting(
|
||||
_ point: consuming EllipticCurvePoint,
|
||||
@@ -244,18 +176,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try point.invert(on: group, context: context)
|
||||
return point
|
||||
}
|
||||
#else
|
||||
@usableFromInline
|
||||
package static func inverting(
|
||||
_ point: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
var point = point
|
||||
try point.invert(on: group, context: context)
|
||||
return point
|
||||
}
|
||||
#endif
|
||||
|
||||
@usableFromInline
|
||||
package mutating func subtract(
|
||||
@@ -278,10 +198,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.subtract(rhs, on: group, context: context)
|
||||
}
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
@usableFromInline
|
||||
package consuming func subtracting(
|
||||
_ rhs: consuming EllipticCurvePoint,
|
||||
@@ -291,23 +207,7 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try self.subtract(rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#else
|
||||
@usableFromInline
|
||||
package func subtracting(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
var `self` = self
|
||||
try self.subtract(rhs, on: group, context: context)
|
||||
return self
|
||||
}
|
||||
#endif
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
@usableFromInline
|
||||
package static func subtracting(
|
||||
_ rhs: consuming EllipticCurvePoint,
|
||||
@@ -318,19 +218,6 @@ package struct EllipticCurvePoint: @unchecked Sendable {
|
||||
try lhs.subtract(rhs, on: group, context: context)
|
||||
return lhs
|
||||
}
|
||||
#else
|
||||
@usableFromInline
|
||||
package static func subtracting(
|
||||
_ rhs: EllipticCurvePoint,
|
||||
from lhs: EllipticCurvePoint,
|
||||
on group: BoringSSLEllipticCurveGroup,
|
||||
context: FiniteFieldArithmeticContext? = nil
|
||||
) throws -> EllipticCurvePoint {
|
||||
var lhs = lhs
|
||||
try lhs.subtract(rhs, on: group, context: context)
|
||||
return lhs
|
||||
}
|
||||
#endif
|
||||
|
||||
@usableFromInline
|
||||
package init<MessageBytes: ContiguousBytes, DSTBytes: ContiguousBytes>(
|
||||
|
||||
@@ -71,10 +71,6 @@ extension AES {
|
||||
self.backing.update(bufferPointer)
|
||||
}
|
||||
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
/// Finalizes the message authentication computation and returns the
|
||||
/// computed code.
|
||||
///
|
||||
@@ -87,16 +83,6 @@ extension AES {
|
||||
self.cowIfNeeded()
|
||||
return self.backing.finalize()
|
||||
}
|
||||
#else
|
||||
/// Finalizes the message authentication computation and returns the
|
||||
/// computed code.
|
||||
///
|
||||
/// - Returns: The message authentication code.
|
||||
public func finalize() -> AES.CMAC.MAC {
|
||||
var `self` = self
|
||||
return self.backing.finalize()
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Updates the MAC with data.
|
||||
///
|
||||
|
||||
@@ -78,6 +78,7 @@ add_library(CryptoExtras
|
||||
"Util/ThreadSpecific/ThreadPosix.swift"
|
||||
"Util/ThreadSpecific/ThreadSpecific.swift"
|
||||
"Util/ThreadSpecific/ThreadWindows.swift"
|
||||
"Util/Zeroization.swift"
|
||||
"ZKPs/DLEQ.swift"
|
||||
"ZKPs/Prover.swift"
|
||||
"ZKPs/Verifier.swift"
|
||||
|
||||
@@ -72,16 +72,3 @@ final class BoringSSLSHA512256Context {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutablePointer {
|
||||
fileprivate func zeroize() {
|
||||
let size = MemoryLayout.size(ofValue: Pointee.self)
|
||||
memset_s(self, size, 0, size)
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawBufferPointer {
|
||||
fileprivate func zeroize() {
|
||||
memset_s(self.baseAddress!, self.count, 0, self.count)
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,9 @@ internal struct BoringSSLPBKDF2 {
|
||||
outputByteCount: Int,
|
||||
rounds: Int
|
||||
) throws -> SymmetricKey {
|
||||
// This should be SecureBytes, but we can't use that here.
|
||||
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
|
||||
var derivedKeyData = Data(count: outputByteCount)
|
||||
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
|
||||
|
||||
let rc = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
|
||||
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
|
||||
|
||||
@@ -39,8 +39,9 @@ internal struct CommonCryptoPBKDF2 {
|
||||
outputByteCount: Int,
|
||||
rounds: Int
|
||||
) throws -> SymmetricKey {
|
||||
// This should be SecureBytes, but we can't use that here.
|
||||
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
|
||||
var derivedKeyData = Data(count: outputByteCount)
|
||||
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
|
||||
|
||||
let derivationStatus = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes -> Int32 in
|
||||
let saltBytes: ContiguousBytes = salt.regions.count == 1 ? salt.regions.first! : Array(salt)
|
||||
|
||||
@@ -81,8 +81,9 @@ internal struct BoringSSLScrypt {
|
||||
parallelism: Int,
|
||||
maxMemory: Int? = nil
|
||||
) throws -> SymmetricKey {
|
||||
// This should be SecureBytes, but we can't use that here.
|
||||
// SecureBytes is internal to Crypto, so zero the buffer by hand once the key has been copied out.
|
||||
var derivedKeyData = Data(count: outputByteCount)
|
||||
defer { derivedKeyData.withUnsafeMutableBytes { $0.zeroize() } }
|
||||
|
||||
// This computes the maximum amount of memory that will be used by the scrypt algorithm with an additional memory page to spare. This value will be used by the BoringSSL as the memory limit for the algorithm.
|
||||
// An additional memory page is added to the computed value (using POSIX specification) to ensure that the memory limit is not too tight.
|
||||
|
||||
@@ -35,6 +35,9 @@ extension P384 {
|
||||
|
||||
static var ciphersuite: Ciphersuite { Ciphersuite(H2G.self) }
|
||||
|
||||
/// The maximum length, in bytes, of an input, imposed by the two-byte length prefix in the RFC 9497 framing.
|
||||
static let maximumInputByteCount = 0xFFFF
|
||||
|
||||
/// A P-384 public key used to blind inputs and finalize blinded elements.
|
||||
public struct PublicKey {
|
||||
fileprivate typealias BackingPublicKey = P384.Signing.PublicKey
|
||||
@@ -367,6 +370,9 @@ extension P384._VOPRF {
|
||||
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
|
||||
extension P384._VOPRF.PublicKey {
|
||||
internal func blind<D: DataProtocol>(_ input: D, with fixedBlind: P384._VOPRF.H2G.G.Scalar) throws -> P384._VOPRF.BlindedInput {
|
||||
guard input.count <= P384._VOPRF.maximumInputByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
let input = Data(input)
|
||||
let (blind, blindedElement) = Self.client.blindMessage(input, blind: fixedBlind)
|
||||
return P384._VOPRF.BlindedInput(
|
||||
@@ -436,6 +442,9 @@ extension P384._VOPRF.PrivateKey {
|
||||
///
|
||||
/// - Seealso: [RFC 9497: VOPRF Protocol - Evaluate]( https://cfrg.github.io/draft-irtf-cfrg-voprf/draft-irtf-cfrg-voprf.html#section-3.3.2-7).
|
||||
public func evaluate<D: DataProtocol>(_ input: D) throws -> Data {
|
||||
guard input.count <= P384._VOPRF.maximumInputByteCount else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
let inputElement = P384._VOPRF.H2G.hashToGroup(
|
||||
Data(input),
|
||||
domainSeparationString: Self.hashToGroupDST
|
||||
|
||||
@@ -530,7 +530,7 @@ extension _RSA.Signing {
|
||||
extension _RSA.Encryption {
|
||||
/// Identical to ``_RSA/Signing/PublicKey``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PublicKey {
|
||||
public struct PublicKey: Sendable {
|
||||
public struct Primitives: Sendable, Hashable {
|
||||
public var modulus: Data
|
||||
public var publicExponent: Data
|
||||
@@ -612,7 +612,7 @@ extension _RSA.Encryption {
|
||||
|
||||
/// Identical to ``_RSA/Signing/PrivateKey``.
|
||||
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
|
||||
public struct PrivateKey {
|
||||
public struct PrivateKey: Sendable {
|
||||
private var backing: BackingPrivateKey
|
||||
|
||||
/// Construct an RSA private key from a PEM representation.
|
||||
|
||||
@@ -19,14 +19,9 @@ import Foundation
|
||||
#endif
|
||||
|
||||
extension Data {
|
||||
// This enhancement can only be present on 6.1 or later because of the
|
||||
// absence of https://github.com/swiftlang/swift/pull/76186 in older
|
||||
// compilers.
|
||||
#if compiler(>=6.1)
|
||||
// This overload reduces allocations when used in a chain of infix operations.
|
||||
static func + (lhs: consuming Data, rhs: consuming Data) -> Data {
|
||||
lhs.append(contentsOf: rhs)
|
||||
return lhs
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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.txt for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if canImport(FoundationEssentials)
|
||||
import FoundationEssentials
|
||||
#else
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
protocol Zeroization {
|
||||
mutating func zeroize()
|
||||
}
|
||||
|
||||
extension UnsafeMutablePointer: Zeroization {
|
||||
/// Zeroizes the pointee
|
||||
func zeroize() {
|
||||
let size = MemoryLayout<Pointee>.size
|
||||
memset_s(self, size, 0, size)
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
memset_s(&self, self.count, 0, self.count)
|
||||
}
|
||||
}
|
||||
|
||||
extension Data: Zeroization {
|
||||
internal mutating func zeroize() {
|
||||
_ = self.withUnsafeMutableBytes {
|
||||
memset_s($0.baseAddress!, $0.count, 0, $0.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func withUnsafeTemporaryZeroingAllocation<R>(
|
||||
byteCount: Int,
|
||||
alignment: Int,
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws -> R
|
||||
) rethrows -> R {
|
||||
try withUnsafeTemporaryAllocation(byteCount: byteCount, alignment: alignment) { buffer in
|
||||
defer { buffer.zeroize() }
|
||||
return try body(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
|
||||
func withTemporaryZeroingAllocation<R>(
|
||||
byteCount: Int,
|
||||
alignment: Int,
|
||||
_ body: (inout OutputRawSpan) throws -> R
|
||||
) rethrows -> R {
|
||||
try withUnsafeTemporaryZeroingAllocation(byteCount: byteCount, alignment: alignment) { buffer in
|
||||
var output = OutputRawSpan(buffer: buffer, initializedCount: 0)
|
||||
return try body(&output)
|
||||
}
|
||||
}
|
||||
@@ -325,28 +325,3 @@ extension P384._ARCV1: ARCV1 {}
|
||||
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
|
||||
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
|
||||
extension P384: ARCCurve {}
|
||||
|
||||
|
||||
// Swift 5.10 compiler needs a little more help to infer the conformances.
|
||||
#if swift(<6.0)
|
||||
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
|
||||
fileprivate extension P256._ARCV1.PrivateKey {
|
||||
typealias H2G = P256._ARCV1.H2G
|
||||
typealias Credential = P256._ARCV1.Credential
|
||||
typealias PublicKey = P256._ARCV1.PublicKey
|
||||
typealias CredentialRequest = P256._ARCV1.CredentialRequest
|
||||
typealias CredentialResponse = P256._ARCV1.CredentialResponse
|
||||
typealias Presentation = P256._ARCV1.Presentation
|
||||
}
|
||||
|
||||
@available(*, deprecated, message: "ARC(P-384) has been removed from the IETF draft; use ARC(P-256) instead.")
|
||||
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
|
||||
fileprivate extension P384._ARCV1.PrivateKey {
|
||||
typealias H2G = P384._ARCV1.H2G
|
||||
typealias Credential = P384._ARCV1.Credential
|
||||
typealias PublicKey = P384._ARCV1.PublicKey
|
||||
typealias CredentialRequest = P384._ARCV1.CredentialRequest
|
||||
typealias CredentialResponse = P384._ARCV1.CredentialResponse
|
||||
typealias Presentation = P384._ARCV1.Presentation
|
||||
}
|
||||
#endif
|
||||
@@ -96,4 +96,21 @@ final class VOPRFPublicAPITests: XCTestCase {
|
||||
|
||||
XCTAssertThrowsError(try P384._VOPRF.BlindedElement(oprfRepresentation: uncompressed))
|
||||
}
|
||||
|
||||
func testInputLongerThanRFC9497LimitThrows() throws {
|
||||
let privateKey = P384._VOPRF.PrivateKey()
|
||||
let publicKey = privateKey.publicKey
|
||||
|
||||
// RFC 9497 caps inputs at 2^16 - 1 bytes, the most the two-byte length prefix in the framing can encode.
|
||||
let maximumInput = Data(repeating: 0x41, count: 0xFFFF)
|
||||
let blindedInput = try publicKey.blind(maximumInput)
|
||||
let blindEvaluation = try privateKey.evaluate(blindedInput.blindedElement)
|
||||
XCTAssertNoThrow(try publicKey.finalize(blindedInput, using: blindEvaluation))
|
||||
XCTAssertNoThrow(try privateKey.evaluate(maximumInput))
|
||||
|
||||
// Oversized inputs are rejected where they enter, so finalize can never be given one.
|
||||
let oversizedInput = Data(repeating: 0x41, count: 0x1_0000)
|
||||
XCTAssertThrowsError(try publicKey.blind(oversizedInput))
|
||||
XCTAssertThrowsError(try privateKey.evaluate(oversizedInput))
|
||||
}
|
||||
}
|
||||
@@ -248,6 +248,13 @@ final class TestRSAEncryption: XCTestCase {
|
||||
XCTAssertEqual(191, publicKey.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
|
||||
}
|
||||
|
||||
func testKeysAreSendable() {
|
||||
func assertSendable<T: Sendable>(_: T.Type) {}
|
||||
|
||||
assertSendable(_RSA.Encryption.PublicKey.self)
|
||||
assertSendable(_RSA.Encryption.PrivateKey.self)
|
||||
}
|
||||
|
||||
func testPKCS1() throws {
|
||||
let pubKeyPEM = """
|
||||
-----BEGIN RSA PUBLIC KEY-----
|
||||
|
||||
@@ -219,6 +219,43 @@ class ASN1Tests: XCTestCase {
|
||||
XCTAssertEqual(serializer.serializedBytes, decodedPrivateKey)
|
||||
}
|
||||
|
||||
func testPKCS8PrivateKeyWithMismatchedCurveIsRejected() throws {
|
||||
func pkcs8(_ algorithm: ASN1.RFC5480AlgorithmIdentifier, _ privateKey: Data, _ publicKey: Data) throws -> (der: Data, pem: String) {
|
||||
let pkey = ASN1.PKCS8PrivateKey(algorithm: algorithm, privateKey: Array(privateKey), publicKey: Array(publicKey))
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(pkey)
|
||||
let der = Data(serializer.serializedBytes)
|
||||
return (der, ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: der).pemString)
|
||||
}
|
||||
|
||||
let p256 = P256.Signing.PrivateKey()
|
||||
let p384 = P384.Signing.PrivateKey()
|
||||
let p521 = P521.Signing.PrivateKey()
|
||||
|
||||
let p256InP384 = try pkcs8(.ecdsaP384, p256.rawRepresentation, p256.publicKey.x963Representation)
|
||||
XCTAssertThrowsError(try P256.Signing.PrivateKey(derRepresentation: p256InP384.der))
|
||||
XCTAssertThrowsError(try P256.Signing.PrivateKey(pemRepresentation: p256InP384.pem))
|
||||
XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(derRepresentation: p256InP384.der))
|
||||
XCTAssertThrowsError(try P256.KeyAgreement.PrivateKey(pemRepresentation: p256InP384.pem))
|
||||
|
||||
let p384InP521 = try pkcs8(.ecdsaP521, p384.rawRepresentation, p384.publicKey.x963Representation)
|
||||
XCTAssertThrowsError(try P384.Signing.PrivateKey(derRepresentation: p384InP521.der))
|
||||
XCTAssertThrowsError(try P384.Signing.PrivateKey(pemRepresentation: p384InP521.pem))
|
||||
XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(derRepresentation: p384InP521.der))
|
||||
XCTAssertThrowsError(try P384.KeyAgreement.PrivateKey(pemRepresentation: p384InP521.pem))
|
||||
|
||||
let p521InP256 = try pkcs8(.ecdsaP256, p521.rawRepresentation, p521.publicKey.x963Representation)
|
||||
XCTAssertThrowsError(try P521.Signing.PrivateKey(derRepresentation: p521InP256.der))
|
||||
XCTAssertThrowsError(try P521.Signing.PrivateKey(pemRepresentation: p521InP256.pem))
|
||||
XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(derRepresentation: p521InP256.der))
|
||||
XCTAssertThrowsError(try P521.KeyAgreement.PrivateKey(pemRepresentation: p521InP256.pem))
|
||||
|
||||
// The correctly labelled encodings still load.
|
||||
let p256InP256 = try pkcs8(.ecdsaP256, p256.rawRepresentation, p256.publicKey.x963Representation)
|
||||
XCTAssertEqual(try P256.Signing.PrivateKey(derRepresentation: p256InP256.der).rawRepresentation, p256.rawRepresentation)
|
||||
XCTAssertEqual(try P256.KeyAgreement.PrivateKey(pemRepresentation: p256InP256.pem).rawRepresentation, p256.rawRepresentation)
|
||||
}
|
||||
|
||||
func testRejectDripFedASN1SPKIP256() throws {
|
||||
// This test drip-feeds an ASN.1 P256 SPKI block. It should never parse correctly until we feed the entire block.
|
||||
let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ=="
|
||||
|
||||
@@ -217,6 +217,12 @@ final class SecureBytesTests: XCTestCase {
|
||||
XCTAssertEqual(base.count, 22)
|
||||
XCTAssertEqual(Array(copy), [0, 1, 2, 3, 4])
|
||||
}
|
||||
|
||||
func testZeroizePointerToMultiWordValueClearsAllBytes() {
|
||||
var value: (UInt64, UInt64, UInt64, UInt64) = (1, 2, 3, 4)
|
||||
withUnsafeMutablePointer(to: &value) { $0.zeroize() }
|
||||
XCTAssertEqual(withUnsafeBytes(of: value) { Array($0) }, Array(repeating: UInt8(0), count: 32))
|
||||
}
|
||||
}
|
||||
|
||||
#endif // canImport(CryptoKit)
|
||||
@@ -34,7 +34,6 @@ struct RFCVectorDecoder {
|
||||
for _ in 0..<3 {
|
||||
fileURL!.deleteLastPathComponent()
|
||||
}
|
||||
#if compiler(>=6.0)
|
||||
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
|
||||
fileURL!.append(path: "Test Vectors", directoryHint: .isDirectory)
|
||||
fileURL!.append(path: "\(fileName).txt", directoryHint: .notDirectory)
|
||||
@@ -42,10 +41,6 @@ struct RFCVectorDecoder {
|
||||
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
|
||||
}
|
||||
#else
|
||||
fileURL! = fileURL!.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL! = fileURL!.appendingPathComponent("\(fileName).txt", isDirectory: false)
|
||||
#endif
|
||||
|
||||
let rfcVectorData = try Data(contentsOf: fileURL!)
|
||||
self.rfcVectorData = String(decoding: rfcVectorData, as: Unicode.UTF8.self)
|
||||
|
||||
@@ -26,7 +26,6 @@ extension XCTestCase {
|
||||
for _ in 0..<3 {
|
||||
fileURL.deleteLastPathComponent()
|
||||
}
|
||||
#if compiler(>=6.0)
|
||||
if #available(macOS 13, iOS 16, watchOS 9, tvOS 16, visionOS 1, macCatalyst 16, *) {
|
||||
fileURL.append(path: "Test Vectors", directoryHint: .isDirectory)
|
||||
fileURL.append(path: "\(jsonName).json", directoryHint: .notDirectory)
|
||||
@@ -34,10 +33,6 @@ extension XCTestCase {
|
||||
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
|
||||
}
|
||||
#else
|
||||
fileURL = fileURL.appendingPathComponent("Test Vectors", isDirectory: true)
|
||||
fileURL = fileURL.appendingPathComponent("\(jsonName).json", isDirectory: false)
|
||||
#endif
|
||||
|
||||
let data = try orFail(file: file, line: line) { try Data(contentsOf: unwrap(fileURL, file: file, line: line)) }
|
||||
|
||||
|
||||
Reference in new issue
Block a user