Skip to content
This repository was archived by the owner on Oct 15, 2024. It is now read-only.

Commit 0b4ba25

Browse files
committed
fix(crypto-pgpainless): refactor key extraction to correctly encrypt messages
1 parent fa59dc4 commit 0b4ba25

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandler.kt

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import java.io.ByteArrayInputStream
1616
import java.io.InputStream
1717
import java.io.OutputStream
1818
import javax.inject.Inject
19+
import org.bouncycastle.openpgp.PGPPublicKeyRing
1920
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection
2021
import org.pgpainless.PGPainless
2122
import org.pgpainless.decryption_verification.ConsumerOptions
@@ -66,19 +67,22 @@ public class PGPainlessCryptoHandler @Inject constructor() : CryptoHandler<PGPKe
6667
runCatching {
6768
if (keys.isEmpty()) throw NoKeysProvided("No keys provided for encryption")
6869
val armoredKeys = keys.map { key -> key.contents.decodeToString() }
69-
val pubKeysStream = ByteArrayInputStream(armoredKeys.joinToString("\n").toByteArray())
70-
val publicKeyRingCollection =
71-
pubKeysStream.use { PGPainless.readKeyRing().publicKeyRingCollection(pubKeysStream) }
72-
val encryptionOptions =
73-
EncryptionOptions.encryptCommunications()
74-
.addRecipients(publicKeyRingCollection.asIterable())
75-
val producerOptions = ProducerOptions.encrypt(encryptionOptions).setAsciiArmor(true)
70+
val secKeysStream = ByteArrayInputStream(armoredKeys.joinToString("\n").toByteArray())
71+
val secretKeyRingCollection =
72+
PGPainless.readKeyRing().secretKeyRingCollection(secKeysStream)
73+
val publicKeyRings = arrayListOf<PGPPublicKeyRing>()
74+
secretKeyRingCollection.forEach { secretKeyRing ->
75+
publicKeyRings.add(PGPainless.extractCertificate(secretKeyRing))
76+
}
77+
require(publicKeyRings.isNotEmpty()) { "No public keys to encrypt message to" }
78+
val encryptionOptions = EncryptionOptions().addRecipients(publicKeyRings.asIterable())
79+
val producerOptions = ProducerOptions.encrypt(encryptionOptions).setAsciiArmor(false)
7680
val encryptor =
7781
PGPainless.encryptAndOrSign().onOutputStream(outputStream).withOptions(producerOptions)
7882
plaintextStream.copyTo(encryptor)
7983
encryptor.close()
8084
val result = encryptor.result
81-
publicKeyRingCollection.keyRings.forEach { keyRing ->
85+
publicKeyRings.forEach { keyRing ->
8286
require(result.isEncryptedFor(keyRing)) {
8387
"Stream should be encrypted for ${keyRing.publicKey.keyID} but wasn't"
8488
}

0 commit comments

Comments
 (0)