Update to CryptoKit 2021 API (#86)

This patch adds Crypto support for new API added in CryptoKit during the
summer releases of 2021.
This commit is contained in:
Cory Benfield authored and GitHub committed 2021-06-09 09:51:01 +01:00
1 parent 01c3fdfb85
commit 22fd389195
13 files changed
+335 -4

No files matched your search

@@ -34,4 +34,5 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
return try body(self)
}
}
#endif
#endif // Linux or !SwiftPM
+2
View File
@@ -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"
+4
View File
@@ -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.
+4
View File
@@ -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<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")
#else
return HKDF<H>.deriveKey(inputKeyMaterial: SymmetricKey(data: ss), salt: salt, info: sharedInfo, outputByteCount: outputByteCount)
#endif
}
}
+50
View File
@@ -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: DataProtocol>(_ wrappedKey: WrappedKey, using kek: SymmetricKey) throws -> SymmetricKey {
return try AESWRAPImpl.unwrap(key: kek, wrappedKey: wrappedKey)
}
}
}
#endif // Linux or !SwiftPM
@@ -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<WrappedKey: DataProtocol>(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<WrappedKey: ContiguousBytes>(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<ResultType>(mode: AESKeyMode, _ body: (UnsafePointer<AES_KEY>) 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
@@ -39,6 +39,9 @@ public struct HMAC<H: HashFunction>: 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<H: HashFunction>: MACAlgorithm {
})
}
outerHasher.update(data: outerKey)
#endif
}
/// Computes a Message Authentication Code.
+24
View File
@@ -68,6 +68,9 @@ extension P256.Signing {
/// Initializes ECDSASignature from the DER representation.
public init<D: DataProtocol>(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<ArraySlice<UInt8>>(asn1Encoded: parsed)
@@ -87,6 +90,7 @@ extension P256.Signing {
raw.append(contentsOf: signature.s)
self.rawRepresentation = raw
#endif
}
public func withUnsafeBytes<R>(_ 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<D: DataProtocol>(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<ArraySlice<UInt8>>(asn1Encoded: parsed)
@@ -221,6 +232,7 @@ extension P384.Signing {
raw.append(contentsOf: signature.s)
self.rawRepresentation = raw
#endif
}
public func withUnsafeBytes<R>(_ 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<D: DataProtocol>(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<ArraySlice<UInt8>>(asn1Encoded: parsed)
@@ -355,6 +374,7 @@ extension P521.Signing {
raw.append(contentsOf: signature.s)
self.rawRepresentation = raw
#endif
}
public func withUnsafeBytes<R>(_ 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
}
}
}
@@ -76,6 +76,9 @@ extension ${CURVE}.Signing {
/// Initializes ECDSASignature from the DER representation.
public init<D: DataProtocol>(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<ArraySlice<UInt8>>(asn1Encoded: parsed)
@@ -95,6 +98,7 @@ extension ${CURVE}.Signing {
raw.append(contentsOf: signature.s)
self.rawRepresentation = raw
#endif
}
public func withUnsafeBytes<R>(_ 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
}
}
}
+2 -2
View File
@@ -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 }
}
}
@@ -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))
@@ -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
+1 -1
View File
@@ -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]