80 lines
2.7 KiB
Swift
80 lines
2.7 KiB
Swift
//
|
|
// ObjectivePGPInterface.swift
|
|
// passKit
|
|
//
|
|
// Created by Danny Moesch on 08.09.19.
|
|
// Copyright © 2019 Bob Sun. All rights reserved.
|
|
//
|
|
|
|
import ObjectivePGP
|
|
|
|
struct ObjectivePGPInterface: PGPInterface {
|
|
private let keyring = ObjectivePGP.defaultKeyring
|
|
|
|
init(publicArmoredKey: String, privateArmoredKey: String) throws {
|
|
guard let publicKeyData = publicArmoredKey.data(using: .ascii), let privateKeyData = privateArmoredKey.data(using: .ascii) else {
|
|
throw AppError.keyImport
|
|
}
|
|
let publicKeys = try ObjectivePGP.readKeys(from: publicKeyData)
|
|
let privateKeys = try ObjectivePGP.readKeys(from: privateKeyData)
|
|
keyring.import(keys: publicKeys)
|
|
keyring.import(keys: privateKeys)
|
|
guard publicKeys.first != nil, privateKeys.first != nil else {
|
|
throw AppError.keyImport
|
|
}
|
|
}
|
|
|
|
func decrypt(encryptedData: Data, keyIDHint _: String?, passPhraseForKey: @escaping (String) -> String) throws -> Data? {
|
|
try ObjectivePGP.decrypt(encryptedData, andVerifySignature: false, using: keyring.keys) { selectedKey in
|
|
guard let selectedKey else {
|
|
return nil
|
|
}
|
|
return passPhraseForKey(selectedKey.keyID.longIdentifier)
|
|
}
|
|
}
|
|
|
|
func encryptWithAllKeys(plainData: Data) throws -> Data {
|
|
let keys = keyring.keys.filter { $0.isPublic && $0.isSecret }
|
|
return try encrypt(plainData: plainData, keyIDs: keys.map(\.keyID.longIdentifier))
|
|
}
|
|
|
|
func encrypt(plainData: Data, keyIDs: [String]) throws -> Data {
|
|
let keys = try keyIDs.map { keyID in
|
|
guard let key = keyring.findKey(keyID) else {
|
|
throw AppError.pgpPublicKeyNotFound(keyID: keyID)
|
|
}
|
|
return key
|
|
}
|
|
|
|
let encryptedData = try ObjectivePGP.encrypt(plainData, addSignature: false, using: keys, passphraseForKey: nil)
|
|
if Defaults.encryptInArmored {
|
|
return Armor.armored(encryptedData, as: .message).data(using: .ascii)!
|
|
}
|
|
return encryptedData
|
|
}
|
|
|
|
func containsPublicKey(with keyID: String) -> Bool {
|
|
keyring.findKey(keyID)?.isPublic ?? false
|
|
}
|
|
|
|
func containsPrivateKey(with keyID: String) -> Bool {
|
|
keyring.findKey(keyID)?.isSecret ?? false
|
|
}
|
|
|
|
func getKeyIDs(type: PGPKey) -> [String] {
|
|
getKeys(type: type).map(\.keyID.longIdentifier)
|
|
}
|
|
|
|
func getShortKeyIDs(type: PGPKey) -> [String] {
|
|
getKeys(type: type).map(\.keyID.shortIdentifier)
|
|
}
|
|
|
|
private func getKeys(type: PGPKey) -> [Key] {
|
|
switch type {
|
|
case .PUBLIC:
|
|
keyring.keys.filter(\.isPublic)
|
|
case .PRIVATE:
|
|
keyring.keys.filter(\.isSecret)
|
|
}
|
|
}
|
|
}
|