From 22fd38919566816705c57d5f4dd5a97a4edcf25e Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Wed, 9 Jun 2021 09:51:01 +0100 Subject: [PATCH] Update to CryptoKit 2021 API (#86) This patch adds Crypto support for new API added in CryptoKit during the summer releases of 2021. --- .../Basic ASN1 Types/ArraySliceBigint.swift | 3 +- Sources/Crypto/CMakeLists.txt | 2 + Sources/Crypto/CryptoKitErrors.swift | 4 + Sources/Crypto/Key Agreement/DH.swift | 4 + Sources/Crypto/Key Wrapping/AESWrap.swift | 50 ++++++++ .../BoringSSL/AESWrap_boring.swift | 119 ++++++++++++++++++ .../HMAC/HMAC.swift | 4 + Sources/Crypto/Signatures/ECDSA.swift | 24 ++++ Sources/Crypto/Signatures/ECDSA.swift.gyb | 8 ++ Sources/Crypto/Util/SecureBytes.swift | 4 +- .../AES-GCM-Runner.swift | 17 +++ .../Key Wrapping/KeyWrapping.swift | 98 +++++++++++++++ Tests/CryptoTests/Utils/BytesUtil.swift | 2 +- 13 files changed, 335 insertions(+), 4 deletions(-) create mode 100644 Sources/Crypto/Key Wrapping/AESWrap.swift create mode 100644 Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift create mode 100644 Tests/CryptoTests/Key Wrapping/KeyWrapping.swift diff --git a/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift b/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift index fda1b8e3..12620795 100644 --- a/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift +++ b/Sources/Crypto/ASN1/Basic ASN1 Types/ArraySliceBigint.swift @@ -34,4 +34,5 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 { return try body(self) } } -#endif + +#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/CMakeLists.txt b/Sources/Crypto/CMakeLists.txt index be6451ec..46e7d772 100644 --- a/Sources/Crypto/CMakeLists.txt +++ b/Sources/Crypto/CMakeLists.txt @@ -43,6 +43,8 @@ add_library(Crypto "Key Agreement/DH.swift" "Key Agreement/ECDH.swift" "Key Derivation/HKDF.swift" + "Key Wrapping/AESWrap.swift" + "Key Wrapping/BoringSSL/AESWrap_boring.swift" "Keys/EC/BoringSSL/Ed25519_boring.swift" "Keys/EC/BoringSSL/EllipticCurvePoint_boring.swift" "Keys/EC/BoringSSL/EllipticCurve_boring.swift" diff --git a/Sources/Crypto/CryptoKitErrors.swift b/Sources/Crypto/CryptoKitErrors.swift index c8943b7d..bd1bf3ed 100644 --- a/Sources/Crypto/CryptoKitErrors.swift +++ b/Sources/Crypto/CryptoKitErrors.swift @@ -19,11 +19,15 @@ /// - 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 occured. +/// - wrapFailure: Failed to wrap key +/// - unwrapFailure: Failed to unwrap key public enum CryptoKitError: Error { case incorrectKeySize case incorrectParameterSize case authenticationFailure case underlyingCoreCryptoError(error: Int32) + case wrapFailure + case unwrapFailure } /// Errors encountered when parsing ASN.1 formatted keys. diff --git a/Sources/Crypto/Key Agreement/DH.swift b/Sources/Crypto/Key Agreement/DH.swift index 1e33ee90..5fa9eb8e 100644 --- a/Sources/Crypto/Key Agreement/DH.swift +++ b/Sources/Crypto/Key Agreement/DH.swift @@ -108,7 +108,11 @@ public struct SharedSecret: ContiguousBytes { /// - outputByteCount: The length in bytes of resulting symmetric key. /// - Returns: The derived symmetric key public func hkdfDerivedSymmetricKey(using hashFunction: H.Type, salt: Salt, sharedInfo: SI, outputByteCount: Int) -> SymmetricKey { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else return HKDF.deriveKey(inputKeyMaterial: SymmetricKey(data: ss), salt: salt, info: sharedInfo, outputByteCount: outputByteCount) + #endif } } diff --git a/Sources/Crypto/Key Wrapping/AESWrap.swift b/Sources/Crypto/Key Wrapping/AESWrap.swift new file mode 100644 index 00000000..f0d12e09 --- /dev/null +++ b/Sources/Crypto/Key Wrapping/AESWrap.swift @@ -0,0 +1,50 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2021 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 (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +@_exported import CryptoKit +#else +import Foundation + +#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +typealias AESWRAPImpl = CoreCryptoAESWRAPImpl +#else +typealias AESWRAPImpl = BoringSSLAESWRAPImpl +#endif + +extension AES { + /// The Key Wrapping module provides AES Key Wrapping, according to the IETF RFC 3394 specification. + public enum KeyWrap { + /// Wraps a key with AES wrap (RFC 3394), according to the IETF RFC 3394 specification. + /// + /// - Parameters: + /// - 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. + /// + /// - Parameters: + /// - wrappedKey: The wrapped key + /// - kek: The key encryption key + /// - Returns: The unwrapped key, the method will throw if the payload was incorrectly wrapped. + public static func unwrap(_ wrappedKey: WrappedKey, using kek: SymmetricKey) throws -> SymmetricKey { + return try AESWRAPImpl.unwrap(key: kek, wrappedKey: wrappedKey) + } + } +} + +#endif // Linux or !SwiftPM diff --git a/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift b/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift new file mode 100644 index 00000000..333bcb70 --- /dev/null +++ b/Sources/Crypto/Key Wrapping/BoringSSL/AESWrap_boring.swift @@ -0,0 +1,119 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 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 (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +@_exported import CryptoKit +#else +@_implementationOnly import CCryptoBoringSSL +import Foundation + +enum BoringSSLAESWRAPImpl { + static func wrap(key: SymmetricKey, keyToWrap: SymmetricKey) throws -> Data { + // There's a flat 8-byte overhead to AES KeyWrap. + var output = Data(repeating: 0, count: keyToWrap.byteCount + 8) + + let rc = try key.withUnsafeAESKEY(mode: .encrypting) { aesKey in + output.withUnsafeMutableBytes { outputPtr -> CInt in + // Memory bind is safe: we cannot alias the pointer here. + let outputPtr = outputPtr.bindMemory(to: UInt8.self) + return keyToWrap.withUnsafeBytes { keyToWrapPtr -> CInt in + // Memory bind is safe: we cannot alias the pointer here. + let keyToWrapPtr = keyToWrapPtr.bindMemory(to: UInt8.self) + return CCryptoBoringSSL_AES_wrap_key( + aesKey, nil, outputPtr.baseAddress, keyToWrapPtr.baseAddress, keyToWrapPtr.count + ) + } + } + } + + guard rc >= 0 else { + throw CryptoKitError.internalBoringSSLError() + } + + // Assert our 8-byte overhead story was true. + assert(rc == keyToWrap.byteCount + 8) + return output.prefix(Int(rc)) + } + + static func unwrap(key: SymmetricKey, wrappedKey: WrappedKey) throws -> SymmetricKey { + if wrappedKey.regions.count == 1 { + return try self.unwrap(key: key, contiguousWrappedKey: wrappedKey.regions.first!) + } else { + let contiguous = Data(wrappedKey) + return try self.unwrap(key: key, contiguousWrappedKey: contiguous) + } + } + + private static func unwrap(key: SymmetricKey, contiguousWrappedKey: WrappedKey) throws -> SymmetricKey { + let unwrapped = try contiguousWrappedKey.withUnsafeBytes { inPtr in + try [UInt8](unsafeUninitializedCapacity: inPtr.count) { outputPtr, count in + // Bind is safe: we cannot violate the aliasing rules here as we never call to arbitrary code. + let inPtr = inPtr.bindMemory(to: UInt8.self) + let rc = try key.withUnsafeAESKEY(mode: .decrypting) { aesKey in + CCryptoBoringSSL_AES_unwrap_key( + aesKey, nil, outputPtr.baseAddress, inPtr.baseAddress, inPtr.count + ) + } + + guard rc > 0 else { + throw CryptoKitError.internalBoringSSLError() + } + + // Assert our 8-byte overhead story is true. + assert(rc == inPtr.count - 8) + count = Int(rc) + } + } + + return SymmetricKey(data: unwrapped) + } +} + +extension SymmetricKey { + fileprivate enum AESKeyMode { + case encrypting + case decrypting + } + + fileprivate func withUnsafeAESKEY(mode: AESKeyMode, _ body: (UnsafePointer) throws -> ResultType) throws -> ResultType { + try self.withUnsafeBytes { bytesPointer in + // Bind is safe: cannot alias the pointer here. + let bytesPointer = bytesPointer.bindMemory(to: UInt8.self) + + var aesKey = AES_KEY() + let bitsInKey = UInt32(bytesPointer.count * 8) + let rc: CInt + + switch mode { + case .encrypting: + rc = CCryptoBoringSSL_AES_set_encrypt_key( + bytesPointer.baseAddress!, bitsInKey, &aesKey + ) + case .decrypting: + rc = CCryptoBoringSSL_AES_set_decrypt_key( + bytesPointer.baseAddress!, bitsInKey, &aesKey + ) + } + + guard rc == 0 else { + throw CryptoKitError.internalBoringSSLError() + } + + return try withUnsafePointer(to: aesKey) { + return try body($0) + } + } + } +} + +#endif // (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API diff --git a/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift b/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift index 002f1e4f..3c8ece74 100644 --- a/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift +++ b/Sources/Crypto/Message Authentication Codes/HMAC/HMAC.swift @@ -39,6 +39,9 @@ public struct HMAC: MACAlgorithm { /// /// - Parameter key: The key to use for HMAC. public init(key: SymmetricKey) { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else var K: ContiguousBytes if key.byteCount == H.blockByteCount { @@ -75,6 +78,7 @@ public struct HMAC: MACAlgorithm { }) } outerHasher.update(data: outerKey) + #endif } /// Computes a Message Authentication Code. diff --git a/Sources/Crypto/Signatures/ECDSA.swift b/Sources/Crypto/Signatures/ECDSA.swift index 52908625..0ed4836f 100644 --- a/Sources/Crypto/Signatures/ECDSA.swift +++ b/Sources/Crypto/Signatures/ECDSA.swift @@ -68,6 +68,9 @@ extension P256.Signing { /// Initializes ECDSASignature from the DER representation. public init(derRepresentation: D) throws { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let parsed = try ASN1.parse(Array(derRepresentation)) let signature = try ASN1.ECDSASignature>(asn1Encoded: parsed) @@ -87,6 +90,7 @@ extension P256.Signing { raw.append(contentsOf: signature.s) self.rawRepresentation = raw + #endif } public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { @@ -95,6 +99,9 @@ extension P256.Signing { /// A DER-encoded representation of the signature public var derRepresentation: Data { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let raw = rawRepresentation let half = raw.count / 2 let r = Array(raw.prefix(upTo: half))[...] @@ -104,6 +111,7 @@ extension P256.Signing { var serializer = ASN1.Serializer() try! serializer.serialize(sig) return Data(serializer.serializedBytes) + #endif } } } @@ -202,6 +210,9 @@ extension P384.Signing { /// Initializes ECDSASignature from the DER representation. public init(derRepresentation: D) throws { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let parsed = try ASN1.parse(Array(derRepresentation)) let signature = try ASN1.ECDSASignature>(asn1Encoded: parsed) @@ -221,6 +232,7 @@ extension P384.Signing { raw.append(contentsOf: signature.s) self.rawRepresentation = raw + #endif } public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { @@ -229,6 +241,9 @@ extension P384.Signing { /// A DER-encoded representation of the signature public var derRepresentation: Data { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let raw = rawRepresentation let half = raw.count / 2 let r = Array(raw.prefix(upTo: half))[...] @@ -238,6 +253,7 @@ extension P384.Signing { var serializer = ASN1.Serializer() try! serializer.serialize(sig) return Data(serializer.serializedBytes) + #endif } } } @@ -336,6 +352,9 @@ extension P521.Signing { /// Initializes ECDSASignature from the DER representation. public init(derRepresentation: D) throws { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let parsed = try ASN1.parse(Array(derRepresentation)) let signature = try ASN1.ECDSASignature>(asn1Encoded: parsed) @@ -355,6 +374,7 @@ extension P521.Signing { raw.append(contentsOf: signature.s) self.rawRepresentation = raw + #endif } public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { @@ -363,6 +383,9 @@ extension P521.Signing { /// A DER-encoded representation of the signature public var derRepresentation: Data { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let raw = rawRepresentation let half = raw.count / 2 let r = Array(raw.prefix(upTo: half))[...] @@ -372,6 +395,7 @@ extension P521.Signing { var serializer = ASN1.Serializer() try! serializer.serialize(sig) return Data(serializer.serializedBytes) + #endif } } } diff --git a/Sources/Crypto/Signatures/ECDSA.swift.gyb b/Sources/Crypto/Signatures/ECDSA.swift.gyb index 1b7271af..8f58e407 100644 --- a/Sources/Crypto/Signatures/ECDSA.swift.gyb +++ b/Sources/Crypto/Signatures/ECDSA.swift.gyb @@ -76,6 +76,9 @@ extension ${CURVE}.Signing { /// Initializes ECDSASignature from the DER representation. public init(derRepresentation: D) throws { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let parsed = try ASN1.parse(Array(derRepresentation)) let signature = try ASN1.ECDSASignature>(asn1Encoded: parsed) @@ -95,6 +98,7 @@ extension ${CURVE}.Signing { raw.append(contentsOf: signature.s) self.rawRepresentation = raw + #endif } public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { @@ -103,6 +107,9 @@ extension ${CURVE}.Signing { /// A DER-encoded representation of the signature public var derRepresentation: Data { + #if os(iOS) && (arch(arm) || arch(i386)) + fatalError("Unsupported architecture") + #else let raw = rawRepresentation let half = raw.count / 2 let r = Array(raw.prefix(upTo: half))[...] @@ -112,6 +119,7 @@ extension ${CURVE}.Signing { var serializer = ASN1.Serializer() try! serializer.serialize(sig) return Data(serializer.serializedBytes) + #endif } } } diff --git a/Sources/Crypto/Util/SecureBytes.swift b/Sources/Crypto/Util/SecureBytes.swift index 9e65c9d2..5c0805bc 100644 --- a/Sources/Crypto/Util/SecureBytes.swift +++ b/Sources/Crypto/Util/SecureBytes.swift @@ -280,11 +280,11 @@ extension SecureBytes { @usableFromInline subscript(offset offset: Int) -> UInt8 { get { - //precondition(offset >= 0 && offset < self.count) + // precondition(offset >= 0 && offset < self.count) return self.withUnsafeMutablePointerToElements { return ($0 + offset).pointee } } set { - //precondition(offset >= 0 && offset < self.count) + // precondition(offset >= 0 && offset < self.count) return self.withUnsafeMutablePointerToElements { ($0 + offset).pointee = newValue } } } diff --git a/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift b/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift index 4c41116d..bf5358a1 100644 --- a/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift +++ b/Tests/CryptoTests/Authenticated Encryption/AES-GCM-Runner.swift @@ -41,6 +41,23 @@ struct AESGCMTestVector: Codable { } class AESGCMTests: XCTestCase { + func testPropertiesStayTheSameAfterFailedOpening() throws { + let message = Data("this is a message".utf8) + let sealed = try AES.GCM.seal(message, using: SymmetricKey(size: .bits128)) + + // We copy the bytes of these fields out here to ensure they're saved. + let originalCiphertext = Array(sealed.ciphertext) + let originalNonce = Array(sealed.nonce) + let originalTag = Array(sealed.tag) + + XCTAssertThrowsError(try AES.GCM.open(sealed, using: SymmetricKey(size: .bits128))) + + // The fields must all be unchanged. + XCTAssertEqual(originalCiphertext, Array(sealed.ciphertext)) + XCTAssertEqual(originalNonce, Array(sealed.nonce)) + XCTAssertEqual(originalTag, Array(sealed.tag)) + } + func testBadKeySize() { let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)! let key = SymmetricKey(size: .init(bitCount: 304)) diff --git a/Tests/CryptoTests/Key Wrapping/KeyWrapping.swift b/Tests/CryptoTests/Key Wrapping/KeyWrapping.swift new file mode 100644 index 00000000..4457da6e --- /dev/null +++ b/Tests/CryptoTests/Key Wrapping/KeyWrapping.swift @@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// 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 XCTest + +#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +// Skip tests that require @testable imports of CryptoKit. +#else +#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API +@testable import CryptoKit +#else +@testable import Crypto +#endif + +class KeyWrappingTests: XCTestCase { + func testAESWrapTestVectors() throws { + struct wrapVector { + let kek: SymmetricKey + let key: SymmetricKey + let wrap: Data + } + + let vector: [wrapVector] = [ + // Corecrypto Test Vector + wrapVector(kek: try SymmetricKey(data: Data(hexString: "f59782f1dceb0544a8da06b34969b9212b55ce6dcbdd0975a33f4b3f88b538da")), + key: try SymmetricKey(data: Data(hexString: "73d33060b5f9f2eb5785c0703ddfa704")), + wrap: try Data(hexString: "2e63946ea3c090902fa1558375fdb2907742ac74e39403fc")), + // IETF Test Vector - Wrap 128 bits of Key Data with a 128-bit KEK + wrapVector(kek: try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F")), + key: try SymmetricKey(data: Data(hexString: "00112233445566778899AABBCCDDEEFF")), + wrap: try Data(hexString: "1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5")), + // IETF Test Vector - Wrap 128 bits of Key Data with a 192-bit KEK + wrapVector(kek: try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F1011121314151617")), + key: try SymmetricKey(data: Data(hexString: "00112233445566778899AABBCCDDEEFF")), + wrap: try Data(hexString: "96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D")), + // IETF Test Vector - Wrap 128 bits of Key Data with a 256-bit KEK + wrapVector(kek: try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")), + key: try SymmetricKey(data: Data(hexString: "00112233445566778899AABBCCDDEEFF")), + wrap: try Data(hexString: "64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7")), + // IETF Test Vector - Wrap 192 bits of Key Data with a 192-bit KEK + wrapVector(kek: try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F1011121314151617")), + key: try SymmetricKey(data: Data(hexString: "00112233445566778899AABBCCDDEEFF0001020304050607")), + wrap: try Data(hexString: "031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2")), + // IETF Test Vector - Wrap 192 bits of Key Data with a 256-bit KEK + wrapVector(kek: try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")), + key: try SymmetricKey(data: Data(hexString: "00112233445566778899AABBCCDDEEFF0001020304050607")), + wrap: try Data(hexString: "A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1")), + // IETF Test Vector - Wrap 256 bits of Key Data with a 256-bit KEK + wrapVector(kek: try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")), + key: try SymmetricKey(data: Data(hexString: "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F")), + wrap: try Data(hexString: "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21")) + ] + + try vector.forEach { e in + let kek = SymmetricKey(data: e.kek) + var wrapped = try AES.KeyWrap.wrap(e.key, using: kek) + XCTAssertEqual(e.wrap, wrapped) + let unwrapped = try AES.KeyWrap.unwrap(wrapped, using: kek) + XCTAssertEqual(e.key, unwrapped) + + wrapped[0] = wrapped[0] ^ 1 + + XCTAssertThrowsError(try AES.KeyWrap.unwrap(wrapped, using: kek)) + } + } + + func testWrappingAndUnwrappingEmptinessFails() throws { + let kek = try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")) + let key = SymmetricKey(data: Data()) + + XCTAssertThrowsError(try AES.KeyWrap.wrap(key, using: kek)) + + let zeroLengthUnwrapped = Data() + XCTAssertThrowsError(try AES.KeyWrap.unwrap(zeroLengthUnwrapped, using: kek)) + } + + func testWrappingUnwrappingWithTheEmptyKeyFails() throws { + let kek = SymmetricKey(data: Data()) + let key = try SymmetricKey(data: Data(hexString: "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")) + + XCTAssertThrowsError(try AES.KeyWrap.wrap(key, using: kek)) + + let wrappedKey = try Data(hexString: "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21") + XCTAssertThrowsError(try AES.KeyWrap.unwrap(wrappedKey, using: kek)) + } +} + +#endif // (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM diff --git a/Tests/CryptoTests/Utils/BytesUtil.swift b/Tests/CryptoTests/Utils/BytesUtil.swift index d29f2189..e242f4d3 100644 --- a/Tests/CryptoTests/Utils/BytesUtil.swift +++ b/Tests/CryptoTests/Utils/BytesUtil.swift @@ -84,7 +84,7 @@ extension Data { throw ByteHexEncodingErrors.incorrectString } - let stringBytes: [UInt8] = Array(hexString.data(using: String.Encoding.utf8)!) + let stringBytes: [UInt8] = Array(hexString.lowercased().data(using: String.Encoding.utf8)!) for i in 0...((hexString.count / 2) - 1) { let char1 = stringBytes[2 * i]