PGPInterface can encrypt with multiple keys, PGPAgent can encrypt with all keys

This commit is contained in:
Lysann Tranvouez 2026-03-11 00:21:30 +01:00
parent 39dab8c6c0
commit a56193dc86
5 changed files with 87 additions and 11 deletions

View file

@ -123,26 +123,43 @@ struct GopenPGPInterface: PGPInterface {
}
}
@available(*, deprecated, message: "Use encrypt(plainData:keyIDs:) instead.")
func encrypt(plainData: Data, keyID: String?) throws -> Data {
let key: CryptoKey? = {
if let keyID {
return publicKeys.first(where: { key, _ in key.hasSuffix(keyID.lowercased()) })?.value
}
return publicKeys.first?.value
}()
guard let keyID = keyID ?? publicKeys.keys.first else {
// this is invalid, but we want the new function to throw the error for us
return try encrypt(plainData: plainData, keyIDs: [])
}
return try encrypt(plainData: plainData, keyIDs: [keyID])
}
guard let publicKey = key else {
func encryptWithAllKeys(plainData: Data) throws -> Data {
let keyIDs = publicKeys.keys.filter { key in privateKeys.keys.contains(key) }
return try encrypt(plainData: plainData, keyIDs: keyIDs)
}
func encrypt(plainData: Data, keyIDs: [String]) throws -> Data {
let keys: [CryptoKey] = keyIDs.compactMap { keyID in
publicKeys.first(where: { key, _ in key.hasSuffix(keyID.lowercased()) })?.value
}
guard let firstKey = keys.first else {
throw AppError.encryption
}
let otherKeys = keys.dropFirst()
var error: NSError?
guard let keyRing = CryptoNewKeyRing(publicKey, &error) else {
guard let keyRing = CryptoNewKeyRing(firstKey, &error) else {
guard error == nil else {
throw error!
}
throw AppError.encryption
}
do {
try otherKeys.forEach { key in
try keyRing.add(key)
}
} catch {
throw AppError.encryption
}
let encryptedData = try keyRing.encrypt(CryptoNewPlainMessage(plainData.mutable as Data), privateKey: nil)
if Defaults.encryptInArmored {