From da38d344b9113fbed360f9a24b85a72cc815611b Mon Sep 17 00:00:00 2001 From: Dmitriy Zharov Date: Tue, 10 Sep 2024 23:59:11 +0200 Subject: [PATCH] Adds retrieval support for RSA keys --- .../SwiftSecurity/CryptoKit/SecKeyConvertible.swift | 11 +++++++++-- Sources/SwiftSecurity/Keychain/Keychain.swift | 10 ++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Sources/SwiftSecurity/CryptoKit/SecKeyConvertible.swift b/Sources/SwiftSecurity/CryptoKit/SecKeyConvertible.swift index 66967b5..f497b9d 100644 --- a/Sources/SwiftSecurity/CryptoKit/SecKeyConvertible.swift +++ b/Sources/SwiftSecurity/CryptoKit/SecKeyConvertible.swift @@ -14,8 +14,14 @@ public protocol SecKeyConvertible: SecKeyRepresentable { /// Creates a key from an X9.63 representation. init(x963Representation: Bytes) throws where Bytes: ContiguousBytes + /// Creates a key from a Distinguished Encoding Rules (DER) encoded representation. + init(derRepresentation: Bytes) throws where Bytes : RandomAccessCollection, Bytes.Element == UInt8 + /// An X9.63 representation of the key. var x963Representation: Data { get } + + /// A Distinguished Encoding Rules (DER) encoded representation of the private key. + var derRepresentation: Data { get } } // MARK: - CryptoKit @@ -86,10 +92,11 @@ extension SecKeyConvertible { let keyData: Data switch secKeyDescriptor.keyType { case .ecsecPrimeRandom: + // X9.63 keyData = x963Representation case .rsa: - // override and use data in PKCS #1 format - throw SwiftSecurityError.unimplemented + // PCKS #1, DER-Encoded + keyData = derRepresentation } var error: Unmanaged? diff --git a/Sources/SwiftSecurity/Keychain/Keychain.swift b/Sources/SwiftSecurity/Keychain/Keychain.swift index 8607810..2868294 100644 --- a/Sources/SwiftSecurity/Keychain/Keychain.swift +++ b/Sources/SwiftSecurity/Keychain/Keychain.swift @@ -349,8 +349,14 @@ extension Keychain: SecKeyStore { } throw SwiftSecurityError.invalidParameter } - - return try T(x963Representation: data) + + if let ecKey = try? T(x963Representation: data) { + return ecKey + } else if let rsaKey = try? T(derRepresentation: data) { + return rsaKey + } else { + throw SwiftSecurityError.invalidParameter + } } }