2019-06-29 23:09:24 +02:00
|
|
|
//
|
|
|
|
|
// KeyFileManager.swift
|
|
|
|
|
// passKit
|
|
|
|
|
//
|
|
|
|
|
// Created by Danny Moesch on 29.06.19.
|
|
|
|
|
// Copyright © 2019 Bob Sun. All rights reserved.
|
|
|
|
|
//
|
|
|
|
|
|
|
|
|
|
public class KeyFileManager {
|
2019-09-08 23:00:46 +02:00
|
|
|
public typealias KeyHandler = (String, String) -> Void
|
2019-06-29 23:09:24 +02:00
|
|
|
|
2019-07-02 20:20:56 +02:00
|
|
|
public static let PublicPgp = KeyFileManager(keyType: PgpKey.PUBLIC)
|
|
|
|
|
public static let PrivatePgp = KeyFileManager(keyType: PgpKey.PRIVATE)
|
2019-07-02 20:28:47 +02:00
|
|
|
public static let PrivateSsh = KeyFileManager(keyType: SshKey.PRIVATE)
|
2019-06-29 23:09:24 +02:00
|
|
|
|
2019-07-02 20:20:56 +02:00
|
|
|
private let keyType: CryptographicKey
|
2019-06-29 23:09:24 +02:00
|
|
|
private let keyPath: String
|
2019-09-08 23:00:46 +02:00
|
|
|
private let keyHandler: KeyHandler
|
2019-06-29 23:09:24 +02:00
|
|
|
|
2019-07-02 20:20:56 +02:00
|
|
|
private convenience init(keyType: CryptographicKey) {
|
2019-06-29 23:09:24 +02:00
|
|
|
self.init(keyType: keyType, keyPath: keyType.getFileSharingPath())
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-08 23:00:46 +02:00
|
|
|
public init(keyType: CryptographicKey, keyPath: String, keyHandler: @escaping KeyHandler = AppKeychain.shared.add) {
|
2019-06-29 23:09:24 +02:00
|
|
|
self.keyType = keyType
|
|
|
|
|
self.keyPath = keyPath
|
2019-09-08 23:00:46 +02:00
|
|
|
self.keyHandler = keyHandler
|
2019-06-29 23:09:24 +02:00
|
|
|
}
|
|
|
|
|
|
2019-09-08 23:00:46 +02:00
|
|
|
public func importKeyFromFileSharing() throws {
|
|
|
|
|
let keyFileContent = try String(contentsOfFile: keyPath, encoding: .ascii)
|
|
|
|
|
try importKey(from: keyFileContent)
|
2019-06-29 23:09:24 +02:00
|
|
|
try FileManager.default.removeItem(atPath: keyPath)
|
|
|
|
|
}
|
2019-09-08 23:00:46 +02:00
|
|
|
|
|
|
|
|
public func importKey(from string: String) throws {
|
2021-04-24 16:47:09 +02:00
|
|
|
guard string.unicodeScalars.allSatisfy(\.isASCII) else {
|
2020-09-20 15:07:18 +02:00
|
|
|
throw AppError.encoding
|
2019-09-08 23:00:46 +02:00
|
|
|
}
|
|
|
|
|
keyHandler(string, keyType.getKeychainKey())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public func importKey(from url: URL) throws {
|
|
|
|
|
try importKey(from: String(contentsOf: url, encoding: .ascii))
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-29 23:09:24 +02:00
|
|
|
public func doesKeyFileExist() -> Bool {
|
2020-06-28 21:25:40 +02:00
|
|
|
FileManager.default.fileExists(atPath: keyPath)
|
2019-06-29 23:09:24 +02:00
|
|
|
}
|
|
|
|
|
}
|