org.bouncycastle.openpgp.PGPSecretKeyRing

Here are the examples of the java api org.bouncycastle.openpgp.PGPSecretKeyRing taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

123 Examples 7

19 Source : OpenPGPKeyBasedEncryptor.java
with Apache License 2.0
from wangrenlei

private static PGPPrivateKey getDecryptedPrivateKey(String provider, String secretKeyringFile, long keyId, char[] preplacedphrase) throws IOException, PGPException {
    // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated
    // Read in from the secret keyring file
    try (FileInputStream keyInputStream = new FileInputStream(secretKeyringFile)) {
        // Form the SecretKeyRing collection (1.53 way with fingerprint calculator)
        PGPSecretKeyRingCollection pgpSecretKeyRingCollection = new PGPSecretKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator());
        // The decryptor is identical for all keys
        final PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(provider).build(preplacedphrase);
        // Iterate over all secret keyrings
        Iterator<PGPSecretKeyRing> keyringIterator = pgpSecretKeyRingCollection.getKeyRings();
        PGPSecretKeyRing keyRing;
        PGPSecretKey secretKey;
        while (keyringIterator.hasNext()) {
            keyRing = keyringIterator.next();
            // If keyId exists, get a specific secret key; else, iterate over all
            if (keyId != 0) {
                secretKey = keyRing.getSecretKey(keyId);
                try {
                    return secretKey.extractPrivateKey(decryptor);
                } catch (Exception e) {
                    throw new PGPException("No private key available using preplacedphrase", e);
                }
            } else {
                Iterator<PGPSecretKey> keyIterator = keyRing.getSecretKeys();
                while (keyIterator.hasNext()) {
                    secretKey = keyIterator.next();
                    try {
                        return secretKey.extractPrivateKey(decryptor);
                    } catch (Exception e) {
                    // TODO: Log (expected) failures?
                    }
                }
            }
        }
    }
    // If this point is reached, no private key could be extracted with the given preplacedphrase
    throw new PGPException("No private key available using preplacedphrase");
}

19 Source : ArmoredAsciiSigner.java
with Apache License 2.0
from spring-io

private PGPSecretKey getSigningKey(PGPSecretKeyRingCollection keyrings) {
    for (PGPSecretKeyRing keyring : keyrings) {
        Iterable<PGPSecretKey> secretKeys = keyring::getSecretKeys;
        for (PGPSecretKey candidate : secretKeys) {
            if (candidate.isSigningKey()) {
                return candidate;
            }
        }
    }
    throw new IllegalArgumentException("Keyring does not contain a suitable signing key");
}

19 Source : AptSigningFacet.java
with Eclipse Public License 1.0
from sonatype-nexus-community

private PGPSecretKey readSecretKey() throws IOException, PGPException {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(config.keypair.getBytes())), new JcaKeyFingerprintCalculator());
    Iterator<PGPSecretKeyRing> keyRings = pgpSec.getKeyRings();
    while (keyRings.hasNext()) {
        PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRings.next();
        Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
        while (keys.hasNext()) {
            PGPSecretKey key = (PGPSecretKey) keys.next();
            if (key.isSigningKey()) {
                return key;
            }
        }
    }
    throw new IllegalStateException("Can't find signing key in key ring.");
}

19 Source : PGPSecretKeyUtils.java
with Apache License 2.0
from s4u

/**
 * Verify expiration time of secret key.
 *
 * @param secretKey     a key to check
 * @param secretKeyRing a keyRing used for prepare message
 *
 * @throws PGPSignerException if key expired
 */
public static void verifyKeyExpiration(PGPSecretKey secretKey, PGPSecretKeyRing secretKeyRing) {
    long validSeconds = secretKey.getPublicKey().getValidSeconds();
    if (validSeconds > 0) {
        LocalDateTime expireDateTime = secretKey.getPublicKey().getCreationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().plusSeconds(validSeconds);
        if (LocalDateTime.now().isAfter(expireDateTime)) {
            throw new PGPSignerException(keyIdDescription(secretKey, secretKeyRing) + " was expired at: " + expireDateTime);
        }
    }
}

19 Source : PGPSecretKeyUtils.java
with Apache License 2.0
from s4u

/**
 * Generate string with key id description.
 *
 * @param secretKey     given key
 * @param secretKeyRing keys ring with master and sub keys
 *
 * @return string with key id description
 */
public static String keyIdDescription(PGPSecretKey secretKey, PGPSecretKeyRing secretKeyRing) {
    Optional<PGPSecretKey> masterKey = getMasterKey(secretKey, secretKeyRing);
    if (masterKey.isPresent()) {
        return String.format("SubKeyId: 0x%016X of %s", secretKey.getKeyID(), fingerprint(masterKey.get()));
    } else {
        return "KeyId: " + fingerprint(secretKey);
    }
}

19 Source : PGPSecretKeyUtils.java
with Apache License 2.0
from s4u

/**
 * List of user ids from secret key. If secret key is sub key list is taken from master key.
 *
 * @param secretKey     a secret key for user ids
 * @param secretKeyRing a keyRing of connected keys - need for sub key
 *
 * @return List user ids from key
 */
public static Collection<String> getUserIDs(PGPSecretKey secretKey, PGPSecretKeyRing secretKeyRing) {
    // use getRawUserIDs and standard java String to transform byte array to utf8
    // because BC generate exception if there is some problem in decoding utf8
    // https://github.com/s4u/pgpverify-maven-plugin/issues/61
    Set<byte[]> ret = new LinkedHashSet<>();
    secretKey.getPublicKey().getRawUserIDs().forEachRemaining(ret::add);
    getMasterKey(secretKey, secretKeyRing).ifPresent(masterKey -> masterKey.getPublicKey().getRawUserIDs().forEachRemaining(ret::add));
    return ret.stream().map(b -> new String(b, StandardCharsets.UTF_8)).collect(Collectors.toSet());
}

19 Source : PGPUtils.java
with MIT License
from quan-to

static PGPSecretKey getSecretKey(String privateKeyData) throws IOException, PGPException {
    PGPPrivateKey privKey = null;
    try (InputStream privStream = new ArmoredInputStream(new ByteArrayInputStream(privateKeyData.getBytes("UTF-8")))) {
        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privStream), new JcaKeyFingerprintCalculator());
        Iterator keyRingIter = pgpSec.getKeyRings();
        while (keyRingIter.hasNext()) {
            PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();
            Iterator keyIter = keyRing.getSecretKeys();
            while (keyIter.hasNext()) {
                PGPSecretKey key = (PGPSecretKey) keyIter.next();
                if (key.isSigningKey()) {
                    return key;
                }
            }
        }
    }
    throw new IllegalArgumentException("Can't find signing key in key ring.");
}

19 Source : Module.java
with MIT License
from quan-to

@ReactMethod
public void generateKeyPair(final String userId, final int numBits, final String preplacedphrase, Promise promise) {
    Log.d("ReactNativePGP", "generateKeyPair");
    try {
        WritableMap resultMap = Arguments.createMap();
        PGPKeyRingGenerator keyGenerator = PGPUtils.generateKeyRingGenerator(userId, numBits, preplacedphrase.toCharArray());
        // public key
        PGPPublicKeyRing publicKeyRing = keyGenerator.generatePublicKeyRing();
        ByteArrayOutputStream publicKeyOutputStream = new ByteArrayOutputStream();
        ArmoredOutputStream armoredPubOutputStream = new ArmoredOutputStream(publicKeyOutputStream);
        publicKeyRing.encode(armoredPubOutputStream);
        armoredPubOutputStream.close();
        resultMap.putString("publicKey", publicKeyOutputStream.toString("UTF-8"));
        // private key
        PGPSecretKeyRing secretKeyRing = keyGenerator.generateSecretKeyRing();
        ByteArrayOutputStream privateKeyOutputStream = new ByteArrayOutputStream();
        ArmoredOutputStream armoredPrivOutputStream = new ArmoredOutputStream(privateKeyOutputStream);
        secretKeyRing.encode(armoredPrivOutputStream);
        armoredPrivOutputStream.close();
        resultMap.putString("privateKey", privateKeyOutputStream.toString("UTF-8"));
        resultMap.putString("fingerPrint", Utils.bytesToHex(secretKeyRing.getPublicKey().getFingerprint()));
        promise.resolve(resultMap);
    } catch (Exception e) {
        promise.reject(new Exception(e.getMessage()));
    }
}

19 Source : KeyFilesOperationsPgpImpl.java
with GNU General Public License v3.0
from pgptool

protected static KeyInfo buildKeyInfoFromSecret(PGPSecretKeyRing secretKeyRing) throws PGPException {
    KeyInfo ret = new KeyInfo();
    ret.setKeyType(KeyTypeEnum.KeyPair);
    PGPPublicKey key = secretKeyRing.getPublicKey();
    ret.setUser(buildUser(key.getUserIDs()));
    ret.setKeyId(KeyDataPgp.buildKeyIdStr(key.getKeyID()));
    fillDates(ret, key);
    fillAlgorithmName(ret, key);
    return ret;
}

19 Source : KeyDataPgp.java
with GNU General Public License v3.0
from pgptool

/**
 * Impl of key data which stores pgp key. For one key pair there will be "ring"
 * of secret info and "ring" for public info. It's weird for naked eye.
 *
 * @author Sergey Karpushin
 */
public clreplaced KeyDataPgp extends KeyData {

    private static final long serialVersionUID = -8446784970537981225L;

    private transient PGPSecretKeyRing secretKeyRing;

    private transient PGPPublicKeyRing publicKeyRing;

    public static KeyDataPgp cast(KeyData keyData) {
        if (keyData == null) {
            return null;
        }
        Preconditions.checkArgument(keyData instanceof KeyDataPgp, "keyData is expected to be of type KeyDataPgp");
        return (KeyDataPgp) keyData;
    }

    public static KeyDataPgp get(Key key) {
        Preconditions.checkArgument(key != null, "Key must not be null");
        return cast(key.getKeyData());
    }

    @Override
    public boolean isCanBeUsedForDecryption() {
        return secretKeyRing != null;
    }

    @Override
    public boolean isCanBeUsedForEncryption() {
        return findKeyForEncryption() != null;
    }

    public PGPPublicKey findKeyForEncryption() {
        if (getPublicKeyRing() != null) {
            return findKeyForEncryption(getPublicKeyRing().getPublicKeys());
        } else if (getSecretKeyRing() != null) {
            return findKeyForEncryption(getSecretKeyRing().getPublicKeys());
        } else {
            return null;
        }
    }

    private static PGPPublicKey findKeyForEncryption(Iterator<PGPPublicKey> publicKeys) {
        for (Iterator<PGPPublicKey> iter = publicKeys; iter.hasNext(); ) {
            PGPPublicKey pk = iter.next();
            if (pk.isEncryptionKey()) {
                return pk;
            }
        }
        return null;
    }

    private void writeObject(ObjectOutputStream oos) throws IOException {
        oos.defaultWriteObject();
        oos.writeBoolean(secretKeyRing != null);
        if (secretKeyRing != null) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            secretKeyRing.encode(os);
            oos.writeObject(os.toByteArray());
        }
        oos.writeBoolean(publicKeyRing != null);
        if (publicKeyRing != null) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            publicKeyRing.encode(os);
            // 
            oos.writeObject(os.toByteArray());
        }
    }

    private void readObject(ObjectInputStream ois) throws ClreplacedNotFoundException, IOException {
        ois.defaultReadObject();
        try {
            if (ois.readBoolean()) {
                secretKeyRing = new PGPSecretKeyRing(initInputStream(ois), KeyFilesOperationsPgpImpl.fingerprintCalculator);
            }
            if (ois.readBoolean()) {
                publicKeyRing = new PGPPublicKeyRing(initInputStream(ois), KeyFilesOperationsPgpImpl.fingerprintCalculator);
            }
        } catch (PGPException e) {
            throw new IOException("Failed to read key", e);
        }
    }

    private ByteArrayInputStream initInputStream(ObjectInputStream ois) throws IOException, ClreplacedNotFoundException {
        byte[] buf = (byte[]) ois.readObject();
        ByteArrayInputStream is = new ByteArrayInputStream(buf);
        return is;
    }

    public PGPSecretKeyRing getSecretKeyRing() {
        return secretKeyRing;
    }

    public void setSecretKeyRing(PGPSecretKeyRing secretKeyRing) {
        this.secretKeyRing = secretKeyRing;
    }

    /**
     * @return PGPPublicKeyRing or NULL if it's not separately defined. If it's NULL
     *         check secret key ring. It's might be NULL if only private key ring
     *         was imported without separate public ring
     */
    public PGPPublicKeyRing getPublicKeyRing() {
        return publicKeyRing;
    }

    public void setPublicKeyRing(PGPPublicKeyRing publicKeyRing) {
        this.publicKeyRing = publicKeyRing;
    }

    public static String buildKeyIdStr(long keyID) {
        return Long.toHexString(keyID).toUpperCase();
    }

    public static long parseIdString(String hexId) {
        return new BigInteger(hexId, 16).longValue();
    }

    @Override
    public boolean isHasAlternativeId(String alternativeId) {
        long id = parseIdString(alternativeId);
        if (secretKeyRing != null) {
            return secretKeyRing.getSecretKey(id) != null;
        } else if (publicKeyRing != null) {
            return publicKeyRing.getPublicKey(id) != null;
        }
        return false;
    }

    public PGPSecretKey findSecretKeyById(String alternativeId) {
        long id = parseIdString(alternativeId);
        if (secretKeyRing != null) {
            return secretKeyRing.getSecretKey(id);
        }
        return null;
    }
}

19 Source : KeyDataPgp.java
with GNU General Public License v3.0
from pgptool

public void setSecretKeyRing(PGPSecretKeyRing secretKeyRing) {
    this.secretKeyRing = secretKeyRing;
}

19 Source : TestEncryptCommsStorageFlagsDifferentiated.java
with Apache License 2.0
from pgpainless

@Test
public void testThatEncryptionDifferentiatesBetweenPurposeKeyFlags() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, IOException {
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().withPrimaryKey(KeySpec.getBuilder(KeyType.RSA(RsaLength._3072)).withKeyFlags(KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA, // no ENCRYPT_COMMS
    KeyFlag.ENCRYPT_STORAGE).withDefaultAlgorithms()).withPrimaryUserId("[email protected]").withoutPreplacedphrase().build();
    PGPPublicKeyRing publicKeys = KeyRingUtils.publicKeyRingFrom(secretKeys);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    EncryptionBuilderInterface.ToRecipients builder = PGPainless.encryptAndOrSign(EncryptionStream.Purpose.COMMUNICATIONS).onOutputStream(out);
    // since the key does not carry the flag ENCRYPT_COMMS, it cannot be used by the stream.
    replacedertThrows(IllegalArgumentException.clreplaced, () -> builder.toRecipients(publicKeys));
}

19 Source : WhitelistKeyRingSelectionStrategyTest.java
with Apache License 2.0
from pgpainless

@Test
public void testWithSecretKeys() throws IOException, PGPException {
    Map<String, Set<Long>> ids = new ConcurrentHashMap<>();
    ids.put(TestKeys.JULIET_UID, Collections.singleton(TestKeys.JULIET_KEY_ID));
    Whitelist.SecRingSelectionStrategy<String> selectionStrategy = new Whitelist.SecRingSelectionStrategy<>(ids);
    PGPSecretKeyRing julietsKeys = TestKeys.getJulietSecretKeyRing();
    PGPSecretKeyRing romeosKeys = TestKeys.getRomeoSecretKeyRing();
    replacedertTrue(selectionStrategy.accept(TestKeys.JULIET_UID, julietsKeys));
    replacedertFalse(selectionStrategy.accept(TestKeys.JULIET_UID, romeosKeys));
    replacedertFalse(selectionStrategy.accept(TestKeys.ROMEO_UID, julietsKeys));
}

19 Source : KeyRingsFromCollectionTest.java
with Apache License 2.0
from pgpainless

@Test
public void selectSecretKeyRingMapFromSecretKeyRingCollectionMapTest() throws IOException, PGPException {
    PGPSecretKeyRing emil = TestKeys.getEmilSecretKeyRing();
    PGPSecretKeyRing juliet = TestKeys.getJulietSecretKeyRing();
    MultiMap<String, PGPSecretKeyRingCollection> map = new MultiMap<>();
    PGPSecretKeyRingCollection julietCollection = new PGPSecretKeyRingCollection(Arrays.asList(emil, juliet));
    map.put(TestKeys.JULIET_UID, julietCollection);
    PGPSecretKeyRingCollection emilCollection = new PGPSecretKeyRingCollection(Collections.singletonList(emil));
    map.put(TestKeys.EMIL_UID, emilCollection);
    replacedertEquals(2, julietCollection.size());
    map.put("invalidId", emilCollection);
    SecretKeyRingSelectionStrategy<String> strategy = new ExactUserId.SecRingSelectionStrategy();
    MultiMap<String, PGPSecretKeyRing> selected = strategy.selectKeyRingsFromCollections(map);
    replacedertEquals(1, selected.get(TestKeys.JULIET_UID).size());
    replacedertEquals(1, selected.get(TestKeys.EMIL_UID).size());
    replacedertNull(selected.get("invalidId"));
}

19 Source : KeyRingsFromCollectionTest.java
with Apache License 2.0
from pgpainless

@Test
public void selectSecretKeyRingFromSecretKeyRingCollectionTest() throws IOException, PGPException {
    PGPSecretKeyRing emil = TestKeys.getEmilSecretKeyRing();
    PGPSecretKeyRing juliet = TestKeys.getJulietSecretKeyRing();
    PGPSecretKeyRingCollection collection = new PGPSecretKeyRingCollection(Arrays.asList(emil, juliet));
    SecretKeyRingSelectionStrategy<String> strategy = new ExactUserId.SecRingSelectionStrategy();
    Set<PGPSecretKeyRing> secretKeyRings = strategy.selectKeyRingsFromCollection(TestKeys.JULIET_UID, collection);
    replacedertEquals(1, secretKeyRings.size());
    replacedertEquals(juliet.getPublicKey().getKeyID(), secretKeyRings.iterator().next().getPublicKey().getKeyID());
}

19 Source : KeyFlagBasedSelectionStrategyTest.java
with Apache License 2.0
from pgpainless

@Test
public void testSelectKeysFromKeyRing() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().withSubKey(KeySpec.getBuilder(KeyType.ECDSA(EllipticCurve._P256)).withKeyFlags(KeyFlag.SIGN_DATA).withDefaultAlgorithms()).withSubKey(KeySpec.getBuilder(KeyType.XDH(XDHCurve._X25519)).withKeyFlags(KeyFlag.ENCRYPT_COMMS).withDefaultAlgorithms()).withPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519)).withKeyFlags(KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA, KeyFlag.AUTHENTICATION).withDefaultAlgorithms()).withPrimaryUserId("[email protected]").withoutPreplacedphrase().build();
    HasAnyKeyFlagSelectionStrategy.SecretKey secSelection = new HasAnyKeyFlagSelectionStrategy.SecretKey(KeyFlag.SIGN_DATA);
    Set<PGPSecretKey> secSigningKeys = secSelection.selectKeysFromKeyRing(secretKeys);
    replacedertEquals(2, secSigningKeys.size());
    PGPPublicKeyRing publicKeys = KeyRingUtils.publicKeyRingFrom(secretKeys);
    HasAnyKeyFlagSelectionStrategy.PublicKey pubSelection = new HasAnyKeyFlagSelectionStrategy.PublicKey(KeyFlag.SIGN_DATA);
    Set<PGPPublicKey> pubSigningKeys = pubSelection.selectKeysFromKeyRing(publicKeys);
    replacedertEquals(2, pubSigningKeys.size());
    List<Long> ids = new ArrayList<>();
    for (PGPSecretKey secretKey : secSigningKeys) {
        ids.add(secretKey.getKeyID());
    }
    for (PGPPublicKey publicKey : pubSigningKeys) {
        replacedertTrue(ids.contains(publicKey.getKeyID()));
    }
    secSelection = new HasAnyKeyFlagSelectionStrategy.SecretKey(KeyFlag.ENCRYPT_STORAGE);
    replacedertTrue(secSelection.selectKeysFromKeyRing(secretKeys).isEmpty());
}

19 Source : KeyFlagBasedSelectionStrategyTest.java
with Apache License 2.0
from pgpainless

@Test
public void testKeyFlagSelectors() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().withSubKey(KeySpec.getBuilder(KeyType.ECDSA(EllipticCurve._P256)).withKeyFlags(KeyFlag.SIGN_DATA).withDefaultAlgorithms()).withSubKey(KeySpec.getBuilder(KeyType.XDH(XDHCurve._X25519)).withKeyFlags(KeyFlag.ENCRYPT_COMMS).withDefaultAlgorithms()).withPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519)).withKeyFlags(KeyFlag.CERTIFY_OTHER, KeyFlag.AUTHENTICATION).withDefaultAlgorithms()).withPrimaryUserId("[email protected]").withoutPreplacedphrase().build();
    Iterator<PGPSecretKey> iterator = secretKeys.iterator();
    // CERTIFY_OTHER and AUTHENTICATION
    PGPSecretKey s_primaryKey = iterator.next();
    // SIGN_DATA
    PGPSecretKey s_signingKey = iterator.next();
    // ENCRYPT_COMMS
    PGPSecretKey s_encryptionKey = iterator.next();
    HasAllKeyFlagSelectionStrategy.SecretKey s_certifyOther = new HasAllKeyFlagSelectionStrategy.SecretKey(KeyFlag.CERTIFY_OTHER);
    HasAllKeyFlagSelectionStrategy.SecretKey s_encryptComms = new HasAllKeyFlagSelectionStrategy.SecretKey(KeyFlag.ENCRYPT_COMMS);
    HasAllKeyFlagSelectionStrategy.SecretKey s_encryptCommsEncryptStorage = new HasAllKeyFlagSelectionStrategy.SecretKey(KeyFlag.ENCRYPT_COMMS, KeyFlag.ENCRYPT_STORAGE);
    HasAnyKeyFlagSelectionStrategy.SecretKey s_anyEncryptCommsEncryptStorage = new HasAnyKeyFlagSelectionStrategy.SecretKey(KeyFlag.ENCRYPT_COMMS, KeyFlag.ENCRYPT_STORAGE);
    replacedertTrue(s_certifyOther.accept(s_primaryKey));
    replacedertFalse(s_certifyOther.accept(s_encryptionKey));
    replacedertFalse(s_certifyOther.accept(s_signingKey));
    replacedertTrue(s_encryptComms.accept(s_encryptionKey));
    replacedertFalse(s_encryptComms.accept(s_primaryKey));
    replacedertFalse(s_encryptComms.accept(s_signingKey));
    replacedertFalse(s_encryptCommsEncryptStorage.accept(s_encryptionKey), "Must not accept the key, as it only carries ENCRYPT_COMMS, but not ENCRYPT_STORAGE");
    replacedertFalse(s_encryptCommsEncryptStorage.accept(s_primaryKey));
    replacedertFalse(s_encryptCommsEncryptStorage.accept(s_signingKey));
    replacedertTrue(s_anyEncryptCommsEncryptStorage.accept(s_encryptionKey));
    replacedertFalse(s_anyEncryptCommsEncryptStorage.accept(s_primaryKey));
    replacedertFalse(s_anyEncryptCommsEncryptStorage.accept(s_signingKey));
    PGPPublicKey p_primaryKey = s_primaryKey.getPublicKey();
    PGPPublicKey p_encryptionKey = s_encryptionKey.getPublicKey();
    PGPPublicKey p_signingKey = s_signingKey.getPublicKey();
    HasAllKeyFlagSelectionStrategy.PublicKey p_certifyOther = new HasAllKeyFlagSelectionStrategy.PublicKey(KeyFlag.CERTIFY_OTHER);
    HasAllKeyFlagSelectionStrategy.PublicKey p_encryptComms = new HasAllKeyFlagSelectionStrategy.PublicKey(KeyFlag.ENCRYPT_COMMS);
    HasAllKeyFlagSelectionStrategy.PublicKey p_encryptCommsEncryptStorage = new HasAllKeyFlagSelectionStrategy.PublicKey(KeyFlag.ENCRYPT_COMMS, KeyFlag.ENCRYPT_STORAGE);
    HasAnyKeyFlagSelectionStrategy.PublicKey p_anyEncryptCommsEncryptStorage = new HasAnyKeyFlagSelectionStrategy.PublicKey(KeyFlag.ENCRYPT_COMMS, KeyFlag.ENCRYPT_STORAGE);
    replacedertTrue(p_certifyOther.accept(p_primaryKey));
    replacedertFalse(p_certifyOther.accept(p_encryptionKey));
    replacedertFalse(p_certifyOther.accept(p_signingKey));
    replacedertTrue(p_encryptComms.accept(p_encryptionKey));
    replacedertFalse(p_encryptComms.accept(p_primaryKey));
    replacedertFalse(p_encryptComms.accept(p_signingKey));
    replacedertFalse(p_encryptCommsEncryptStorage.accept(p_encryptionKey), "Must not accept the key, as it only carries ENCRYPT_COMMS, but not ENCRYPT_STORAGE");
    replacedertFalse(p_encryptCommsEncryptStorage.accept(p_primaryKey));
    replacedertFalse(p_encryptCommsEncryptStorage.accept(p_signingKey));
    replacedertTrue(p_anyEncryptCommsEncryptStorage.accept(p_encryptionKey));
    replacedertFalse(p_anyEncryptCommsEncryptStorage.accept(p_primaryKey));
    replacedertFalse(p_anyEncryptCommsEncryptStorage.accept(p_signingKey));
}

19 Source : BCUtilTest.java
with Apache License 2.0
from pgpainless

@Test
public void removeUnsignedKeysTest() throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    @SuppressWarnings("deprecation")
    PGPSecretKeyRing alice = PGPainless.generateKeyRing().simpleRsaKeyRing("[email protected]", RsaLength._1024);
    PGPSecretKeyRing mallory = PGPainless.generateKeyRing().simpleEcKeyRing("[email protected]");
    PGPSecretKey subKey = null;
    Iterator<PGPSecretKey> sit = mallory.getSecretKeys();
    while (sit.hasNext()) {
        PGPSecretKey s = sit.next();
        if (!s.isMasterKey()) {
            subKey = s;
            break;
        }
    }
    replacedertNotNull(subKey);
    PGPSecretKeyRing alice_mallory = PGPSecretKeyRing.insertSecretKey(alice, subKey);
    // Check, if alice_mallory contains mallory's key
    replacedertNotNull(alice_mallory.getSecretKey(subKey.getKeyID()));
    PGPSecretKeyRing cleaned = BCUtil.removeUnreplacedociatedKeysFromKeyRing(alice_mallory, alice.getPublicKey());
    replacedertNull(cleaned.getSecretKey(subKey.getKeyID()));
}

19 Source : BCUtilTest.java
with Apache License 2.0
from pgpainless

@Test
public void getMasterKeyFromRingTest() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    PGPPublicKey primaryKey = BCUtil.getMasterKeyFrom(secretKeys);
    replacedertNotNull(primaryKey);
    replacedertEquals(TestKeys.CRYPTIE_FINGERPRINT, new OpenPgpV4Fingerprint(primaryKey));
}

19 Source : BCUtilTest.java
with Apache License 2.0
from pgpainless

@Test
public void keyRingToCollectionTest() throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException {
    PGPSecretKeyRing sec = PGPainless.generateKeyRing().withSubKey(KeySpec.getBuilder(KeyType.RSA(RsaLength._3072)).withKeyFlags(KeyFlag.ENCRYPT_COMMS).withDefaultAlgorithms()).withPrimaryKey(KeySpec.getBuilder(KeyType.RSA(RsaLength._3072)).withKeyFlags(KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA).withDefaultAlgorithms()).withPrimaryUserId("[email protected]").withoutPreplacedphrase().build();
    PGPPublicKeyRing pub = KeyRingUtils.publicKeyRingFrom(sec);
    LOGGER.log(Level.FINER, "Main ID: " + sec.getPublicKey().getKeyID() + " " + pub.getPublicKey().getKeyID());
    int secSize = 1;
    Iterator<PGPPublicKey> secPubIt = sec.getPublicKeys();
    while (secPubIt.hasNext()) {
        PGPPublicKey k = secPubIt.next();
        LOGGER.log(Level.FINER, secSize + " " + k.getKeyID() + " " + k.isEncryptionKey() + " " + k.isMasterKey());
        secSize++;
    }
    LOGGER.log(Level.FINER, "After BCUtil.publicKeyRingFromSecretKeyRing()");
    int pubSize = 1;
    Iterator<PGPPublicKey> pubPubIt = pub.getPublicKeys();
    while (pubPubIt.hasNext()) {
        PGPPublicKey k = pubPubIt.next();
        LOGGER.log(Level.FINER, pubSize + " " + k.getKeyID() + " " + k.isEncryptionKey() + " " + k.isMasterKey());
        pubSize++;
    }
    replacedertEquals(secSize, pubSize);
    PGPSecretKeyRingCollection secCol = BCUtil.keyRingsToKeyRingCollection(sec);
    int secColSize = 0;
    Iterator<PGPSecretKeyRing> secColIt = secCol.getKeyRings();
    while (secColIt.hasNext()) {
        PGPSecretKeyRing r = secColIt.next();
        LOGGER.log(Level.FINER, "" + r.getPublicKey().getKeyID());
        secColSize++;
    }
    LOGGER.log(Level.FINER, "SecCol: " + secColSize);
    PGPPublicKeyRingCollection pubCol = BCUtil.keyRingsToKeyRingCollection(pub);
    int pubColSize = 0;
    Iterator<PGPPublicKeyRing> pubColIt = pubCol.getKeyRings();
    while (pubColIt.hasNext()) {
        PGPPublicKeyRing r = pubColIt.next();
        LOGGER.log(Level.FINER, "" + r.getPublicKey().getKeyID());
        pubColSize++;
    }
    LOGGER.log(Level.FINER, "PubCol: " + pubColSize);
}

19 Source : TestKeysTest.java
with Apache License 2.0
from pgpainless

public clreplaced TestKeysTest {

    private final PGPSecretKeyRing julietSecRing;

    private final PGPSecretKeyRing romeoSecRing;

    private final PGPSecretKeyRing emilSecRing;

    private final PGPPublicKeyRing julietPubRing;

    private final PGPPublicKeyRing romeoPubRing;

    private final PGPPublicKeyRing emilPubRing;

    public TestKeysTest() throws IOException, PGPException {
        this.julietSecRing = TestKeys.getJulietSecretKeyRing();
        this.romeoSecRing = TestKeys.getRomeoSecretKeyRing();
        this.emilSecRing = TestKeys.getEmilSecretKeyRing();
        this.julietPubRing = TestKeys.getJulietPublicKeyRing();
        this.romeoPubRing = TestKeys.getRomeoPublicKeyRing();
        this.emilPubRing = TestKeys.getEmilPublicKeyRing();
    }

    @Test
    public void replacedertJulietsPublicKeyIsSameInPubRingAndSecRing() throws IOException {
        replacedertArrayEquals(julietSecRing.getPublicKey().getEncoded(), julietPubRing.getPublicKey().getEncoded());
    }

    @Test
    public void replacedertJulietsKeysIdEquals() {
        replacedertEquals(TestKeys.JULIET_KEY_ID, julietSecRing.getSecretKey().getKeyID());
        replacedertEquals(TestKeys.JULIET_KEY_ID, julietSecRing.getPublicKey().getKeyID());
        replacedertEquals(TestKeys.JULIET_KEY_ID, julietPubRing.getPublicKey().getKeyID());
    }

    @Test
    public void replacedertJulietsKeyUIDEquals() {
        replacedertEquals(TestKeys.JULIET_UID, julietSecRing.getPublicKey().getUserIDs().next());
        replacedertEquals(1, TestUtils.getNumberOfItemsInIterator(julietSecRing.getPublicKey().getUserIDs()));
    }

    @Test
    public void replacedertJulietsKeyRingFingerprintMatches() {
        replacedertEquals(TestKeys.JULIET_FINGERPRINT, new OpenPgpV4Fingerprint(julietSecRing));
    }

    @Test
    public void replacedertJulietsPublicKeyFingerprintMatchesHerSecretKeyFingerprint() {
        replacedertEquals(new OpenPgpV4Fingerprint(julietSecRing.getPublicKey()), new OpenPgpV4Fingerprint(julietSecRing.getSecretKey()));
    }

    @Test
    public void replacedertJulietsFingerprintGetKeyIdMatches() {
        replacedertEquals(TestKeys.JULIET_KEY_ID, TestKeys.JULIET_FINGERPRINT.getKeyId(), "calling getKeyId() on juliet's fingerprint must return her key id.");
    }

    @Test
    public void replacedertRomeosPublicKeyIsSameInPubRingAndSecRing() throws IOException {
        replacedertArrayEquals(romeoSecRing.getPublicKey().getEncoded(), romeoPubRing.getPublicKey().getEncoded());
    }

    @Test
    public void replacedertRomeosKeyIdEquals() {
        replacedertEquals(TestKeys.ROMEO_KEY_ID, romeoSecRing.getSecretKey().getKeyID(), "Key ID of Romeo's secret key must match his key id.");
    }

    @Test
    public void replacedertRomeosKeyUIDMatches() {
        replacedertEquals(TestKeys.ROMEO_UID, romeoSecRing.getPublicKey().getUserIDs().next());
    }

    @Test
    public void replacedertRomeosKeyRingFingerprintMatches() {
        replacedertEquals(TestKeys.ROMEO_FINGERPRINT, new OpenPgpV4Fingerprint(romeoSecRing));
    }

    @Test
    public void replacedertRomeosPublicKeyFingerprintMatchesHisSecretKeyFingerprint() {
        replacedertEquals(new OpenPgpV4Fingerprint(romeoSecRing.getPublicKey()), new OpenPgpV4Fingerprint(romeoSecRing.getSecretKey()));
    }

    @Test
    public void replacedertRomesKeysFingerprintMatches() {
        replacedertEquals(TestKeys.ROMEO_KEY_ID, TestKeys.ROMEO_FINGERPRINT.getKeyId());
    }

    @Test
    public void replacedertRomeosSecretKeyRingHreplacedamePublicKeyId() throws IOException {
        PGPPublicKeyRing julietsPublicKeys = TestKeys.getJulietPublicKeyRing();
        replacedertEquals(julietSecRing.getPublicKey().getKeyID(), julietsPublicKeys.getPublicKey().getKeyID());
    }

    @Test
    public void replacedertEmilsPublicKeyIsSameInPubRingAndSecRing() throws IOException {
        replacedertArrayEquals(emilSecRing.getPublicKey().getEncoded(), emilPubRing.getPublicKey().getEncoded());
    }

    @Test
    public void replacedertEmilsKeysIdEquals() {
        replacedertEquals(TestKeys.EMIL_KEY_ID, emilSecRing.getSecretKey().getKeyID());
        replacedertEquals(TestKeys.EMIL_KEY_ID, emilSecRing.getPublicKey().getKeyID());
        replacedertEquals(TestKeys.EMIL_KEY_ID, emilPubRing.getPublicKey().getKeyID());
    }

    @Test
    public void replacedertEmilsKeyUIDEquals() {
        replacedertEquals(TestKeys.EMIL_UID, emilSecRing.getPublicKey().getUserIDs().next());
        replacedertEquals(1, TestUtils.getNumberOfItemsInIterator(emilSecRing.getPublicKey().getUserIDs()));
    }

    @Test
    public void replacedertEmilsKeyRingFingerprintMatches() {
        replacedertEquals(TestKeys.EMIL_FINGERPRINT, new OpenPgpV4Fingerprint(emilSecRing));
    }

    @Test
    public void replacedertEmilsPublicKeyFingerprintMatchesHerSecretKeyFingerprint() {
        replacedertEquals(new OpenPgpV4Fingerprint(emilSecRing.getPublicKey()), new OpenPgpV4Fingerprint(emilSecRing.getSecretKey()));
    }

    @Test
    public void replacedertEmilsFingerprintGetKeyIdMatches() {
        replacedertEquals(TestKeys.EMIL_KEY_ID, TestKeys.EMIL_FINGERPRINT.getKeyId(), "calling getKeyId() on emil's fingerprint must return her key id.");
    }
}

19 Source : TestKeys.java
with Apache License 2.0
from pgpainless

public clreplaced TestKeys {

    private static final KeyFingerPrintCalculator calc = new BcKeyFingerprintCalculator();

    private static PGPSecretKeyRing julietSecretKeyRing = null;

    private static PGPPublicKeyRing julietPublicKeyRing = null;

    private static PGPSecretKeyRing romeoSecretKeyRing = null;

    private static PGPPublicKeyRing romeoPublicKeyRing = null;

    private static PGPSecretKeyRing emilSecretKeyRing = null;

    private static PGPPublicKeyRing emilPublicKeyRing = null;

    private static PGPSecretKeyRing cryptieSecretKeyRing = null;

    private static PGPPublicKeyRing cryptiePublicKeyRing = null;

    private static PGPSecretKeyRingCollection julietSecretKeyRingCollection = null;

    private static PGPPublicKeyRingCollection julietPublicKeyRingCollection = null;

    private static PGPSecretKeyRingCollection romeoSecretKeyRingCollection = null;

    private static PGPPublicKeyRingCollection romeoPublicKeyRingCollection = null;

    private static PGPSecretKeyRingCollection emilSecretKeyRingCollection = null;

    private static PGPPublicKeyRingCollection emilPublicKeyRingCollection = null;

    private static PGPSecretKeyRingCollection cryptieSecretKeyRingCollection = null;

    private static PGPPublicKeyRingCollection cryptiePublicKeyRingCollection = null;

    public static final String JULIET_UID = "xmpp:[email protected]";

    public static final long JULIET_KEY_ID = -5425419407118114754L;

    public static final String JULIET_FINGERPRINT_STRING = "1D018C772DF8C5EF86A1DCC9B4B509CB5936E03E";

    public static final OpenPgpV4Fingerprint JULIET_FINGERPRINT = new OpenPgpV4Fingerprint(JULIET_FINGERPRINT_STRING);

    /**
     * Public key of xmpp:[email protected].
     */
    public static final String JULIET_PUB = "" + "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "\n" + "mQENBFrxov4BCAChZwPrBxxIlwzpieR5T2pnaOZLWH0WqSON6rVjvfbJHWdDi3Th\n" + "remHW4gg4IBSTXkVFDIeQNVcOvGNgMg3Oe/x0I6FK12jrw9prycmjFxQ7A0ix7ZG\n" + "UkTF5jITgzJbkH100gYfXtZsfTyvgISSAT//6vvvQPZ3zCr09XvAG0CyQ1BhULsv\n" + "mVRe4Oh5b0VK4kLdv+GiA/T+49UKZj6lne9Vdti16ZIj7teVCbicfdhpTzsjur42\n" + "r8ptouKAuyFPw9KnGNwVlIiv5jt/Kit/LoOBenh74sitsCXq8IQ9kKp/eNt8TF4u\n" + "D4IGpxnJfB8XCiixYHoFEajmQBVJXNYtvoPvABEBAAG0F3htcHA6anVsaWV0QGNh\n" + "cHVsZXQubGl0iQFOBBMBCAA4FiEEHQGMdy34xe+GodzJtLUJy1k24D4FAlrxov4C\n" + "Gy8FCwkIBwIGFQoJCAsCBBYCAwECHgECF4AACgkQtLUJy1k24D6H7AgAoTjx4ezc\n" + "A83NeOY3tMHVQTM7hKuy0wMcSzQgVgJmhLYRZS8r+FocPZua/eke49GPhe2yozvl\n" + "ByWHtotklQeJiwOKxuPKMzneVA1ZK3/9LdGvtZlHMcAkEKDhit8HIaEcsFd4Z1re\n" + "EhF2lyvY/E+rrx9YxV0QjisSWV2dSptv6FeGSztr9e5E+Head6hEQhsugiTVRF+1\n" + "6mG90te0WGQ9YNiJ2FJovx5kBLTTuhwUz8Oacqihd2+RDDI5p3wJoogVL31aNb4n\n" + "c7dGo8ieJPHGlkBsOfmreSxijTodZz9MXsgcx7b//u0uQryViJoZHWbtnXOFjjNc\n" + "GWBtS084NKWl9w==\n" + "=ecwX\n" + "-----END PGP PUBLIC KEY BLOCK-----";

    /**
     * Private key of xmpp:[email protected].
     */
    public static final String JULIET_SEC = "" + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + "\n" + "lQOYBFrxov4BCAChZwPrBxxIlwzpieR5T2pnaOZLWH0WqSON6rVjvfbJHWdDi3Th\n" + "remHW4gg4IBSTXkVFDIeQNVcOvGNgMg3Oe/x0I6FK12jrw9prycmjFxQ7A0ix7ZG\n" + "UkTF5jITgzJbkH100gYfXtZsfTyvgISSAT//6vvvQPZ3zCr09XvAG0CyQ1BhULsv\n" + "mVRe4Oh5b0VK4kLdv+GiA/T+49UKZj6lne9Vdti16ZIj7teVCbicfdhpTzsjur42\n" + "r8ptouKAuyFPw9KnGNwVlIiv5jt/Kit/LoOBenh74sitsCXq8IQ9kKp/eNt8TF4u\n" + "D4IGpxnJfB8XCiixYHoFEajmQBVJXNYtvoPvABEBAAEAB/4jMbXagW3q7DkOEZnm\n" + "0+jVTLvu0QhRsScGEphj+++8sfMq+NVPQp9p+w0Hcjy49ZjB/mnhS+zaVCYI33yJ\n" + "AlKubXYuVqLwBsO7HUzRrIiSwq4ol9jIo7bIWmYv+As6iRq6JvPb0k+6T2K0uDbw\n" + "KWKduM0fwhAcVkJFsOO/o5GrbQaJc3oioFk8uFWTnO+FPBRTJ9oTlVG2M/tEatZK\n" + "gl7I8Ukl0YYruCNUFKZ0tvO8HqulxBgUbGPBer1uOlfUD4RXdc8/PUiFKNo48XSu\n" + "ZUEAZKGbFBjuX5Z8ha7+sUMEYEt70qlbkiLQxgHKAmpyridAk3q/SB3y2VB8Ik7I\n" + "gpExBADInzLROYuUcXqmty+znVwm6nRIB75JBAy778zgIxx1v0O3QlVnR+YI8gJM\n" + "mQ/9pD6LyP9hktWDmJxG8tX+kSuIp3wNJc5EMeXtCCmkUW0CP1gUhAbNW3MezKa5\n" + "II5IhE9RgIsYqSU8ZgeIh72ON8XTp8i/wGipCXvJPggSAMXukQQAzfRmtLW+JHEK\n" + "B8ETIYh8IUjXJ6TVlmuBwZ0eXjCpqy9arJi6tacesDJwnL3sqOMQWUmqGsCGSKA5\n" + "replacedkVsxX/htIq8GFyludjg8t4Nr+fOGfChEq8QE0PHE2CgskQMHpfHvfIdnwKve\n" + "Fg2Q8twoMw849O6PF3k/848Z65lDin8EAMDbuPWL7KU2sWeqvDEuoulS5K1gsq8X\n" + "p3Od3+f0OG8YViMjKcVlSKHVvdlK4dlsccJrJJx6VzotV47LsmvVbzDwUE//MYq7\n" + "QwwQetZbpdQZDysSGVqHMTuAg/1pr2u5rqh4cFqCYatgZwinEI2TQMXEqnSc+mj8\n" + "xp/LNq5BZZQuO4y0F3htcHA6anVsaWV0QGNhcHVsZXQubGl0iQFOBBMBCAA4FiEE\n" + "HQGMdy34xe+GodzJtLUJy1k24D4FAlrxov4CGy8FCwkIBwIGFQoJCAsCBBYCAwEC\n" + "HgECF4AACgkQtLUJy1k24D6H7AgAoTjx4ezcA83NeOY3tMHVQTM7hKuy0wMcSzQg\n" + "VgJmhLYRZS8r+FocPZua/eke49GPhe2yozvlByWHtotklQeJiwOKxuPKMzneVA1Z\n" + "K3/9LdGvtZlHMcAkEKDhit8HIaEcsFd4Z1reEhF2lyvY/E+rrx9YxV0QjisSWV2d\n" + "Sptv6FeGSztr9e5E+Head6hEQhsugiTVRF+16mG90te0WGQ9YNiJ2FJovx5kBLTT\n" + "uhwUz8Oacqihd2+RDDI5p3wJoogVL31aNb4nc7dGo8ieJPHGlkBsOfmreSxijTod\n" + "Zz9MXsgcx7b//u0uQryViJoZHWbtnXOFjjNcGWBtS084NKWl9w==\n" + "=yPPE\n" + "-----END PGP PRIVATE KEY BLOCK-----";

    public static final String ROMEO_UID = "xmpp:[email protected]";

    public static final long ROMEO_KEY_ID = 334147643349279223L;

    public static final String ROMEO_FINGERPRINT_STRING = "35D299D08A2F7D80230B095D04A32182E05E21F7";

    public static final OpenPgpV4Fingerprint ROMEO_FINGERPRINT = new OpenPgpV4Fingerprint(ROMEO_FINGERPRINT_STRING);

    /**
     * Public key of xmpp:[email protected].
     */
    public static final String ROMEO_PUB = "" + "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "\n" + "mQENBFrxopkBCADiYg/+mEObXgxuMW6/LFKpEyaJK9pBMgutuxnYZ9PXWZmOhDIT\n" + "Ugm9X9YJ3Qh94KaHge9F4uCeFASmM1vvUTRFTEb1W5RR9ZE/sy/cdAttnZ5JloPi\n" + "CT3HDMIJAxIXhRJkeUR9GUb51ql27bMXl6lFh865VdNSXN/B8FzRQHENxv1Bq/6Z\n" + "iQOViIETeRRgO+u6u2iZkYlHgYMaoMK7+YiNlHXanU9Atcuaz0ZCJS/XFNH89iqB\n" + "Kvnv7KCQh4FhrNMLJRzNPXV8MY05nn0zF72qeEsniB16Xde18lMro8fQehg2mLwc\n" + "XGtCwCKI6QbZVxYQt77r3ZACiwl66soFWijVABEBAAG0F3htcHA6cm9tZW9AbW9u\n" + "dGFndWUubGl0iQFOBBMBCAA4FiEENdKZ0IovfYAjCwldBKMhguBeIfcFAlrxopkC\n" + "Gy8FCwkIBwIGFQoJCAsCBBYCAwECHgECF4AACgkQBKMhguBeIfcj8AgAu1wubUwr\n" + "2aQmDN3OqRM4M4yRL3oyYMkCKIjqD6KEeFsIXSSkXOuREJKEo8Mb1+ewV0SYmHCC\n" + "K3bKKq3m71AQ7evDhKGshacPYesiDvMdHWQdQnjfaoHhyn9qIKl7H0Xv1yf/wyuG\n" + "ANy1jYgtCEuYw7D+EsqNDdn8Xh+k/9s4aMI/6mfC0yGZgG8EyLTfbZkGPoS4aZfV\n" + "AGFbuqryg48dXtnuzAPKcdgMTTMSnmR729YlfkjCffcFaldyXoe1VMbudUO7nkO9\n" + "g65i5EXenkbc2h0TRDQ4lDFQyModqFTwYFYxAf/RA6tuhIQEoCnpCytFMvrRKMb3\n" + "Bx5vYRDVmE3jeg==\n" + "=2jSg\n" + "-----END PGP PUBLIC KEY BLOCK-----";

    /**
     * Private key of xmpp:[email protected].
     */
    public static final String ROMEO_SEC = "" + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + "\n" + "lQOYBFrxopkBCADiYg/+mEObXgxuMW6/LFKpEyaJK9pBMgutuxnYZ9PXWZmOhDIT\n" + "Ugm9X9YJ3Qh94KaHge9F4uCeFASmM1vvUTRFTEb1W5RR9ZE/sy/cdAttnZ5JloPi\n" + "CT3HDMIJAxIXhRJkeUR9GUb51ql27bMXl6lFh865VdNSXN/B8FzRQHENxv1Bq/6Z\n" + "iQOViIETeRRgO+u6u2iZkYlHgYMaoMK7+YiNlHXanU9Atcuaz0ZCJS/XFNH89iqB\n" + "Kvnv7KCQh4FhrNMLJRzNPXV8MY05nn0zF72qeEsniB16Xde18lMro8fQehg2mLwc\n" + "XGtCwCKI6QbZVxYQt77r3ZACiwl66soFWijVABEBAAEAB/4mu5p69/hRQ+UikWie\n" + "Yun9rZ4hSBR+pR5kaifA4/rV1Km2PZ4HujiaYyRO6beDOgWkF7IlpezCfzBQc2ce\n" + "ailkVemqHzIgV8CzQmhE8sHlzlr/wjXsXaJpRSCJxDG7PnRoJmt2b/W512WFSKQk\n" + "vDklAVh4U1vlsqhCGWr4DmuJbJkRyDhcX01tplRwim283F7bGqRcMBmKMZHiMgVc\n" + "0u84EYKKVizJ3YAaaVqZyHb4qdeKK2ak3fPNuGT/oGd2sxnkL+BZGjJpu3RGpTA1\n" + "tbOvOQnJGHQtABFxE8n6H9dHPJGtgyz2+udjUhL/P/E3PDoXazZkXRq2oHZKgg0f\n" + "AwOBBADsWncHgvz15rXPF7O6AivbGTJ5ctkgVy4U3Fu2sk9rf0fx0sryBSqtTBw1\n" + "Uvn/p9RwTsKw6fng6Nf78xpZFlUDB00YCcuWkGodxvjTAyB0dtBmkhopeKi0dmHh\n" + "ndnR6Pv0CsXu8nG7lUi+q6s3oc4h2OfDBhrqsyYY5M2gGit3dQQA9TNuinJD9XXv\n" + "QRyauMnSJ5xRcfOu8QCxZlllCvffZjSGCPoVjUpJEe9qsVbXVj2GYCxjLCSXV0V+\n" + "vlJfdPrl1BhZ3fmEpg0u7SyGDDOe8fe1ehk5sAeL8O0eFWlPSEaEccsjlpJ2FO0n\n" + "P04SZdOeM6wmhDTEDzpFnjbPndQTH+ED/R1zNzr55DvxQodmrW/BvTmhGQ22rHtk\n" + "IUfbeMaVfUvNLJA/JksrUIx3Gga9QCDZgfm1RsRhLUlHiqTQe23sPWgKOsbf5O1j\n" + "XJZaCNZ7LloVQbkG7xFcnb/n1+JjBr4FxXjAA6cY/iRGlznjIIaasyklKm1/4LuQ\n" + "hnH3QqTvCN3dOFS0F3htcHA6cm9tZW9AbW9udGFndWUubGl0iQFOBBMBCAA4FiEE\n" + "NdKZ0IovfYAjCwldBKMhguBeIfcFAlrxopkCGy8FCwkIBwIGFQoJCAsCBBYCAwEC\n" + "HgECF4AACgkQBKMhguBeIfcj8AgAu1wubUwr2aQmDN3OqRM4M4yRL3oyYMkCKIjq\n" + "D6KEeFsIXSSkXOuREJKEo8Mb1+ewV0SYmHCCK3bKKq3m71AQ7evDhKGshacPYesi\n" + "DvMdHWQdQnjfaoHhyn9qIKl7H0Xv1yf/wyuGANy1jYgtCEuYw7D+EsqNDdn8Xh+k\n" + "/9s4aMI/6mfC0yGZgG8EyLTfbZkGPoS4aZfVAGFbuqryg48dXtnuzAPKcdgMTTMS\n" + "nmR729YlfkjCffcFaldyXoe1VMbudUO7nkO9g65i5EXenkbc2h0TRDQ4lDFQyMod\n" + "qFTwYFYxAf/RA6tuhIQEoCnpCytFMvrRKMb3Bx5vYRDVmE3jeg==\n" + "=LZ1b\n" + "-----END PGP PRIVATE KEY BLOCK-----";

    public static final String EMIL_UID = "<[email protected]>";

    public static final long EMIL_KEY_ID = 6284463849526474508L;

    public static final String EMIL_FINGERPRINT_STRING = "4F665C4DC2C4660BC6425E415736E6931ACF370C";

    public static final OpenPgpV4Fingerprint EMIL_FINGERPRINT = new OpenPgpV4Fingerprint(EMIL_FINGERPRINT_STRING);

    public static final Date EMIL_CREATION_DATE = new Date(1578852104000L);

    /**
     * Public key of <pre><[email protected]></pre>.
     */
    public static final String EMIL_PUB = "" + "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "Version: BCPG v1.64\n" + "\n" + "mFIEXhtfCBMIKoZIzj0DAQcCAwTGSFMBUOSLusXS8hdNHbdK3gN8hS7jd4ky7Czl\n" + "mSti+oVyRJUwQAFZJ1NMsg1H8flSJP1/9YbHd9FBU4bHKGKPtBE8ZW1pbEBlbWFp\n" + "bC51c2VyPoh1BBMTCgAdBQJeG18IAhsjBRYCAwEABAsJCAcFFQoJCAsCHgEACgkQ\n" + "VzbmkxrPNwz8rAD/S/VCQc5NJLArgTDkgrt3Q573HiYfrIQo1uk3dwV15WIBAMiq\n" + "oDmRMb8jzOBv6FGW4P5WAubPdnAvDD7XmArD+TSeuFYEXhtfCBIIKoZIzj0DAQcC\n" + "AwTgWDWmHJLQUQ35Qg/rINmUhkUhj1E4O5t6Y2PipbqlGfDufLmIKnX40BoJPS4G\n" + "HW7U0QXfwSaTXa1BAaNsMUomAwEIB4h1BBgTCgAdBQJeG18IAhsMBRYCAwEABAsJ\n" + "CAcFFQoJCAsCHgEACgkQVzbmkxrPNwxOcwEA19Fnhw7XwpQoT61Fqg54vroAwTZ3\n" + "T5A+LOdevAtzNOUA/RWeKfOGk6D+vKYRNpMJyqsHi/vBeKwXoeN0n6HuExVF\n" + "=a1W7\n" + "-----END PGP PUBLIC KEY BLOCK-----";

    /**
     * Secret key of <pre><[email protected]></pre>.
     */
    public static final String EMIL_SEC = "" + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + "Version: BCPG v1.64\n" + "\n" + "lHcEXhtfCBMIKoZIzj0DAQcCAwTGSFMBUOSLusXS8hdNHbdK3gN8hS7jd4ky7Czl\n" + "mSti+oVyRJUwQAFZJ1NMsg1H8flSJP1/9YbHd9FBU4bHKGKPAAD5AdecgJ92sAXP\n" + "l4U4oW6l4KKUb8IT3J5g68Z+Q9WIq6kS5bQRPGVtaWxAZW1haWwudXNlcj6IdQQT\n" + "EwoAHQUCXhtfCAIbIwUWAgMBAAQLCQgHBRUKCQgLAh4BAAoJEFc25pMazzcM/KwA\n" + "/0v1QkHOTSSwK4Ew5IK7d0Oe9x4mH6yEKNbpN3cFdeViAQDIqqA5kTG/I8zgb+hR\n" + "luD+VgLmz3ZwLww+15gKw/k0npx7BF4bXwgSCCqGSM49AwEHAgME4Fg1phyS0FEN\n" + "+UIP6yDZlIZFIY9RODubemNj4qW6pRnw7ny5iCp1+NAaCT0uBh1u1NEF38Emk12t\n" + "QQGjbDFKJgMBCAcAAQCMHcK/wrUR1R8HKvLUFzUB/a5zj1reOzQOsFtoLte3Mg6u\n" + "iHUEGBMKAB0FAl4bXwgCGwwFFgIDAQAECwkIBwUVCgkICwIeAQAKCRBXNuaTGs83\n" + "DE5zAQDX0WeHDtfClChPrUWqDni+ugDBNndPkD4s5168C3M05QD9FZ4p84aToP68\n" + "phE2kwnKqweL+8F4rBeh43Sfoe4TFUU=\n" + "=Pqd/\n" + "-----END PGP PRIVATE KEY BLOCK-----";

    public static final String CRYPTIE_UID = "[email protected]";

    public static final String CRYPTIE_PreplacedWORD = "preplacedword123";

    public static final Preplacedphrase CRYPTIE_PreplacedPHRASE = Preplacedphrase.fromPreplacedword(CRYPTIE_PreplacedWORD);

    public static final long CRYPTIE_KEY_ID = -821156605394703576L;

    public static final String CRYPTIE_FINGERPRINT_STRING = "A395D3BA58CA3FA0DE8F2991F49AAA6B067BAB28";

    public static final OpenPgpV4Fingerprint CRYPTIE_FINGERPRINT = new OpenPgpV4Fingerprint(CRYPTIE_FINGERPRINT_STRING);

    /**
     * Public EC key of [email protected].
     */
    public static final String CRYPTIE_PUB = "" + "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "Version: BCPG v1.64\n" + "\n" + "mFIEXht1HBMIKoZIzj0DAQcCAwQgSQNsoRMqlb9bm4XmXRxIyJoXhIADAQcqkrkt\n" + "uWvGWeu5m5HLi1LfwVHZWTGff94uq/uK3O3Vg0W4EQjF8qB6tBVjcnlwdGllQGVu\n" + "Y3J5cHRlZC5rZXmIdQQTEwoAHQUCXht1HAIbIwUWAgMBAAQLCQgHBRUKCQgLAh4B\n" + "AAoJEPSaqmsGe6soOWEBAMPW0d/DBVIs9tscIt+jXbg49kwYo57rbbEmp/X05RZS\n" + "AQDHDMOkesBjv9zQToWGGb0FmkWbrDCzA0i10mbyNAe4d7hWBF4bdR0SCCqGSM49\n" + "AwEHAgMENs+3TanqesZgSXn3gtz3QEqu8ZLID2+8U1Jh2KkkiasI1S+48k+CMiFb\n" + "0CclBy6+mX0k8chzj8wCNOgM74DB0AMBCAeIdQQYEwoAHQUCXht1HQIbDAUWAgMB\n" + "AAQLCQgHBRUKCQgLAh4BAAoJEPSaqmsGe6sovOUA/3Zb9qJM/9znjFM9hxMVL0y3\n" + "9wKEqKkSPRj0WVr6O5ybAP9S/Q/tzQ2in19xBg06XzNyd5a1nrwR9n4kjd4VpQWh\n" + "xQ==\n" + "=6SyK\n" + "-----END PGP PUBLIC KEY BLOCK-----";

    /**
     * Encrypted secret EC key of [email protected].
     *
     * Preplacedword: {@link #CRYPTIE_PreplacedWORD}
     */
    public static final String CRYPTIE_SEC = "" + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + "Version: BCPG v1.64\n" + "\n" + "lKUEXht1HBMIKoZIzj0DAQcCAwQgSQNsoRMqlb9bm4XmXRxIyJoXhIADAQcqkrkt\n" + "uWvGWeu5m5HLi1LfwVHZWTGff94uq/uK3O3Vg0W4EQjF8qB6/gkDApZ4y1XLA8XH\n" + "YM7ke2XPiiBQfapmHmZD0OUvlsTwSwDeg7wM9caWduXp7GU5j00T0gzr04xE83bw\n" + "pjjMxa1YRaOAJcjm1W/GGXRfXA/vSAO0FWNyeXB0aWVAZW5jcnlwdGVkLmtleYh1\n" + "BBMTCgAdBQJeG3UcAhsjBRYCAwEABAsJCAcFFQoJCAsCHgEACgkQ9JqqawZ7qyg5\n" + "YQEAw9bR38MFUiz22xwi36NduDj2TBijnuttsSan9fTlFlIBAMcMw6R6wGO/3NBO\n" + "hYYZvQWaRZusMLMDSLXSZvI0B7h3nKkEXht1HRIIKoZIzj0DAQcCAwQ2z7dNqep6\n" + "xmBJefeC3PdASq7xksgPb7xTUmHYqSSJqwjVL7jyT4IyIVvQJyUHLr6ZfSTxyHOP\n" + "zAI06AzvgMHQAwEIB/4JAwKWeMtVywPFx2Ci0C0EtcGVxy847rppLWNcaR3FnP/9\n" + "MGxLKDvLdGljC829gxxf5wq/5qUehPqFnQD11L00cFScvlVzs53nO34iUVsJl079\n" + "iHUEGBMKAB0FAl4bdR0CGwwFFgIDAQAECwkIBwUVCgkICwIeAQAKCRD0mqprBnur\n" + "KLzlAP92W/aiTP/c54xTPYcTFS9Mt/cChKipEj0Y9Fla+jucmwD/Uv0P7c0Nop9f\n" + "cQYNOl8zcneWtZ68EfZ+JI3eFaUFocU=\n" + "=1d67\n" + "-----END PGP PRIVATE KEY BLOCK-----";

    public static PGPSecretKeyRing getJulietSecretKeyRing() throws IOException, PGPException {
        if (julietSecretKeyRing == null) {
            julietSecretKeyRing = new PGPSecretKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(JULIET_SEC.getBytes())), calc);
        }
        return julietSecretKeyRing;
    }

    public static PGPSecretKeyRingCollection getJulietSecretKeyRingCollection() throws IOException, PGPException {
        if (julietSecretKeyRingCollection == null) {
            julietSecretKeyRingCollection = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(JULIET_SEC.getBytes())), calc);
        }
        return julietSecretKeyRingCollection;
    }

    public static PGPPublicKeyRing getJulietPublicKeyRing() throws IOException {
        if (julietPublicKeyRing == null) {
            julietPublicKeyRing = new PGPPublicKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(JULIET_PUB.getBytes())), calc);
        }
        return julietPublicKeyRing;
    }

    public static PGPPublicKeyRingCollection getJulietPublicKeyRingCollection() throws IOException, PGPException {
        if (julietPublicKeyRingCollection == null) {
            julietPublicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(JULIET_PUB.getBytes())), calc);
        }
        return julietPublicKeyRingCollection;
    }

    public static PGPSecretKeyRing getRomeoSecretKeyRing() throws IOException, PGPException {
        if (romeoSecretKeyRing == null) {
            romeoSecretKeyRing = new PGPSecretKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(ROMEO_SEC.getBytes())), calc);
        }
        return romeoSecretKeyRing;
    }

    public static PGPSecretKeyRingCollection getRomeoSecretKeyRingCollection() throws IOException, PGPException {
        if (romeoSecretKeyRingCollection == null) {
            romeoSecretKeyRingCollection = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(ROMEO_SEC.getBytes())), calc);
        }
        return romeoSecretKeyRingCollection;
    }

    public static PGPPublicKeyRing getRomeoPublicKeyRing() throws IOException {
        if (romeoPublicKeyRing == null) {
            romeoPublicKeyRing = new PGPPublicKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(ROMEO_PUB.getBytes())), calc);
        }
        return romeoPublicKeyRing;
    }

    public static PGPPublicKeyRingCollection getRomeoPublicKeyRingCollection() throws IOException, PGPException {
        if (romeoPublicKeyRingCollection == null) {
            romeoPublicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(ROMEO_PUB.getBytes())), calc);
        }
        return romeoPublicKeyRingCollection;
    }

    public static PGPSecretKeyRing getEmilSecretKeyRing() throws IOException, PGPException {
        if (emilSecretKeyRing == null) {
            emilSecretKeyRing = new PGPSecretKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(EMIL_SEC.getBytes())), calc);
        }
        return emilSecretKeyRing;
    }

    public static PGPSecretKeyRingCollection getEmilSecretKeyRingCollection() throws IOException, PGPException {
        if (emilSecretKeyRingCollection == null) {
            emilSecretKeyRingCollection = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(EMIL_SEC.getBytes())), calc);
        }
        return emilSecretKeyRingCollection;
    }

    public static PGPPublicKeyRing getEmilPublicKeyRing() throws IOException {
        if (emilPublicKeyRing == null) {
            emilPublicKeyRing = new PGPPublicKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(EMIL_PUB.getBytes())), calc);
        }
        return emilPublicKeyRing;
    }

    public static PGPPublicKeyRingCollection getEmilPublicKeyRingCollection() throws IOException, PGPException {
        if (emilPublicKeyRingCollection == null) {
            emilPublicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(EMIL_PUB.getBytes())), calc);
        }
        return emilPublicKeyRingCollection;
    }

    public static PGPSecretKeyRing getCryptieSecretKeyRing() throws IOException, PGPException {
        if (cryptieSecretKeyRing == null) {
            cryptieSecretKeyRing = new PGPSecretKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(CRYPTIE_SEC.getBytes())), calc);
        }
        return cryptieSecretKeyRing;
    }

    public static PGPSecretKeyRingCollection getCryptieSecretKeyRingCollection() throws IOException, PGPException {
        if (cryptieSecretKeyRingCollection == null) {
            cryptieSecretKeyRingCollection = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(CRYPTIE_SEC.getBytes())), calc);
        }
        return cryptieSecretKeyRingCollection;
    }

    public static PGPPublicKeyRing getCryptiePublicKeyRing() throws IOException {
        if (cryptiePublicKeyRing == null) {
            cryptiePublicKeyRing = new PGPPublicKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(CRYPTIE_PUB.getBytes())), calc);
        }
        return cryptiePublicKeyRing;
    }

    public static PGPPublicKeyRingCollection getCryptiePublicKeyRingCollection() throws IOException, PGPException {
        if (cryptiePublicKeyRingCollection == null) {
            cryptiePublicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(CRYPTIE_PUB.getBytes())), calc);
        }
        return cryptiePublicKeyRingCollection;
    }

    public static final String TEST_MESSAGE_01_PLAIN = "This message is encrypted\n";

    /**
     * Test Message signed with {@link #JULIET_SEC} and encrypted for {@link #JULIET_PUB}.
     */
    public static final String MSG_SIGN_CRYPT_JULIET_JULIET = "-----BEGIN PGP MESSAGE-----\n" + "\n" + "hQEMA7S1CctZNuA+AQf/SMX7NTOaAynogTVKE9BMWSj5fgK+7sFrCKiLYbungJEu\n" + "RA/fYqaJNfZN3GARqsHcGaGihQDXr0thnx71+37NhV2cHVeFkeMsHmJf/74lRrHk\n" + "QBXDv2ez0LxUwhkE15/d/NTlT/fm8Vzce6rsm7/ZvzQIaWYyDCnpHXyftJplKd+Y\n" + "PW0PaoFRq1wlZKcNUp/1a3xxpbSpvsYkiAxpdGIwvgUIb85KpFN0EWD3aH8C65it\n" + "Iphuv8CEaKqcO0hchQr7kYclEM0qcmm1ukw8+niTV8TFqAzNZh7DF/IWaMeamgfA\n" + "P6pAB1oy7YoWUPQgy7mczD76WzPgJjy8y0hxFd9/f9LA2gEZZ/ClAiX0gHglc4oa\n" + "j5iKIICvtTQzKYL29mW66BUistqMavz6eqHRggoADCBzfgOwuoAQxZMyj33bmrWm\n" + "831LMu+4sZyx6ihLvZ0YcDKMd7C7pQJ3Ucxt+DJUlTmo6KxzGdwGhq7cUcXwCuer\n" + "3MoPIV5YQwXBMbYN9fXV+yQagquz0z7r5igE7AQ1d9SyLJoQ3IHXnsa0xcUVZrIs\n" + "A59LdIXEeRk/Ctjqp34UdTsuUPzervPexY+kNQVSQ2VODhwM5IowzPZFGviPNJYa\n" + "nGt27c4rsQ3sSC/WkdUxdaVY2+m7JktfnklUyVyC5wE1Nw+bO3sni6FeoP/fVSVi\n" + "HmPy7vMj23cQcvcAnuUEd4Qua0lwVrN1MTUggfZOzcH4+9rgMn/uYRAwPH9hdLWQ\n" + "vziQMH5qtJMyWy08m9hIxleoI3+zIGSbra15R+hdWwEaD9+Pak//0Q0thFMeNww7\n" + "Y8gK8CSbUHbUjefUIx0s+JjrDGtXG8xfl63MLBbU7yLLB4Vcx77Sxxi3yt5DTi0n\n" + "GmPGRU4LsOYbpPFy\n" + "=caif\n" + "-----END PGP MESSAGE-----";
}

19 Source : SecretKeyRingProtectorTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void testCallbackBasedKeyRingProtector(ImplementationFactory implementationFactory) throws IOException, PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    SecretKeyRingProtector2 protector = new CallbackBasedKeyringProtector(new CallbackBasedKeyringProtector.Callback() {

        @Override
        public Preplacedphrase getPreplacedphraseFor(PGPSecretKey secretKey) {
            return TestKeys.CRYPTIE_PreplacedPHRASE;
        }
    });
    PGPSecretKeyRing secretKeys = TestKeys.getEmilSecretKeyRing();
    for (PGPSecretKey secretKey : secretKeys) {
        secretKey.extractPrivateKey(protector.getDecryptor(secretKey));
        replacedertNotNull(protector.getEncryptor(secretKey));
    }
}

19 Source : SecretKeyRingProtectorTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void testUnlockAllKeysWithSamePreplacedword(ImplementationFactory implementationFactory) throws IOException, PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    SecretKeyRingProtector protector = SecretKeyRingProtector.unlockAllKeysWith(TestKeys.CRYPTIE_PreplacedPHRASE, secretKeys);
    for (PGPSecretKey secretKey : secretKeys) {
        PBESecretKeyDecryptor decryptor = protector.getDecryptor(secretKey.getKeyID());
        replacedertNotNull(decryptor);
        secretKey.extractPrivateKey(decryptor);
    }
    PGPSecretKeyRing unrelatedKeys = PGPainless.generateKeyRing().simpleEcKeyRing("unrelated", "SecurePreplacedword");
    for (PGPSecretKey unrelatedKey : unrelatedKeys) {
        PBESecretKeyDecryptor decryptor = protector.getDecryptor(unrelatedKey.getKeyID());
        replacedertNull(decryptor);
        replacedertThrows(PGPException.clreplaced, () -> unrelatedKey.extractPrivateKey(protector.getDecryptor(unrelatedKey.getKeyID())));
    }
}

19 Source : SecretKeyRingProtectorTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void testUnlockSingleKeyWithPreplacedphrase(ImplementationFactory implementationFactory) throws IOException, PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    Iterator<PGPSecretKey> iterator = secretKeys.iterator();
    PGPSecretKey secretKey = iterator.next();
    PGPSecretKey subKey = iterator.next();
    SecretKeyRingProtector protector = SecretKeyRingProtector.unlockSingleKeyWith(TestKeys.CRYPTIE_PreplacedPHRASE, secretKey);
    replacedertNotNull(protector.getDecryptor(secretKey.getKeyID()));
    replacedertNotNull(protector.getEncryptor(secretKey.getKeyID()));
    replacedertNull(protector.getEncryptor(subKey.getKeyID()));
    replacedertNull(protector.getDecryptor(subKey.getKeyID()));
}

19 Source : RevokeSubKeyTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void detachedRevokeSubkeyTest(ImplementationFactory implementationFactory) throws IOException, PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    OpenPgpV4Fingerprint fingerprint = new OpenPgpV4Fingerprint(secretKeys);
    SecretKeyRingProtector protector = PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys, Preplacedphrase.fromPreplacedword("preplacedword123"));
    PGPSignature revocationCertificate = PGPainless.modifyKeyRing(secretKeys).createRevocationCertificate(fingerprint, protector, RevocationAttributes.createKeyRevocation().withReason(RevocationAttributes.Reason.KEY_RETIRED).withDescription("Key no longer used."));
    // CHECKSTYLE:OFF
    System.out.println("Revocation Certificate:");
    System.out.println(ArmorUtils.toAsciiArmoredString(revocationCertificate.getEncoded()));
    // CHECKSTYLE:ON
    PGPPublicKey publicKey = secretKeys.getPublicKey();
    replacedertFalse(publicKey.hasRevocation());
    publicKey = PGPPublicKey.addCertification(publicKey, revocationCertificate);
    replacedertTrue(publicKey.hasRevocation());
}

19 Source : RevokeSubKeyTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void revokeSukeyTest(ImplementationFactory implementationFactory) throws IOException, PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    Iterator<PGPSecretKey> keysIterator = secretKeys.iterator();
    PGPSecretKey primaryKey = keysIterator.next();
    PGPSecretKey subKey = keysIterator.next();
    replacedertFalse(subKey.getPublicKey().hasRevocation());
    SecretKeyRingProtector protector = PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys, Preplacedphrase.fromPreplacedword("preplacedword123"));
    secretKeys = PGPainless.modifyKeyRing(secretKeys).revokeSubKey(new OpenPgpV4Fingerprint(subKey), protector).done();
    keysIterator = secretKeys.iterator();
    primaryKey = keysIterator.next();
    subKey = keysIterator.next();
    replacedertTrue(subKey.getPublicKey().hasRevocation());
}

19 Source : RevokeSubKeyTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void testRevocationSignatureTypeCorrect(ImplementationFactory implementationFactory) throws IOException, PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    Iterator<PGPPublicKey> keysIterator = secretKeys.getPublicKeys();
    PGPPublicKey primaryKey = keysIterator.next();
    PGPPublicKey subKey = keysIterator.next();
    SecretKeyRingProtector protector = PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys, Preplacedphrase.fromPreplacedword("preplacedword123"));
    SecretKeyRingEditorInterface editor = PGPainless.modifyKeyRing(secretKeys);
    PGPSignature keyRevocation = editor.createRevocationCertificate(primaryKey.getKeyID(), protector, null);
    PGPSignature subkeyRevocation = editor.createRevocationCertificate(subKey.getKeyID(), protector, null);
    replacedertEquals(SignatureType.KEY_REVOCATION.getCode(), keyRevocation.getSignatureType());
    replacedertEquals(SignatureType.SUBKEY_REVOCATION.getCode(), subkeyRevocation.getSignatureType());
}

19 Source : RevokeKeyWithGenericCertificationSignatureTest.java
with Apache License 2.0
from pgpainless

private KeyPair revokeKey(String priv) throws IOException, PGPException {
    byte[] armoredBytes = priv.getBytes(StandardCharsets.UTF_8);
    PGPSecretKeyRing r = PGPainless.readKeyRing().secretKeyRing(armoredBytes);
    PGPSecretKey secretKey = r.getSecretKey();
    // this is not ideal, but still valid usage
    PGPSecretKeyRing secretKeyRing = PGPainless.modifyKeyRing(new PGPSecretKeyRing(Arrays.asList(secretKey))).revoke(new UnprotectedKeysProtector()).done();
    PGPPublicKey pkr = secretKeyRing.getPublicKeys().next();
    ByteArrayOutputStream pubOutBytes = new ByteArrayOutputStream();
    try (ArmoredOutputStream pubOut = ArmoredOutputStreamFactory.get(pubOutBytes)) {
        pkr.encode(pubOut);
    }
    pubOutBytes.close();
    PGPSecretKey skr = secretKeyRing.getSecretKeys().next();
    ByteArrayOutputStream secOutBytes = new ByteArrayOutputStream();
    try (ArmoredOutputStream privOut = ArmoredOutputStreamFactory.get(secOutBytes)) {
        skr.encode(privOut);
    }
    secOutBytes.close();
    return new KeyPair(pubOutBytes.toByteArray(), secOutBytes.toByteArray());
}

19 Source : ChangeSecretKeyRingPassphraseTest.java
with Apache License 2.0
from pgpainless

public clreplaced ChangeSecretKeyRingPreplacedphraseTest {

    private final PGPSecretKeyRing keyRing = PGPainless.generateKeyRing().simpleEcKeyRing("[email protected]", "weakPreplacedphrase");

    public ChangeSecretKeyRingPreplacedphraseTest() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
    }

    @ParameterizedTest
    @MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
    public void changePreplacedphraseOfWholeKeyRingTest(ImplementationFactory implementationFactory) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, IOException {
        ImplementationFactory.setFactoryImplementation(implementationFactory);
        PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changePreplacedphraseFromOldPreplacedphrase(Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNewPreplacedphrase(Preplacedphrase.fromPreplacedword("1337p455phr453")).done();
        PGPSecretKeyRing changedPreplacedphraseKeyRing = secretKeys;
        replacedertEquals(KeyRingProtectionSettings.secureDefaultSettings().getEncryptionAlgorithm().getAlgorithmId(), changedPreplacedphraseKeyRing.getSecretKey().getKeyEncryptionAlgorithm());
        replacedertThrows(PGPException.clreplaced, () -> signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.emptyPreplacedphrase()), "Unlocking secret key ring with empty preplacedphrase MUST fail.");
        replacedertThrows(PGPException.clreplaced, () -> signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.fromPreplacedword("weakPreplacedphrase")), "Unlocking secret key ring with old preplacedphrase MUST fail.");
        replacedertDoesNotThrow(() -> signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.fromPreplacedword("1337p455phr453")), "Unlocking the secret key ring with the new preplacedphrase MUST succeed.");
    }

    @ParameterizedTest
    @MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
    public void changePreplacedphraseOfWholeKeyRingToEmptyPreplacedphrase(ImplementationFactory implementationFactory) throws PGPException, IOException {
        ImplementationFactory.setFactoryImplementation(implementationFactory);
        PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changePreplacedphraseFromOldPreplacedphrase(Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNoPreplacedphrase().done();
        PGPSecretKeyRing changedPreplacedphraseKeyRing = secretKeys;
        replacedertEquals(SymmetricKeyAlgorithm.NULL.getAlgorithmId(), changedPreplacedphraseKeyRing.getSecretKey().getKeyEncryptionAlgorithm());
        signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.emptyPreplacedphrase());
    }

    @ParameterizedTest
    @MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
    public void changePreplacedphraseOfSingleSubkeyToNewPreplacedphrase(ImplementationFactory implementationFactory) throws PGPException {
        ImplementationFactory.setFactoryImplementation(implementationFactory);
        Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
        PGPSecretKey primaryKey = keys.next();
        PGPSecretKey subKey = keys.next();
        extractPrivateKey(primaryKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
        extractPrivateKey(subKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
        PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changeSubKeyPreplacedphraseFromOldPreplacedphrase(subKey.getPublicKey().getKeyID(), Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNewPreplacedphrase(Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase")).done();
        keys = secretKeys.getSecretKeys();
        primaryKey = keys.next();
        subKey = keys.next();
        extractPrivateKey(primaryKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
        extractPrivateKey(subKey, Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase"));
        final PGPSecretKey finalPrimaryKey = primaryKey;
        replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalPrimaryKey, Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase")), "Unlocking the primary key with the subkey preplacedphrase must fail.");
        final PGPSecretKey finalSubKey = subKey;
        replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalSubKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase")), "Unlocking the subkey with the primary key preplacedphrase must fail.");
    }

    @ParameterizedTest
    @MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
    public void changePreplacedphraseOfSingleSubkeyToEmptyPreplacedphrase(ImplementationFactory implementationFactory) throws PGPException {
        ImplementationFactory.setFactoryImplementation(implementationFactory);
        Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
        PGPSecretKey primaryKey = keys.next();
        PGPSecretKey subKey = keys.next();
        PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changeSubKeyPreplacedphraseFromOldPreplacedphrase(primaryKey.getKeyID(), Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNoPreplacedphrase().done();
        keys = secretKeys.getSecretKeys();
        primaryKey = keys.next();
        subKey = keys.next();
        extractPrivateKey(primaryKey, Preplacedphrase.emptyPreplacedphrase());
        extractPrivateKey(subKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
        final PGPSecretKey finalPrimaryKey = primaryKey;
        replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalPrimaryKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase")), "Unlocking the unprotected primary key with the old preplacedphrase must fail.");
        final PGPSecretKey finalSubKey = subKey;
        replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalSubKey, Preplacedphrase.emptyPreplacedphrase()), "Unlocking the still protected subkey with an empty preplacedphrase must fail.");
    }

    /**
     * This method throws an PGPException if the provided preplacedphrase cannot unlock the secret key.
     *
     * @param secretKey secret key
     * @param preplacedphrase preplacedphrase
     * @throws PGPException if preplacedphrase is wrong
     */
    private void extractPrivateKey(PGPSecretKey secretKey, Preplacedphrase preplacedphrase) throws PGPException {
        PGPDigestCalculatorProvider digestCalculatorProvider = new BcPGPDigestCalculatorProvider();
        if (preplacedphrase.isEmpty() && secretKey.getKeyEncryptionAlgorithm() != SymmetricKeyAlgorithm.NULL.getAlgorithmId()) {
            throw new PGPException("Cannot unlock encrypted private key with empty preplacedphrase.");
        } else if (!preplacedphrase.isEmpty() && secretKey.getKeyEncryptionAlgorithm() == SymmetricKeyAlgorithm.NULL.getAlgorithmId()) {
            throw new PGPException("Cannot unlock unprotected private key with non-empty preplacedphrase.");
        }
        PBESecretKeyDecryptor decryptor = preplacedphrase.isEmpty() ? null : new BcPBESecretKeyDecryptorBuilder(digestCalculatorProvider).build(preplacedphrase.getChars());
        secretKey.extractPrivateKey(decryptor);
    }

    private void signDummyMessageWithKeysAndPreplacedphrase(PGPSecretKeyRing keyRing, Preplacedphrase preplacedphrase) throws IOException, PGPException {
        String dummyMessage = "dummy";
        ByteArrayOutputStream dummy = new ByteArrayOutputStream();
        EncryptionStream stream = PGPainless.encryptAndOrSign().onOutputStream(dummy).doNotEncrypt().signWith(PreplacedwordBasedSecretKeyRingProtector.forKey(keyRing, preplacedphrase), keyRing).signBinaryDoreplacedent().noArmor();
        Streams.pipeAll(new ByteArrayInputStream(dummyMessage.getBytes()), stream);
        stream.close();
    }
}

19 Source : ChangeSecretKeyRingPassphraseTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void changePreplacedphraseOfWholeKeyRingTest(ImplementationFactory implementationFactory) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, IOException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changePreplacedphraseFromOldPreplacedphrase(Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNewPreplacedphrase(Preplacedphrase.fromPreplacedword("1337p455phr453")).done();
    PGPSecretKeyRing changedPreplacedphraseKeyRing = secretKeys;
    replacedertEquals(KeyRingProtectionSettings.secureDefaultSettings().getEncryptionAlgorithm().getAlgorithmId(), changedPreplacedphraseKeyRing.getSecretKey().getKeyEncryptionAlgorithm());
    replacedertThrows(PGPException.clreplaced, () -> signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.emptyPreplacedphrase()), "Unlocking secret key ring with empty preplacedphrase MUST fail.");
    replacedertThrows(PGPException.clreplaced, () -> signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.fromPreplacedword("weakPreplacedphrase")), "Unlocking secret key ring with old preplacedphrase MUST fail.");
    replacedertDoesNotThrow(() -> signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.fromPreplacedword("1337p455phr453")), "Unlocking the secret key ring with the new preplacedphrase MUST succeed.");
}

19 Source : ChangeSecretKeyRingPassphraseTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void changePreplacedphraseOfSingleSubkeyToEmptyPreplacedphrase(ImplementationFactory implementationFactory) throws PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
    PGPSecretKey primaryKey = keys.next();
    PGPSecretKey subKey = keys.next();
    PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changeSubKeyPreplacedphraseFromOldPreplacedphrase(primaryKey.getKeyID(), Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNoPreplacedphrase().done();
    keys = secretKeys.getSecretKeys();
    primaryKey = keys.next();
    subKey = keys.next();
    extractPrivateKey(primaryKey, Preplacedphrase.emptyPreplacedphrase());
    extractPrivateKey(subKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
    final PGPSecretKey finalPrimaryKey = primaryKey;
    replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalPrimaryKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase")), "Unlocking the unprotected primary key with the old preplacedphrase must fail.");
    final PGPSecretKey finalSubKey = subKey;
    replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalSubKey, Preplacedphrase.emptyPreplacedphrase()), "Unlocking the still protected subkey with an empty preplacedphrase must fail.");
}

19 Source : ChangeSecretKeyRingPassphraseTest.java
with Apache License 2.0
from pgpainless

private void signDummyMessageWithKeysAndPreplacedphrase(PGPSecretKeyRing keyRing, Preplacedphrase preplacedphrase) throws IOException, PGPException {
    String dummyMessage = "dummy";
    ByteArrayOutputStream dummy = new ByteArrayOutputStream();
    EncryptionStream stream = PGPainless.encryptAndOrSign().onOutputStream(dummy).doNotEncrypt().signWith(PreplacedwordBasedSecretKeyRingProtector.forKey(keyRing, preplacedphrase), keyRing).signBinaryDoreplacedent().noArmor();
    Streams.pipeAll(new ByteArrayInputStream(dummyMessage.getBytes()), stream);
    stream.close();
}

19 Source : ChangeSecretKeyRingPassphraseTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void changePreplacedphraseOfWholeKeyRingToEmptyPreplacedphrase(ImplementationFactory implementationFactory) throws PGPException, IOException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changePreplacedphraseFromOldPreplacedphrase(Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNoPreplacedphrase().done();
    PGPSecretKeyRing changedPreplacedphraseKeyRing = secretKeys;
    replacedertEquals(SymmetricKeyAlgorithm.NULL.getAlgorithmId(), changedPreplacedphraseKeyRing.getSecretKey().getKeyEncryptionAlgorithm());
    signDummyMessageWithKeysAndPreplacedphrase(changedPreplacedphraseKeyRing, Preplacedphrase.emptyPreplacedphrase());
}

19 Source : ChangeSecretKeyRingPassphraseTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void changePreplacedphraseOfSingleSubkeyToNewPreplacedphrase(ImplementationFactory implementationFactory) throws PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
    PGPSecretKey primaryKey = keys.next();
    PGPSecretKey subKey = keys.next();
    extractPrivateKey(primaryKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
    extractPrivateKey(subKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
    PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing).changeSubKeyPreplacedphraseFromOldPreplacedphrase(subKey.getPublicKey().getKeyID(), Preplacedphrase.fromPreplacedword("weakPreplacedphrase")).withSecureDefaultSettings().toNewPreplacedphrase(Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase")).done();
    keys = secretKeys.getSecretKeys();
    primaryKey = keys.next();
    subKey = keys.next();
    extractPrivateKey(primaryKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase"));
    extractPrivateKey(subKey, Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase"));
    final PGPSecretKey finalPrimaryKey = primaryKey;
    replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalPrimaryKey, Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase")), "Unlocking the primary key with the subkey preplacedphrase must fail.");
    final PGPSecretKey finalSubKey = subKey;
    replacedertThrows(PGPException.clreplaced, () -> extractPrivateKey(finalSubKey, Preplacedphrase.fromPreplacedword("weakPreplacedphrase")), "Unlocking the subkey with the primary key preplacedphrase must fail.");
}

19 Source : AddUserIdTest.java
with Apache License 2.0
from pgpainless

@Test
public void deleteExistingAndAddNewUserIdToExistingKeyRing() throws PGPException, IOException {
    final String ARMORED_PRIVATE_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\r\n\r\n" + "xVgEX6UIExYJKwYBBAHaRw8BAQdAMfHf64wPQ2LC9In5AKYU/KT1qWvI7e7a\r\n" + "Xr+LWeQGUKIAAQCcB3zZlHfepQT26LIwbTDn4lvQ9LuD1fk2hK6i9FXFxxO7\r\n" + "zRI8dXNlckBleGFtcGxlLmNvbT7CjwQQFgoAIAUCX6UIEwYLCQcIAwIEFQgK\r\n" + "AgQWAgEAAhkBAhsDAh4BACEJEEoCtcZ3snFuFiEENY1GQZqrKQqgUAXASgK1\r\n" + "xneycW6P6AEA5iXFK+fWpj0vn3xpKEuFRqvytPKFzhwd4wEvL+IGSPEBALE/\r\n" + "pZdMzsDoKPENiLFpboDVNVJScwFXIleKmtNaRycFx10EX6UIExIKKwYBBAGX\r\n" + "VQEFAQEHQBDdeawWVNqYkP8c/ihLEUlVpn8cQw7rmRc/sIhdAXhfAwEIBwAA\r\n" + "/0Jy7IelcHDjxE3OzagEzSxNrCVw8uPHNRl8s6iP+CQYEfHCeAQYFggACQUC\r\n" + "X6UIEwIbDAAhCRBKArXGd7JxbhYhBDWNRkGaqykKoFAFwEoCtcZ3snFuWp8B\r\n" + "AIzRBYJSfZzlvlyyPhrbXJoYSICGNy/5x7noXjp/ByeOAQDnTbQi4XwXJrU4\r\n" + "A8Nl9eyz16ZWUzEPwfWgahIG1eQDDA==\r\n" + "=bk4o\r\n" + "-----END PGP PRIVATE KEY BLOCK-----\r\n";
    PGPSecretKeyRing secretKeys = PGPainless.readKeyRing().secretKeyRing(ARMORED_PRIVATE_KEY);
    Iterator<String> userIds = secretKeys.getSecretKey().getPublicKey().getUserIDs();
    replacedertEquals("<[email protected]>", userIds.next());
    replacedertFalse(userIds.hasNext());
    SecretKeyRingProtector protector = new UnprotectedKeysProtector();
    secretKeys = PGPainless.modifyKeyRing(secretKeys).deleteUserId("<[email protected]>", protector).addUserId("[email protected]", protector).done();
    userIds = secretKeys.getSecretKey().getPublicKey().getUserIDs();
    replacedertEquals("[email protected]", userIds.next());
    replacedertFalse(userIds.hasNext());
}

19 Source : AddUserIdTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void addUserIdToExistingKeyRing(ImplementationFactory implementationFactory) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().simpleEcKeyRing("[email protected]", "rabb1th0le");
    Iterator<String> userIds = secretKeys.getSecretKey().getPublicKey().getUserIDs();
    replacedertEquals("[email protected]", userIds.next());
    replacedertFalse(userIds.hasNext());
    SecretKeyRingProtector protector = PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys, Preplacedphrase.fromPreplacedword("rabb1th0le"));
    secretKeys = PGPainless.modifyKeyRing(secretKeys).addUserId("[email protected]", protector).done();
    userIds = secretKeys.getPublicKey().getUserIDs();
    replacedertEquals("[email protected]", userIds.next());
    replacedertEquals("[email protected]", userIds.next());
    replacedertFalse(userIds.hasNext());
    secretKeys = PGPainless.modifyKeyRing(secretKeys).deleteUserId("[email protected]", protector).done();
    userIds = secretKeys.getPublicKey().getUserIDs();
    replacedertEquals("[email protected]", userIds.next());
    replacedertFalse(userIds.hasNext());
}

19 Source : AddUserIdTest.java
with Apache License 2.0
from pgpainless

@Test
public void deleteUserId_noSuchElementExceptionForMissingKey() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    replacedertThrows(NoSuchElementException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).deleteUserId(0L, TestKeys.CRYPTIE_UID, new UnprotectedKeysProtector()));
}

19 Source : AddUserIdTest.java
with Apache License 2.0
from pgpainless

@Test
public void deleteUserId_noSuchElementExceptionForMissingUserId() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    replacedertThrows(NoSuchElementException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).deleteUserId("[email protected]", new UnprotectedKeysProtector()));
}

19 Source : AddUserIdTest.java
with Apache License 2.0
from pgpainless

@Test
public void addUserId_NoSuchElementExceptionForMissingKey() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    replacedertThrows(NoSuchElementException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).addUserId(0L, TestKeys.CRYPTIE_UID, new UnprotectedKeysProtector()));
}

19 Source : AddSubKeyTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void testAddSubKey(ImplementationFactory implementationFactory) throws IOException, PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    List<Long> keyIdsBefore = new ArrayList<>();
    for (Iterator<PGPPublicKey> it = secretKeys.getPublicKeys(); it.hasNext(); ) {
        keyIdsBefore.add(it.next().getKeyID());
    }
    secretKeys = PGPainless.modifyKeyRing(secretKeys).addSubKey(KeySpec.getBuilder(ECDSA.fromCurve(EllipticCurve._P256)).withKeyFlags(KeyFlag.SIGN_DATA).withDefaultAlgorithms(), Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase"), PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys, Preplacedphrase.fromPreplacedword("preplacedword123"))).done();
    List<Long> keyIdsAfter = new ArrayList<>();
    for (Iterator<PGPPublicKey> it = secretKeys.getPublicKeys(); it.hasNext(); ) {
        keyIdsAfter.add(it.next().getKeyID());
    }
    replacedertNotEquals(keyIdsAfter, keyIdsBefore);
    keyIdsAfter.removeAll(keyIdsBefore);
    long subKeyId = keyIdsAfter.get(0);
    PGPSecretKey subKey = secretKeys.getSecretKey(subKeyId);
    PGPPrivateKey privateKey = subKey.extractPrivateKey(PreplacedwordBasedSecretKeyRingProtector.forKey(subKey, Preplacedphrase.fromPreplacedword("subKeyPreplacedphrase")).getDecryptor(subKeyId));
}

19 Source : UserIdRevocationTest.java
with Apache License 2.0
from pgpainless

@Test
public void invalidRevocationReasonThrowsIllegalArgumentException() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    SecretKeyRingProtector protector = PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys.getSecretKey(), TestKeys.CRYPTIE_PreplacedPHRASE);
    replacedertThrows(IllegalArgumentException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).revokeUserId("[email protected]", secretKeys.getSecretKey().getKeyID(), protector, RevocationAttributes.createKeyRevocation().withReason(RevocationAttributes.Reason.KEY_RETIRED).withDescription("This is not a valid certification revocation reason.")));
}

19 Source : UserIdRevocationTest.java
with Apache License 2.0
from pgpainless

@Test
public void test() throws IOException, PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InterruptedException {
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().withSubKey(KeySpec.getBuilder(KeyType.XDH(XDHCurve._X25519)).withKeyFlags(KeyFlag.ENCRYPT_COMMS).withDefaultAlgorithms()).withPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519)).withKeyFlags(KeyFlag.SIGN_DATA, KeyFlag.CERTIFY_OTHER).withDefaultAlgorithms()).withPrimaryUserId("[email protected]").withAdditionalUserId("[email protected]").withoutPreplacedphrase().build();
    Thread.sleep(1000);
    // make a copy with revoked subkey
    PGPSecretKeyRing revoked = PGPainless.modifyKeyRing(secretKeys).revokeUserIdOnAllSubkeys("[email protected]", new UnprotectedKeysProtector()).done();
    KeyRingInfo info = PGPainless.inspectKeyRing(revoked);
    List<String> userIds = info.getUserIds();
    replacedertEquals(Arrays.asList("[email protected]", "[email protected]"), userIds);
    replacedertTrue(info.isUserIdValid("[email protected]"));
    replacedertFalse(info.isUserIdValid("[email protected]"));
    replacedertFalse(info.isUserIdValid("[email protected]"));
    info = PGPainless.inspectKeyRing(secretKeys);
    // key on original secret key ring is still valid
    replacedertTrue(info.isUserIdValid("[email protected]"));
    revoked = PGPainless.modifyKeyRing(secretKeys).revokeUserId("[email protected]", secretKeys.getSecretKey().getKeyID(), new UnprotectedKeysProtector()).done();
    info = PGPainless.inspectKeyRing(revoked);
    userIds = info.getUserIds();
    replacedertEquals(Arrays.asList("[email protected]", "[email protected]"), userIds);
    replacedertTrue(info.isUserIdValid("[email protected]"));
    replacedertFalse(info.isUserIdValid("[email protected]"));
    replacedertFalse(info.isUserIdValid("[email protected]"));
}

19 Source : UserIdRevocationTest.java
with Apache License 2.0
from pgpainless

@Test
public void unknownUserIdThrowsNoSuchElementException() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    SecretKeyRingProtector protector = PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys.getSecretKey(), TestKeys.CRYPTIE_PreplacedPHRASE);
    replacedertThrows(NoSuchElementException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).revokeUserId("[email protected]", TestKeys.CRYPTIE_FINGERPRINT, protector));
    replacedertThrows(NoSuchElementException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).revokeUserId("[email protected]", TestKeys.CRYPTIE_KEY_ID, protector));
}

19 Source : UserIdRevocationTest.java
with Apache License 2.0
from pgpainless

@Test
public void unknownKeyThrowsIllegalArgumentException() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    SecretKeyRingProtector protector = PreplacedwordBasedSecretKeyRingProtector.forKey(secretKeys.getSecretKey(), TestKeys.CRYPTIE_PreplacedPHRASE);
    replacedertThrows(IllegalArgumentException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).revokeUserId("[email protected]", 1L, protector));
    replacedertThrows(IllegalArgumentException.clreplaced, () -> PGPainless.modifyKeyRing(secretKeys).revokeUserId("[email protected]", TestKeys.EMIL_FINGERPRINT, protector));
}

19 Source : UserIdRevocationTest.java
with Apache License 2.0
from pgpainless

@Test
public void testRevocationWithRevocationReason() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, InterruptedException {
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().withSubKey(KeySpec.getBuilder(KeyType.XDH(XDHCurve._X25519)).withKeyFlags(KeyFlag.ENCRYPT_COMMS).withDefaultAlgorithms()).withPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519)).withKeyFlags(KeyFlag.SIGN_DATA, KeyFlag.CERTIFY_OTHER).withDefaultAlgorithms()).withPrimaryUserId("[email protected]").withAdditionalUserId("[email protected]").withoutPreplacedphrase().build();
    Thread.sleep(1000);
    secretKeys = PGPainless.modifyKeyRing(secretKeys).revokeUserIdOnAllSubkeys("[email protected]", new UnprotectedKeysProtector(), RevocationAttributes.createCertificateRevocation().withReason(RevocationAttributes.Reason.USER_ID_NO_LONGER_VALID).withDescription("I lost my mail preplacedword")).done();
    PGPSignature signature = SignatureUtils.getLatestSelfSignatureForUserId(secretKeys.getPublicKey(), "[email protected]");
    RevocationReason reason = (RevocationReason) signature.getHashedSubPackets().getSubpacket(SignatureSubpacketTags.REVOCATION_REASON);
    replacedertNotNull(reason);
    replacedertEquals("I lost my mail preplacedword", reason.getRevocationDescription());
}

19 Source : KeyRingInfoTest.java
with Apache License 2.0
from pgpainless

@Test
public void testGetSecretKey() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    PGPPublicKeyRing publicKeys = KeyRingUtils.publicKeyRingFrom(secretKeys);
    KeyRingInfo info = PGPainless.inspectKeyRing(secretKeys);
    replacedertEquals(KeyRingUtils.requirePrimarySecretKeyFrom(secretKeys), info.getSecretKey());
    info = PGPainless.inspectKeyRing(publicKeys);
    replacedertNull(info.getSecretKey());
}

19 Source : KeyRingInfoTest.java
with Apache License 2.0
from pgpainless

@Test
public void testIsFullyDecrypted() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getEmilSecretKeyRing();
    KeyRingInfo info = PGPainless.inspectKeyRing(secretKeys);
    replacedertTrue(info.isFullyDecrypted());
    secretKeys = PGPainless.modifyKeyRing(secretKeys).changePreplacedphraseFromOldPreplacedphrase(null).withSecureDefaultSettings().toNewPreplacedphrase(Preplacedphrase.fromPreplacedword("sw0rdf1sh")).done();
    info = PGPainless.inspectKeyRing(secretKeys);
    replacedertFalse(info.isFullyDecrypted());
}

19 Source : KeyRingInfoTest.java
with Apache License 2.0
from pgpainless

@Test
public void testGetPublicKey() throws IOException, PGPException {
    PGPSecretKeyRing secretKeys = TestKeys.getCryptieSecretKeyRing();
    KeyRingInfo info = PGPainless.inspectKeyRing(secretKeys);
    replacedertEquals(KeyRingUtils.requirePrimaryPublicKeyFrom(secretKeys), info.getPublicKey());
    replacedertEquals(KeyRingUtils.requirePrimarySecretKeyFrom(secretKeys), KeyRingUtils.requireSecretKeyFrom(secretKeys, secretKeys.getPublicKey().getKeyID()));
}

19 Source : GenerateKeyWithAdditionalUserIdTest.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void test(ImplementationFactory implementationFactory) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, IOException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    Date now = new Date();
    Date expiration = new Date(now.getTime() + 1000 * 60);
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().withPrimaryKey(KeySpec.getBuilder(KeyType.RSA(RsaLength._3072)).withKeyFlags(KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA, KeyFlag.ENCRYPT_COMMS).withDefaultAlgorithms()).withPrimaryUserId("[email protected]").withAdditionalUserId("[email protected]").withAdditionalUserId("[email protected]").withAdditionalUserId("\[email protected]     ").setExpirationDate(expiration).withoutPreplacedphrase().build();
    PGPPublicKeyRing publicKeys = KeyRingUtils.publicKeyRingFrom(secretKeys);
    JUtils.replacedertEquals(expiration.getTime(), PGPainless.inspectKeyRing(publicKeys).getExpirationDate().getTime(), 2000);
    Iterator<String> userIds = publicKeys.getPublicKey().getUserIDs();
    replacedertEquals("[email protected]", userIds.next());
    replacedertEquals("[email protected]", userIds.next());
    replacedertEquals("[email protected]", userIds.next());
    replacedertEquals("[email protected]", userIds.next());
    replacedertFalse(userIds.hasNext());
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ArmoredOutputStream armor = ArmoredOutputStreamFactory.get(byteOut);
    secretKeys.encode(armor);
    armor.close();
    // echo this | gpg --list-packets
    // CHECKSTYLE:OFF
    System.out.println(byteOut.toString("UTF-8"));
// CHECKSTYLE:ON
}

See More Examples