1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2025-09-09 18:29:39 +02:00

Port a bunch of more tests

This commit is contained in:
Paul Schaub 2025-04-02 20:54:19 +02:00
parent 674b15637f
commit f79aba74ed
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
11 changed files with 148 additions and 139 deletions

View file

@ -4,6 +4,7 @@
package org.pgpainless.encryption_signing package org.pgpainless.encryption_signing
import java.security.MessageDigest
import org.bouncycastle.openpgp.PGPException import org.bouncycastle.openpgp.PGPException
import org.bouncycastle.openpgp.PGPSignatureGenerator import org.bouncycastle.openpgp.PGPSignatureGenerator
import org.bouncycastle.openpgp.api.OpenPGPKey import org.bouncycastle.openpgp.api.OpenPGPKey
@ -12,7 +13,6 @@ import org.pgpainless.PGPainless
import org.pgpainless.algorithm.SignatureType import org.pgpainless.algorithm.SignatureType
import org.pgpainless.key.protection.SecretKeyRingProtector import org.pgpainless.key.protection.SecretKeyRingProtector
import org.pgpainless.key.protection.UnlockSecretKey import org.pgpainless.key.protection.UnlockSecretKey
import java.security.MessageDigest
class BcHashContextSigner { class BcHashContextSigner {
@ -29,7 +29,8 @@ class BcHashContextSigner {
.mapNotNull { info.getSecretKey(it.keyIdentifier) } .mapNotNull { info.getSecretKey(it.keyIdentifier) }
.firstOrNull() .firstOrNull()
?.let { ?.let {
signHashContext(hashContext, signatureType, UnlockSecretKey.unlockSecretKey(it, protector)) signHashContext(
hashContext, signatureType, UnlockSecretKey.unlockSecretKey(it, protector))
} }
?: throw PGPException("Key does not contain suitable signing subkey.") ?: throw PGPException("Key does not contain suitable signing subkey.")
} }
@ -49,8 +50,7 @@ class BcHashContextSigner {
privateKey: OpenPGPKey.OpenPGPPrivateKey privateKey: OpenPGPKey.OpenPGPPrivateKey
): OpenPGPDocumentSignature { ): OpenPGPDocumentSignature {
return PGPSignatureGenerator( return PGPSignatureGenerator(
BcPGPHashContextContentSignerBuilder(hashContext), BcPGPHashContextContentSignerBuilder(hashContext), privateKey.keyPair.publicKey)
privateKey.keyPair.publicKey)
.apply { init(signatureType.code, privateKey.keyPair.privateKey) } .apply { init(signatureType.code, privateKey.keyPair.privateKey) }
.generate() .generate()
.let { OpenPGPDocumentSignature(it, privateKey.publicKey) } .let { OpenPGPDocumentSignature(it, privateKey.publicKey) }

View file

@ -113,7 +113,10 @@ class UnlockSecretKey {
} }
@JvmStatic @JvmStatic
fun unlockSecretKey(secretKey: OpenPGPSecretKey, passphrase: Passphrase): OpenPGPPrivateKey = fun unlockSecretKey(
secretKey: OpenPGPSecretKey,
passphrase: Passphrase
): OpenPGPPrivateKey =
unlockSecretKey(secretKey, SecretKeyRingProtector.unlockAnyKeyWith(passphrase)) unlockSecretKey(secretKey, SecretKeyRingProtector.unlockAnyKeyWith(passphrase))
} }
} }

View file

@ -16,7 +16,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.api.OpenPGPCertificate; import org.bouncycastle.openpgp.api.OpenPGPCertificate;
import org.bouncycastle.openpgp.api.OpenPGPKey; import org.bouncycastle.openpgp.api.OpenPGPKey;
@ -31,7 +30,6 @@ import org.pgpainless.key.generation.KeySpec;
import org.pgpainless.key.generation.type.KeyType; import org.pgpainless.key.generation.type.KeyType;
import org.pgpainless.key.generation.type.eddsa_legacy.EdDSALegacyCurve; import org.pgpainless.key.generation.type.eddsa_legacy.EdDSALegacyCurve;
import org.pgpainless.key.generation.type.xdh_legacy.XDHLegacySpec; import org.pgpainless.key.generation.type.xdh_legacy.XDHLegacySpec;
import org.pgpainless.key.util.KeyRingUtils;
import org.pgpainless.util.Passphrase; import org.pgpainless.util.Passphrase;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@ -43,10 +41,11 @@ public class EncryptionOptionsTest {
private static OpenPGPCertificate.OpenPGPComponentKey primaryKey; private static OpenPGPCertificate.OpenPGPComponentKey primaryKey;
private static OpenPGPCertificate.OpenPGPComponentKey encryptComms; private static OpenPGPCertificate.OpenPGPComponentKey encryptComms;
private static OpenPGPCertificate.OpenPGPComponentKey encryptStorage; private static OpenPGPCertificate.OpenPGPComponentKey encryptStorage;
private static final PGPainless api = PGPainless.getInstance();
@BeforeAll @BeforeAll
public static void generateKey() { public static void generateKey() {
secretKeys = PGPainless.buildKeyRing() secretKeys = api.buildKey()
.setPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA_LEGACY(EdDSALegacyCurve._Ed25519), KeyFlag.CERTIFY_OTHER) .setPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA_LEGACY(EdDSALegacyCurve._Ed25519), KeyFlag.CERTIFY_OTHER)
.build()) .build())
.addSubkey(KeySpec.getBuilder(KeyType.XDH_LEGACY(XDHLegacySpec._X25519), KeyFlag.ENCRYPT_COMMS) .addSubkey(KeySpec.getBuilder(KeyType.XDH_LEGACY(XDHLegacySpec._X25519), KeyFlag.ENCRYPT_COMMS)
@ -66,7 +65,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testOverrideEncryptionAlgorithmFailsForNULL() { public void testOverrideEncryptionAlgorithmFailsForNULL() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
assertNull(options.getEncryptionAlgorithmOverride()); assertNull(options.getEncryptionAlgorithmOverride());
assertThrows(IllegalArgumentException.class, () -> options.overrideEncryptionAlgorithm(SymmetricKeyAlgorithm.NULL)); assertThrows(IllegalArgumentException.class, () -> options.overrideEncryptionAlgorithm(SymmetricKeyAlgorithm.NULL));
@ -76,7 +75,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testOverrideEncryptionOptions() { public void testOverrideEncryptionOptions() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
assertNull(options.getEncryptionAlgorithmOverride()); assertNull(options.getEncryptionAlgorithmOverride());
options.overrideEncryptionAlgorithm(SymmetricKeyAlgorithm.AES_128); options.overrideEncryptionAlgorithm(SymmetricKeyAlgorithm.AES_128);
@ -85,7 +84,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testAddRecipients_EncryptCommunications() { public void testAddRecipients_EncryptCommunications() {
EncryptionOptions options = EncryptionOptions.encryptCommunications(); EncryptionOptions options = EncryptionOptions.encryptCommunications(api);
options.addRecipient(publicKeys); options.addRecipient(publicKeys);
Set<OpenPGPCertificate.OpenPGPComponentKey> encryptionKeys = options.getEncryptionKeys(); Set<OpenPGPCertificate.OpenPGPComponentKey> encryptionKeys = options.getEncryptionKeys();
@ -95,7 +94,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testAddRecipients_EncryptDataAtRest() { public void testAddRecipients_EncryptDataAtRest() {
EncryptionOptions options = EncryptionOptions.encryptDataAtRest(); EncryptionOptions options = EncryptionOptions.encryptDataAtRest(api);
options.addRecipient(publicKeys); options.addRecipient(publicKeys);
Set<OpenPGPCertificate.OpenPGPComponentKey> encryptionKeys = options.getEncryptionKeys(); Set<OpenPGPCertificate.OpenPGPComponentKey> encryptionKeys = options.getEncryptionKeys();
@ -105,7 +104,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testAddRecipients_AllKeys() { public void testAddRecipients_AllKeys() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
options.addRecipient(publicKeys, EncryptionOptions.encryptToAllCapableSubkeys()); options.addRecipient(publicKeys, EncryptionOptions.encryptToAllCapableSubkeys());
Set<OpenPGPCertificate.OpenPGPComponentKey> encryptionKeys = options.getEncryptionKeys(); Set<OpenPGPCertificate.OpenPGPComponentKey> encryptionKeys = options.getEncryptionKeys();
@ -115,9 +114,10 @@ public class EncryptionOptionsTest {
assertTrue(encryptionKeys.contains(encryptStorage)); assertTrue(encryptionKeys.contains(encryptStorage));
} }
@SuppressWarnings("deprecation")
@Test @Test
public void testAddEmptyRecipientsFails() { public void testAddEmptyRecipientsFails() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
assertThrows(IllegalArgumentException.class, () -> options.addRecipients(Collections.emptyList())); assertThrows(IllegalArgumentException.class, () -> options.addRecipients(Collections.emptyList()));
assertThrows(IllegalArgumentException.class, () -> options.addRecipients(Collections.emptyList(), assertThrows(IllegalArgumentException.class, () -> options.addRecipients(Collections.emptyList(),
ArrayList::new)); ArrayList::new));
@ -125,7 +125,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testAddEmptyPassphraseFails() { public void testAddEmptyPassphraseFails() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () ->
options.addMessagePassphrase(Passphrase.emptyPassphrase())); options.addMessagePassphrase(Passphrase.emptyPassphrase()));
} }
@ -133,7 +133,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testAddRecipient_KeyWithoutEncryptionKeyFails() { public void testAddRecipient_KeyWithoutEncryptionKeyFails() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get();
OpenPGPKey secretKeys = PGPainless.buildKeyRing() OpenPGPKey secretKeys = api.buildKey()
.setPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA_LEGACY(EdDSALegacyCurve._Ed25519), KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA)) .setPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA_LEGACY(EdDSALegacyCurve._Ed25519), KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA))
.addUserId("test@pgpainless.org") .addUserId("test@pgpainless.org")
.build(); .build();
@ -144,7 +144,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testEncryptionKeySelectionStrategyEmpty_ThrowsAssertionError() { public void testEncryptionKeySelectionStrategyEmpty_ThrowsAssertionError() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
assertThrows(KeyException.UnacceptableEncryptionKeyException.class, assertThrows(KeyException.UnacceptableEncryptionKeyException.class,
() -> options.addRecipient(publicKeys, new EncryptionOptions.EncryptionKeySelector() { () -> options.addRecipient(publicKeys, new EncryptionOptions.EncryptionKeySelector() {
@ -157,6 +157,7 @@ public class EncryptionOptionsTest {
assertThrows(KeyException.UnacceptableEncryptionKeyException.class, assertThrows(KeyException.UnacceptableEncryptionKeyException.class,
() -> options.addRecipient(publicKeys, "test@pgpainless.org", new EncryptionOptions.EncryptionKeySelector() { () -> options.addRecipient(publicKeys, "test@pgpainless.org", new EncryptionOptions.EncryptionKeySelector() {
@NotNull
@Override @Override
public List<OpenPGPCertificate.OpenPGPComponentKey> selectEncryptionSubkeys(@Nonnull List<? extends OpenPGPCertificate.OpenPGPComponentKey> encryptionCapableKeys) { public List<OpenPGPCertificate.OpenPGPComponentKey> selectEncryptionSubkeys(@Nonnull List<? extends OpenPGPCertificate.OpenPGPComponentKey> encryptionCapableKeys) {
return Collections.emptyList(); return Collections.emptyList();
@ -166,21 +167,21 @@ public class EncryptionOptionsTest {
@Test @Test
public void testAddRecipients_PGPPublicKeyRingCollection() { public void testAddRecipients_PGPPublicKeyRingCollection() {
PGPPublicKeyRing secondKeyRing = KeyRingUtils.publicKeyRingFrom( OpenPGPKey secondKey = api.generateKey().modernKeyRing("Other <other@pgpainless.org>");
PGPainless.generateKeyRing().modernKeyRing("other@pgpainless.org") OpenPGPCertificate secondCert = secondKey.toCertificate();
.getPGPSecretKeyRing());
PGPPublicKeyRingCollection collection = new PGPPublicKeyRingCollection( PGPPublicKeyRingCollection collection = new PGPPublicKeyRingCollection(
Arrays.asList(publicKeys.getPGPPublicKeyRing(), secondKeyRing)); Arrays.asList(publicKeys.getPGPPublicKeyRing(), secondCert.getPGPPublicKeyRing()));
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get();
// noinspection deprecation
options.addRecipients(collection, EncryptionOptions.encryptToFirstSubkey()); options.addRecipients(collection, EncryptionOptions.encryptToFirstSubkey());
assertEquals(2, options.getEncryptionKeyIdentifiers().size()); assertEquals(2, options.getEncryptionKeyIdentifiers().size());
} }
@Test @Test
public void testAddRecipient_withValidUserId() { public void testAddRecipient_withValidUserId() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
options.addRecipient(publicKeys, "test@pgpainless.org", EncryptionOptions.encryptToFirstSubkey()); options.addRecipient(publicKeys, "test@pgpainless.org", EncryptionOptions.encryptToFirstSubkey());
assertEquals(1, options.getEncryptionMethods().size()); assertEquals(1, options.getEncryptionMethods().size());
@ -188,7 +189,7 @@ public class EncryptionOptionsTest {
@Test @Test
public void testAddRecipient_withInvalidUserId() { public void testAddRecipient_withInvalidUserId() {
EncryptionOptions options = EncryptionOptions.get(); EncryptionOptions options = EncryptionOptions.get(api);
assertThrows(KeyException.UnboundUserIdException.class, () -> options.addRecipient(publicKeys, "invalid@user.id")); assertThrows(KeyException.UnboundUserIdException.class, () -> options.addRecipient(publicKeys, "invalid@user.id"));
} }
} }

View file

@ -17,8 +17,8 @@ import java.util.Date;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.api.OpenPGPCertificate;
import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.api.OpenPGPKey;
import org.bouncycastle.util.io.Streams; import org.bouncycastle.util.io.Streams;
import org.junit.JUtils; import org.junit.JUtils;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
@ -32,14 +32,14 @@ import org.pgpainless.decryption_verification.MessageMetadata;
public class FileInformationTest { public class FileInformationTest {
private static final String data = "Hello, World!\n"; private static final String data = "Hello, World!\n";
private static PGPSecretKeyRing secretKey; private static OpenPGPKey secretKey;
private static PGPPublicKeyRing certificate; private static OpenPGPCertificate certificate;
private static final PGPainless api = PGPainless.getInstance();
@BeforeAll @BeforeAll
public static void generateKey() { public static void generateKey() {
secretKey = PGPainless.generateKeyRing().modernKeyRing("alice@wonderland.lit") secretKey = api.generateKey().modernKeyRing("alice@wonderland.lit");
.getPGPSecretKeyRing(); certificate = secretKey.toCertificate();
certificate = PGPainless.extractCertificate(secretKey);
} }
@Test @Test
@ -50,11 +50,12 @@ public class FileInformationTest {
ByteArrayInputStream dataIn = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); ByteArrayInputStream dataIn = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
EncryptionStream encryptionStream = PGPainless.encryptAndOrSign() // noinspection deprecation
EncryptionStream encryptionStream = api.generateMessage()
.onOutputStream(dataOut) .onOutputStream(dataOut)
.withOptions(ProducerOptions.encrypt( .withOptions(ProducerOptions.encrypt(
EncryptionOptions EncryptionOptions
.encryptCommunications() .encryptCommunications(api)
.addRecipient(certificate)) .addRecipient(certificate))
.setFileName(fileName) .setFileName(fileName)
.setModificationDate(modificationDate) .setModificationDate(modificationDate)
@ -91,11 +92,11 @@ public class FileInformationTest {
public void testDefaults() throws PGPException, IOException { public void testDefaults() throws PGPException, IOException {
ByteArrayInputStream dataIn = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); ByteArrayInputStream dataIn = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
EncryptionStream encryptionStream = PGPainless.encryptAndOrSign() EncryptionStream encryptionStream = api.generateMessage()
.onOutputStream(dataOut) .onOutputStream(dataOut)
.withOptions(ProducerOptions.encrypt( .withOptions(ProducerOptions.encrypt(
EncryptionOptions EncryptionOptions
.encryptCommunications() .encryptCommunications(api)
.addRecipient(certificate)) .addRecipient(certificate))
); );
@ -125,6 +126,7 @@ public class FileInformationTest {
JUtils.assertDateEquals(PGPLiteralData.NOW, decResult.getModificationDate()); JUtils.assertDateEquals(PGPLiteralData.NOW, decResult.getModificationDate());
assertNotNull(decResult.getLiteralDataEncoding()); assertNotNull(decResult.getLiteralDataEncoding());
assertEquals(PGPLiteralData.BINARY, decResult.getLiteralDataEncoding().getCode()); assertEquals(PGPLiteralData.BINARY, decResult.getLiteralDataEncoding().getCode());
// noinspection deprecation
assertFalse(decResult.isForYourEyesOnly()); assertFalse(decResult.isForYourEyesOnly());
} }
@ -132,11 +134,12 @@ public class FileInformationTest {
public void testForYourEyesOnly() throws PGPException, IOException { public void testForYourEyesOnly() throws PGPException, IOException {
ByteArrayInputStream dataIn = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); ByteArrayInputStream dataIn = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
EncryptionStream encryptionStream = PGPainless.encryptAndOrSign() // noinspection deprecation
EncryptionStream encryptionStream = api.generateMessage()
.onOutputStream(dataOut) .onOutputStream(dataOut)
.withOptions(ProducerOptions.encrypt( .withOptions(ProducerOptions.encrypt(
EncryptionOptions EncryptionOptions
.encryptCommunications() .encryptCommunications(api)
.addRecipient(certificate)) .addRecipient(certificate))
.setForYourEyesOnly() .setForYourEyesOnly()
); );
@ -167,6 +170,7 @@ public class FileInformationTest {
JUtils.assertDateEquals(PGPLiteralData.NOW, decResult.getModificationDate()); JUtils.assertDateEquals(PGPLiteralData.NOW, decResult.getModificationDate());
assertNotNull(decResult.getLiteralDataEncoding()); assertNotNull(decResult.getLiteralDataEncoding());
assertEquals(PGPLiteralData.BINARY, decResult.getLiteralDataEncoding().getCode()); assertEquals(PGPLiteralData.BINARY, decResult.getLiteralDataEncoding().getCode());
// noinspection deprecation
assertTrue(decResult.isForYourEyesOnly()); assertTrue(decResult.isForYourEyesOnly());
} }
} }

View file

@ -13,8 +13,8 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.api.OpenPGPCertificate;
import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.api.OpenPGPKey;
import org.bouncycastle.util.io.Streams; import org.bouncycastle.util.io.Streams;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
@ -30,18 +30,18 @@ public class HiddenRecipientEncryptionTest {
@Test @Test
public void testAnonymousRecipientRoundtrip() throws PGPException, IOException { public void testAnonymousRecipientRoundtrip() throws PGPException, IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing() PGPainless api = PGPainless.getInstance();
.modernKeyRing("Alice <alice@pgpainless.org>") OpenPGPKey secretKeys = api.generateKey()
.getPGPSecretKeyRing(); .modernKeyRing("Alice <alice@pgpainless.org>");
PGPPublicKeyRing certificate = PGPainless.extractCertificate(secretKeys); OpenPGPCertificate certificate = secretKeys.toCertificate();
String msg = "Hello, World!\n"; String msg = "Hello, World!\n";
ByteArrayOutputStream ciphertextOut = new ByteArrayOutputStream(); ByteArrayOutputStream ciphertextOut = new ByteArrayOutputStream();
EncryptionStream encryptionStream = PGPainless.encryptAndOrSign() EncryptionStream encryptionStream = api.generateMessage()
.onOutputStream(ciphertextOut) .onOutputStream(ciphertextOut)
.withOptions(ProducerOptions.encrypt( .withOptions(ProducerOptions.encrypt(
EncryptionOptions.get() EncryptionOptions.get(api)
.addHiddenRecipient(certificate) .addHiddenRecipient(certificate)
)); ));
encryptionStream.write(msg.getBytes(StandardCharsets.UTF_8)); encryptionStream.write(msg.getBytes(StandardCharsets.UTF_8));
@ -65,6 +65,8 @@ public class HiddenRecipientEncryptionTest {
assertEquals(msg, plaintextOut.toString()); assertEquals(msg, plaintextOut.toString());
assertTrue(metadata.getRecipientKeyIds().contains(0L)); assertTrue(metadata.getRecipientKeyIds().contains(0L));
assertEquals(1, metadata.getRecipientKeyIdentifiers().size());
assertTrue(metadata.getRecipientKeyIdentifiers().get(0).isWildcard());
assertEquals(actualEncryptionKey, metadata.getDecryptionKey()); assertEquals(actualEncryptionKey, metadata.getDecryptionKey());
} }
} }

View file

@ -13,17 +13,17 @@ import java.util.Collections;
import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator; import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.api.OpenPGPCertificate;
import org.bouncycastle.openpgp.api.OpenPGPImplementation; import org.bouncycastle.openpgp.api.OpenPGPImplementation;
import org.bouncycastle.openpgp.api.OpenPGPKey;
import org.bouncycastle.util.Strings; import org.bouncycastle.util.Strings;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
import org.pgpainless.algorithm.OpenPGPKeyVersion;
import org.pgpainless.algorithm.SignatureType; import org.pgpainless.algorithm.SignatureType;
import org.pgpainless.key.info.KeyRingInfo; import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.protection.UnlockSecretKey; import org.pgpainless.key.protection.UnlockSecretKey;
@ -67,8 +67,8 @@ public class WeirdKeys {
"=BlPm\n" + "=BlPm\n" +
"-----END PGP PRIVATE KEY BLOCK-----\n"; "-----END PGP PRIVATE KEY BLOCK-----\n";
public static PGPSecretKeyRing getTwoCryptSubkeysKey() throws IOException { public static OpenPGPKey getTwoCryptSubkeysKey() throws IOException {
return PGPainless.readKeyRing().secretKeyRing(TWO_CRYPT_SUBKEYS); return PGPainless.getInstance().readKey().parseKey(TWO_CRYPT_SUBKEYS);
} }
/** /**
@ -96,18 +96,18 @@ public class WeirdKeys {
"=h6sT\n" + "=h6sT\n" +
"-----END PGP PRIVATE KEY BLOCK-----\n"; "-----END PGP PRIVATE KEY BLOCK-----\n";
public static PGPSecretKeyRing getArchiveCommsSubkeysKey() throws IOException { public static OpenPGPKey getArchiveCommsSubkeysKey() throws IOException {
return PGPainless.readKeyRing().secretKeyRing(ARCHIVE_COMMS_SUBKEYS); return PGPainless.getInstance().readKey().parseKey(ARCHIVE_COMMS_SUBKEYS);
} }
@Test @Test
public void generateCertAndTestWithNonUTF8UserId() public void generateCertAndTestWithNonUTF8UserId()
throws PGPException, IOException { throws PGPException, IOException {
PGPSecretKeyRing nakedKey = PGPainless.generateKeyRing().modernKeyRing(null) OpenPGPKey nakedKey = PGPainless.getInstance()
.getPGPSecretKeyRing(); .generateKey(OpenPGPKeyVersion.v4) // v4, since we manually craft the binding sig later on
PGPPublicKey pubKey = nakedKey.getPublicKey(); .modernKeyRing(null);
PGPSecretKey secKey = nakedKey.getSecretKey(); OpenPGPKey.OpenPGPSecretKey primaryKey = nakedKey.getPrimarySecretKey();
PGPPrivateKey privKey = UnlockSecretKey.unlockSecretKey(secKey, Passphrase.emptyPassphrase()); OpenPGPKey.OpenPGPPrivateKey privateKey = UnlockSecretKey.unlockSecretKey(primaryKey, Passphrase.emptyPassphrase());
// Non-UTF8 User-ID // Non-UTF8 User-ID
ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ByteArrayOutputStream bOut = new ByteArrayOutputStream();
@ -122,15 +122,15 @@ public class WeirdKeys {
PGPSignatureGenerator sigGen = new PGPSignatureGenerator( PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
OpenPGPImplementation.getInstance().pgpContentSignerBuilder( OpenPGPImplementation.getInstance().pgpContentSignerBuilder(
pubKey.getAlgorithm(), primaryKey.getAlgorithm(),
HashAlgorithmTags.SHA512), HashAlgorithmTags.SHA512),
pubKey); primaryKey.getPGPPublicKey());
sigGen.init(SignatureType.GENERIC_CERTIFICATION.getCode(), privKey); sigGen.init(SignatureType.GENERIC_CERTIFICATION.getCode(), privateKey.getKeyPair().getPrivateKey());
// We have to manually generate the signature over the user-ID // We have to manually generate the signature over the user-ID
// updateWithKey() // updateWithKey()
byte[] keyBytes = pubKey.getPublicKeyPacket().getEncodedContents(); byte[] keyBytes = primaryKey.getPGPPublicKey().getPublicKeyPacket().getEncodedContents();
sigGen.update((byte) 0x99); sigGen.update((byte) 0x99); // 0x99 means v4 key
sigGen.update((byte) (keyBytes.length >> 8)); sigGen.update((byte) (keyBytes.length >> 8));
sigGen.update((byte) (keyBytes.length)); sigGen.update((byte) (keyBytes.length));
sigGen.update(keyBytes); sigGen.update(keyBytes);
@ -144,12 +144,13 @@ public class WeirdKeys {
sigGen.update(idBytes); sigGen.update(idBytes);
PGPSignature signature = sigGen.generate(); PGPSignature signature = sigGen.generate();
pubKey = PGPPublicKey.addCertification(pubKey, idBytes, signature); PGPPublicKey pubKey = PGPPublicKey.addCertification(primaryKey.getPGPPublicKey(), idBytes, signature);
PGPPublicKeyRing cert = new PGPPublicKeyRing(Collections.singletonList(pubKey)); PGPPublicKeyRing pubRing = new PGPPublicKeyRing(Collections.singletonList(pubKey));
OpenPGPCertificate cert = PGPainless.getInstance().toCertificate(pubRing);
// This might fail // This might fail
KeyRingInfo info = PGPainless.inspectKeyRing(cert); KeyRingInfo info = PGPainless.getInstance().inspect(cert);
assertTrue(info.getUserIds().isEmpty()); // Malformed ID is ignored assertTrue(info.getUserIds().isEmpty()); // Malformed ID is ignored
} }
} }

View file

@ -54,10 +54,14 @@ public class PGPKeyRingCollectionTest {
@Test @Test
public void testConstructorFromCollection() { public void testConstructorFromCollection() {
PGPSecretKeyRing first = PGPainless.generateKeyRing().simpleEcKeyRing("alice@wonderland.lit") PGPainless api = PGPainless.getInstance();
PGPSecretKeyRing first = api.generateKey()
.simpleEcKeyRing("alice@wonderland.lit")
.getPGPSecretKeyRing(); .getPGPSecretKeyRing();
PGPSecretKeyRing second = PGPainless.generateKeyRing().simpleEcKeyRing("bob@the-builder.tv") PGPSecretKeyRing second = api.generateKey()
.simpleEcKeyRing("bob@the-builder.tv")
.getPGPSecretKeyRing(); .getPGPSecretKeyRing();
// noinspection deprecation
PGPPublicKeyRing secondPub = KeyRingUtils.publicKeyRingFrom(second); PGPPublicKeyRing secondPub = KeyRingUtils.publicKeyRingFrom(second);
Collection<PGPKeyRing> keys = Arrays.asList(first, second, secondPub); Collection<PGPKeyRing> keys = Arrays.asList(first, second, secondPub);

View file

@ -23,10 +23,13 @@ public class KeyRingCollectionReaderTest {
@Test @Test
public void writeAndParseKeyRingCollections() throws IOException { public void writeAndParseKeyRingCollections() throws IOException {
PGPainless api = PGPainless.getInstance();
// secret keys // secret keys
PGPSecretKeyRing alice = PGPainless.generateKeyRing().modernKeyRing("Alice <alice@pgpainless.org>") PGPSecretKeyRing alice = api.generateKey()
.modernKeyRing("Alice <alice@pgpainless.org>")
.getPGPSecretKeyRing(); .getPGPSecretKeyRing();
PGPSecretKeyRing bob = PGPainless.generateKeyRing().modernKeyRing("Bob <bob@pgpainless.org>") PGPSecretKeyRing bob = api.generateKey()
.modernKeyRing("Bob <bob@pgpainless.org>")
.getPGPSecretKeyRing(); .getPGPSecretKeyRing();
PGPSecretKeyRingCollection collection = KeyRingUtils.keyRingsToKeyRingCollection(alice, bob); PGPSecretKeyRingCollection collection = KeyRingUtils.keyRingsToKeyRingCollection(alice, bob);
@ -36,8 +39,8 @@ public class KeyRingCollectionReaderTest {
assertEquals(collection.size(), parsed.size()); assertEquals(collection.size(), parsed.size());
// public keys // public keys
PGPPublicKeyRing pAlice = KeyRingUtils.publicKeyRingFrom(alice); PGPPublicKeyRing pAlice = alice.toCertificate();
PGPPublicKeyRing pBob = KeyRingUtils.publicKeyRingFrom(bob); PGPPublicKeyRing pBob = bob.toCertificate();
PGPPublicKeyRingCollection pCollection = KeyRingUtils.keyRingsToKeyRingCollection(pAlice, pBob); PGPPublicKeyRingCollection pCollection = KeyRingUtils.keyRingsToKeyRingCollection(pAlice, pBob);
ascii = ArmorUtils.toAsciiArmoredString(pCollection); ascii = ArmorUtils.toAsciiArmoredString(pCollection);

View file

@ -6,6 +6,8 @@ package org.pgpainless.key.parsing;
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -30,6 +32,7 @@ import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection; import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.api.OpenPGPCertificate;
import org.bouncycastle.openpgp.api.OpenPGPImplementation; import org.bouncycastle.openpgp.api.OpenPGPImplementation;
import org.bouncycastle.openpgp.api.OpenPGPKey; import org.bouncycastle.openpgp.api.OpenPGPKey;
import org.bouncycastle.util.io.Streams; import org.bouncycastle.util.io.Streams;
@ -38,13 +41,14 @@ import org.opentest4j.TestAbortedException;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
import org.pgpainless.key.OpenPgpV4Fingerprint; import org.pgpainless.key.OpenPgpV4Fingerprint;
import org.pgpainless.key.collection.PGPKeyRingCollection; import org.pgpainless.key.collection.PGPKeyRingCollection;
import org.pgpainless.key.util.KeyRingUtils;
import org.pgpainless.signature.SignatureUtils; import org.pgpainless.signature.SignatureUtils;
import org.pgpainless.util.ArmoredOutputStreamFactory; import org.pgpainless.util.ArmoredOutputStreamFactory;
import org.pgpainless.util.TestUtils; import org.pgpainless.util.TestUtils;
class KeyRingReaderTest { class KeyRingReaderTest {
private final PGPainless api = PGPainless.getInstance();
private InputStream requireResource(String resourceName) { private InputStream requireResource(String resourceName) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourceName); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourceName);
if (inputStream == null) { if (inputStream == null) {
@ -81,9 +85,9 @@ class KeyRingReaderTest {
Collection<PGPPublicKeyRing> collection = new ArrayList<>(); Collection<PGPPublicKeyRing> collection = new ArrayList<>();
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().simpleEcKeyRing("user_" + i + "@encrypted.key") PGPSecretKeyRing secretKeys = api.generateKey().simpleEcKeyRing("user_" + i + "@encrypted.key")
.getPGPSecretKeyRing(); .getPGPSecretKeyRing();
collection.add(KeyRingUtils.publicKeyRingFrom(secretKeys)); collection.add(secretKeys.toCertificate());
} }
PGPPublicKeyRingCollection originalRings = new PGPPublicKeyRingCollection(collection); PGPPublicKeyRingCollection originalRings = new PGPPublicKeyRingCollection(collection);
@ -275,7 +279,8 @@ class KeyRingReaderTest {
"=9jtR\n" + "=9jtR\n" +
"-----END PGP PRIVATE KEY BLOCK-----"; "-----END PGP PRIVATE KEY BLOCK-----";
PGPSecretKeyRing secretKey = PGPainless.readKeyRing().secretKeyRing(markerAndKey); OpenPGPKey secretKey = api.readKey().parseKey(markerAndKey);
assertNotNull(secretKey);
assertEquals( assertEquals(
new OpenPgpV4Fingerprint("562584F8730F39FCB02AACAE735E5EB1C541C0CE"), new OpenPgpV4Fingerprint("562584F8730F39FCB02AACAE735E5EB1C541C0CE"),
new OpenPgpV4Fingerprint(secretKey)); new OpenPgpV4Fingerprint(secretKey));
@ -304,7 +309,7 @@ class KeyRingReaderTest {
"=6XFh\n" + "=6XFh\n" +
"-----END PGP PUBLIC KEY BLOCK-----\n"; "-----END PGP PUBLIC KEY BLOCK-----\n";
PGPPublicKeyRing certificate = PGPainless.readKeyRing().publicKeyRing(markerAndCert); OpenPGPCertificate certificate = api.readKey().parseCertificate(markerAndCert);
assertEquals( assertEquals(
new OpenPgpV4Fingerprint("4291C2BEF9B9209DF11128E7F6F2BBD4F5D29793"), new OpenPgpV4Fingerprint("4291C2BEF9B9209DF11128E7F6F2BBD4F5D29793"),
@ -450,10 +455,8 @@ class KeyRingReaderTest {
@Test @Test
public void testReadSecretKeysIgnoresMultipleMarkers() throws IOException { public void testReadSecretKeysIgnoresMultipleMarkers() throws IOException {
PGPSecretKeyRing alice = PGPainless.generateKeyRing().modernKeyRing("alice@pgpainless.org") OpenPGPKey alice = api.generateKey().modernKeyRing("alice@pgpainless.org");
.getPGPSecretKeyRing(); OpenPGPKey bob = api.generateKey().modernKeyRing("bob@pgpainless.org");
PGPSecretKeyRing bob = PGPainless.generateKeyRing().modernKeyRing("bob@pgpainless.org")
.getPGPSecretKeyRing();
MarkerPacket marker = TestUtils.getMarkerPacket(); MarkerPacket marker = TestUtils.getMarkerPacket();
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@ -464,11 +467,11 @@ class KeyRingReaderTest {
for (int i = 0; i < 25; i++) { for (int i = 0; i < 25; i++) {
marker.encode(outputStream); marker.encode(outputStream);
} }
alice.encode(outputStream); outputStream.write(alice.getEncoded());
for (int i = 0; i < 53; i++) { for (int i = 0; i < 53; i++) {
marker.encode(outputStream); marker.encode(outputStream);
} }
bob.encode(outputStream); outputStream.write(bob.getEncoded());
for (int i = 0; i < 102; i++) { for (int i = 0; i < 102; i++) {
marker.encode(outputStream); marker.encode(outputStream);
} }
@ -479,15 +482,14 @@ class KeyRingReaderTest {
PGPSecretKeyRingCollection secretKeys = PGPainless.readKeyRing().secretKeyRingCollection(armoredMess); PGPSecretKeyRingCollection secretKeys = PGPainless.readKeyRing().secretKeyRingCollection(armoredMess);
assertEquals(2, secretKeys.size()); assertEquals(2, secretKeys.size());
assertTrue(secretKeys.contains(alice.getSecretKey().getKeyID())); assertTrue(secretKeys.contains(alice.getKeyIdentifier().getKeyId()));
assertTrue(secretKeys.contains(bob.getSecretKey().getKeyID())); assertTrue(secretKeys.contains(bob.getKeyIdentifier().getKeyId()));
} }
@Test @Test
public void testReadingSecretKeysExceedsIterationLimit() public void testReadingSecretKeysExceedsIterationLimit()
throws IOException { throws IOException {
PGPSecretKeyRing alice = PGPainless.generateKeyRing().modernKeyRing("alice@pgpainless.org") OpenPGPKey alice = api.generateKey().modernKeyRing("alice@pgpainless.org");
.getPGPSecretKeyRing();
MarkerPacket marker = TestUtils.getMarkerPacket(); MarkerPacket marker = TestUtils.getMarkerPacket();
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@ -497,7 +499,7 @@ class KeyRingReaderTest {
for (int i = 0; i < 600; i++) { for (int i = 0; i < 600; i++) {
marker.encode(outputStream); marker.encode(outputStream);
} }
alice.encode(outputStream); outputStream.write(alice.getEncoded());
assertThrows(IOException.class, () -> assertThrows(IOException.class, () ->
KeyRingReader.readSecretKeyRing(new ByteArrayInputStream(bytes.toByteArray()), 512)); KeyRingReader.readSecretKeyRing(new ByteArrayInputStream(bytes.toByteArray()), 512));
@ -506,10 +508,8 @@ class KeyRingReaderTest {
@Test @Test
public void testReadingSecretKeyCollectionExceedsIterationLimit() public void testReadingSecretKeyCollectionExceedsIterationLimit()
throws IOException { throws IOException {
PGPSecretKeyRing alice = PGPainless.generateKeyRing().modernKeyRing("alice@pgpainless.org") OpenPGPKey alice = api.generateKey().modernKeyRing("alice@pgpainless.org");
.getPGPSecretKeyRing(); OpenPGPKey bob = api.generateKey().modernKeyRing("bob@pgpainless.org");
PGPSecretKeyRing bob = PGPainless.generateKeyRing().modernKeyRing("bob@pgpainless.org")
.getPGPSecretKeyRing();
MarkerPacket marker = TestUtils.getMarkerPacket(); MarkerPacket marker = TestUtils.getMarkerPacket();
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@ -519,8 +519,8 @@ class KeyRingReaderTest {
for (int i = 0; i < 600; i++) { for (int i = 0; i < 600; i++) {
marker.encode(outputStream); marker.encode(outputStream);
} }
alice.encode(outputStream); outputStream.write(alice.getEncoded());
bob.encode(outputStream); outputStream.write(bob.getEncoded());
assertThrows(IOException.class, () -> assertThrows(IOException.class, () ->
KeyRingReader.readSecretKeyRingCollection(new ByteArrayInputStream(bytes.toByteArray()), 512)); KeyRingReader.readSecretKeyRingCollection(new ByteArrayInputStream(bytes.toByteArray()), 512));
@ -530,9 +530,8 @@ class KeyRingReaderTest {
@Test @Test
public void testReadingPublicKeysExceedsIterationLimit() public void testReadingPublicKeysExceedsIterationLimit()
throws IOException { throws IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("alice@pgpainless.org") OpenPGPKey secretKeys = api.generateKey().modernKeyRing("alice@pgpainless.org");
.getPGPSecretKeyRing(); OpenPGPCertificate alice = secretKeys.toCertificate();
PGPPublicKeyRing alice = PGPainless.extractCertificate(secretKeys);
MarkerPacket marker = TestUtils.getMarkerPacket(); MarkerPacket marker = TestUtils.getMarkerPacket();
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@ -542,7 +541,7 @@ class KeyRingReaderTest {
for (int i = 0; i < 600; i++) { for (int i = 0; i < 600; i++) {
marker.encode(outputStream); marker.encode(outputStream);
} }
alice.encode(outputStream); outputStream.write(alice.getEncoded());
assertThrows(IOException.class, () -> assertThrows(IOException.class, () ->
KeyRingReader.readPublicKeyRing(new ByteArrayInputStream(bytes.toByteArray()), 512)); KeyRingReader.readPublicKeyRing(new ByteArrayInputStream(bytes.toByteArray()), 512));
@ -551,12 +550,10 @@ class KeyRingReaderTest {
@Test @Test
public void testReadingPublicKeyCollectionExceedsIterationLimit() public void testReadingPublicKeyCollectionExceedsIterationLimit()
throws IOException { throws IOException {
PGPSecretKeyRing sec1 = PGPainless.generateKeyRing().modernKeyRing("alice@pgpainless.org") OpenPGPKey sec1 = api.generateKey().modernKeyRing("alice@pgpainless.org");
.getPGPSecretKeyRing(); OpenPGPKey sec2 = api.generateKey().modernKeyRing("bob@pgpainless.org");
PGPSecretKeyRing sec2 = PGPainless.generateKeyRing().modernKeyRing("bob@pgpainless.org") OpenPGPCertificate alice = sec1.toCertificate();
.getPGPSecretKeyRing(); OpenPGPCertificate bob = sec2.toCertificate();
PGPPublicKeyRing alice = PGPainless.extractCertificate(sec1);
PGPPublicKeyRing bob = PGPainless.extractCertificate(sec2);
MarkerPacket marker = TestUtils.getMarkerPacket(); MarkerPacket marker = TestUtils.getMarkerPacket();
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@ -566,8 +563,8 @@ class KeyRingReaderTest {
for (int i = 0; i < 600; i++) { for (int i = 0; i < 600; i++) {
marker.encode(outputStream); marker.encode(outputStream);
} }
alice.encode(outputStream); outputStream.write(alice.getEncoded());
bob.encode(outputStream); outputStream.write(bob.getEncoded());
assertThrows(IOException.class, () -> assertThrows(IOException.class, () ->
KeyRingReader.readPublicKeyRingCollection(new ByteArrayInputStream(bytes.toByteArray()), 512)); KeyRingReader.readPublicKeyRingCollection(new ByteArrayInputStream(bytes.toByteArray()), 512));
@ -575,48 +572,44 @@ class KeyRingReaderTest {
@Test @Test
public void testReadKeyRingWithBinaryPublicKey() throws IOException { public void testReadKeyRingWithBinaryPublicKey() throws IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice <alice@pgpainless.org>") OpenPGPKey secretKeys = api.generateKey().modernKeyRing("Alice <alice@pgpainless.org>");
.getPGPSecretKeyRing(); OpenPGPCertificate publicKeys = secretKeys.toCertificate();
PGPPublicKeyRing publicKeys = PGPainless.extractCertificate(secretKeys);
byte[] bytes = publicKeys.getEncoded(); byte[] bytes = publicKeys.getEncoded();
PGPKeyRing keyRing = PGPainless.readKeyRing() PGPKeyRing keyRing = PGPainless.readKeyRing()
.keyRing(bytes); .keyRing(bytes);
assertTrue(keyRing instanceof PGPPublicKeyRing); assertInstanceOf(PGPPublicKeyRing.class, keyRing);
assertArrayEquals(keyRing.getEncoded(), publicKeys.getEncoded()); assertArrayEquals(keyRing.getEncoded(), publicKeys.getEncoded());
} }
@Test @Test
public void testReadKeyRingWithBinarySecretKey() throws IOException { public void testReadKeyRingWithBinarySecretKey() throws IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice <alice@pgpainless.org>") OpenPGPKey secretKeys = api.generateKey().modernKeyRing("Alice <alice@pgpainless.org>");
.getPGPSecretKeyRing();
byte[] bytes = secretKeys.getEncoded(); byte[] bytes = secretKeys.getEncoded();
PGPKeyRing keyRing = PGPainless.readKeyRing() PGPKeyRing keyRing = PGPainless.readKeyRing()
.keyRing(bytes); .keyRing(bytes);
assertTrue(keyRing instanceof PGPSecretKeyRing); assertInstanceOf(PGPSecretKeyRing.class, keyRing);
assertArrayEquals(keyRing.getEncoded(), secretKeys.getEncoded()); assertArrayEquals(keyRing.getEncoded(), secretKeys.getEncoded());
} }
@Test @Test
public void testReadKeyRingWithArmoredPublicKey() throws IOException { public void testReadKeyRingWithArmoredPublicKey() throws IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice <alice@pgpainless.org>") OpenPGPKey secretKeys = api.generateKey().modernKeyRing("Alice <alice@pgpainless.org>");
.getPGPSecretKeyRing(); OpenPGPCertificate publicKeys = secretKeys.toCertificate();
PGPPublicKeyRing publicKeys = PGPainless.extractCertificate(secretKeys);
String armored = PGPainless.asciiArmor(publicKeys); String armored = PGPainless.asciiArmor(publicKeys);
PGPKeyRing keyRing = PGPainless.readKeyRing() PGPKeyRing keyRing = PGPainless.readKeyRing()
.keyRing(armored); .keyRing(armored);
assertTrue(keyRing instanceof PGPPublicKeyRing); assertInstanceOf(PGPPublicKeyRing.class, keyRing);
assertArrayEquals(keyRing.getEncoded(), publicKeys.getEncoded()); assertArrayEquals(keyRing.getEncoded(), publicKeys.getEncoded());
} }
@Test @Test
public void testReadKeyRingWithArmoredSecretKey() throws IOException { public void testReadKeyRingWithArmoredSecretKey() throws IOException {
PGPainless api = PGPainless.getInstance();
OpenPGPKey secretKeys = api.generateKey().modernKeyRing("Alice <alice@pgpainless.org>"); OpenPGPKey secretKeys = api.generateKey().modernKeyRing("Alice <alice@pgpainless.org>");
// remove PacketFormat argument once https://github.com/bcgit/bc-java/pull/1993 lands in BC // remove PacketFormat argument once https://github.com/bcgit/bc-java/pull/1993 lands in BC
String armored = secretKeys.toAsciiArmoredString(PacketFormat.LEGACY); String armored = secretKeys.toAsciiArmoredString(PacketFormat.LEGACY);
@ -624,7 +617,7 @@ class KeyRingReaderTest {
PGPKeyRing keyRing = PGPainless.readKeyRing() PGPKeyRing keyRing = PGPainless.readKeyRing()
.keyRing(armored); .keyRing(armored);
assertTrue(keyRing instanceof PGPSecretKeyRing); assertInstanceOf(PGPSecretKeyRing.class, keyRing);
assertArrayEquals(keyRing.getEncoded(), secretKeys.getEncoded()); assertArrayEquals(keyRing.getEncoded(), secretKeys.getEncoded());
} }
} }

View file

@ -15,10 +15,10 @@ import java.util.Random;
import org.bouncycastle.bcpg.KeyIdentifier; import org.bouncycastle.bcpg.KeyIdentifier;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyRing;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.api.OpenPGPCertificate;
import org.bouncycastle.openpgp.api.OpenPGPKey;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -78,40 +78,39 @@ public class CachingSecretKeyRingProtectorTest {
@Test @Test
public void testAddPassphraseForKeyRing() throws PGPException { public void testAddPassphraseForKeyRing() throws PGPException {
PGPSecretKeyRing keys = PGPainless.generateKeyRing() OpenPGPKey keys = PGPainless.getInstance().generateKey()
.modernKeyRing("test@test.test", "Passphrase123") .modernKeyRing("test@test.test", "Passphrase123");
.getPGPSecretKeyRing();
Passphrase passphrase = Passphrase.fromPassword("Passphrase123"); Passphrase passphrase = Passphrase.fromPassword("Passphrase123");
protector.addPassphrase(keys, passphrase); protector.addPassphrase(keys, passphrase);
Iterator<PGPSecretKey> it = keys.getSecretKeys(); Iterator<OpenPGPKey.OpenPGPSecretKey> it = keys.getSecretKeys().values().iterator();
while (it.hasNext()) { while (it.hasNext()) {
PGPSecretKey key = it.next(); OpenPGPKey.OpenPGPSecretKey key = it.next();
assertEquals(passphrase, protector.getPassphraseFor(key)); assertEquals(passphrase, protector.getPassphraseFor(key));
assertNotNull(protector.getEncryptor(key.getPublicKey())); assertNotNull(protector.getEncryptor(key));
assertNotNull(protector.getDecryptor(key.getKeyIdentifier())); assertNotNull(protector.getDecryptor(key));
} }
long nonMatching = findNonMatchingKeyId(keys); long nonMatching = findNonMatchingKeyId(keys);
assertNull(protector.getPassphraseFor(new KeyIdentifier(nonMatching))); assertNull(protector.getPassphraseFor(new KeyIdentifier(nonMatching)));
protector.forgetPassphrase(keys); protector.forgetPassphrase(keys);
it = keys.getSecretKeys(); it = keys.getSecretKeys().values().iterator();
while (it.hasNext()) { while (it.hasNext()) {
PGPSecretKey key = it.next(); OpenPGPKey.OpenPGPSecretKey key = it.next();
assertNull(protector.getPassphraseFor(key)); assertNull(protector.getPassphraseFor(key));
assertNull(protector.getEncryptor(key.getPublicKey())); assertNull(protector.getEncryptor(key.getPublicKey()));
assertNull(protector.getDecryptor(key.getKeyIdentifier())); assertNull(protector.getDecryptor(key.getKeyIdentifier()));
} }
} }
private static long findNonMatchingKeyId(PGPKeyRing keyRing) { private static long findNonMatchingKeyId(OpenPGPCertificate cert) {
Random random = new Random(); Random random = new Random();
long nonMatchingKeyId = 123L; long nonMatchingKeyId = 123L;
outerloop: while (true) { outerloop: while (true) {
Iterator<PGPPublicKey> pubKeys = keyRing.getPublicKeys(); Iterator<OpenPGPCertificate.OpenPGPComponentKey> pubKeys = cert.getKeys().iterator();
while (pubKeys.hasNext()) { while (pubKeys.hasNext()) {
if (pubKeys.next().getKeyID() == nonMatchingKeyId) { if (pubKeys.next().getKeyIdentifier().getKeyId() == nonMatchingKeyId) {
nonMatchingKeyId = random.nextLong(); nonMatchingKeyId = random.nextLong();
continue outerloop; continue outerloop;
} }

View file

@ -12,8 +12,8 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.api.OpenPGPCertificate;
import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.api.OpenPGPKey;
import org.bouncycastle.util.io.Streams; import org.bouncycastle.util.io.Streams;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
@ -22,7 +22,6 @@ import org.pgpainless.encryption_signing.EncryptionResult;
import org.pgpainless.encryption_signing.EncryptionStream; import org.pgpainless.encryption_signing.EncryptionStream;
import org.pgpainless.encryption_signing.ProducerOptions; import org.pgpainless.encryption_signing.ProducerOptions;
import org.pgpainless.key.WeirdKeys; import org.pgpainless.key.WeirdKeys;
import org.pgpainless.key.util.KeyRingUtils;
public class TestTwoSubkeysEncryption { public class TestTwoSubkeysEncryption {
@ -35,8 +34,8 @@ public class TestTwoSubkeysEncryption {
/** /**
* {@link WeirdKeys#TWO_CRYPT_SUBKEYS} is a key that has two subkeys which both carry the key flags * {@link WeirdKeys#TWO_CRYPT_SUBKEYS} is a key that has two subkeys which both carry the key flags
* {@link org.pgpainless.algorithm.KeyFlag#ENCRYPT_COMMS} and {@link org.pgpainless.algorithm.KeyFlag#ENCRYPT_STORAGE}. * {@link org.pgpainless.algorithm.KeyFlag#ENCRYPT_COMMS} and {@link org.pgpainless.algorithm.KeyFlag#ENCRYPT_STORAGE}.
* * <p>
* This test verifies that {@link EncryptionOptions#addRecipient(PGPPublicKeyRing, EncryptionOptions.EncryptionKeySelector)} * This test verifies that {@link EncryptionOptions#addRecipient(OpenPGPCertificate, EncryptionOptions.EncryptionKeySelector)}
* works properly, if {@link EncryptionOptions#encryptToAllCapableSubkeys()} is provided as argument. * works properly, if {@link EncryptionOptions#encryptToAllCapableSubkeys()} is provided as argument.
* *
* @throws IOException not expected * @throws IOException not expected
@ -44,10 +43,10 @@ public class TestTwoSubkeysEncryption {
*/ */
@Test @Test
public void testEncryptsToBothSubkeys() throws IOException, PGPException { public void testEncryptsToBothSubkeys() throws IOException, PGPException {
PGPSecretKeyRing twoSuitableSubkeysKeyRing = WeirdKeys.getTwoCryptSubkeysKey(); OpenPGPKey twoSuitableSubkeysKeyRing = WeirdKeys.getTwoCryptSubkeysKey();
PGPPublicKeyRing publicKeys = KeyRingUtils.publicKeyRingFrom(twoSuitableSubkeysKeyRing); OpenPGPCertificate publicKeys = twoSuitableSubkeysKeyRing.toCertificate();
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
EncryptionStream encryptionStream = PGPainless.encryptAndOrSign() EncryptionStream encryptionStream = PGPainless.getInstance().generateMessage()
.onOutputStream(out) .onOutputStream(out)
.withOptions( .withOptions(
ProducerOptions.encrypt(EncryptionOptions.get() ProducerOptions.encrypt(EncryptionOptions.get()