org.bouncycastle.openpgp.PGPSignature

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

51 Examples 7

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

public static boolean isUserIdValid(PGPPublicKey publicKey, String userId) throws PGPException {
    PGPSignature latestSelfSig = getLatestSelfSignatureForUserId(publicKey, userId);
    if (latestSelfSig == null) {
        return false;
    }
    return latestSelfSig.getSignatureType() != SignatureType.CERTIFICATION_REVOCATION.getCode();
}

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

public PGPSignature getLatestValidSelfOrBindingSignatureOnKey(long subKeyId) throws PGPException {
    PGPSignature self = getLatestValidSelfSignatureOnKey(subKeyId);
    PGPSignature binding = getLatestValidBindingSignatureOnKey(subKeyId);
    if (self == null) {
        return binding;
    }
    if (binding == null) {
        return self;
    }
    return self.getCreationTime().after(binding.getCreationTime()) ? self : binding;
}

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

public static void validate(PGPSignature signature) throws PGPException {
    validateHashedAreaHreplacedignatureCreationTime(signature);
    validateSignatureCreationTimeIsNotInUnhashedArea(signature);
    validateSignatureDoesNotContainCriticalUnknownSubpackets(signature);
    validateSignatureDoesNotContainCriticalUnknownNotations(signature);
}

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

public boolean verify(PGPSignature signature) throws PGPException {
    this.verified = getOnePreplacedSignature().verify(signature);
    if (verified) {
        this.signature = signature;
    }
    return verified;
}

18 Source : Verify.java
with Apache License 2.0
from pgpainless

private void printValidSignatures(Map<OpenPgpV4Fingerprint, PGPSignature> validSignatures, Map<File, PGPPublicKeyRing> publicKeys) {
    for (OpenPgpV4Fingerprint sigKeyFp : validSignatures.keySet()) {
        PGPSignature signature = validSignatures.get(sigKeyFp);
        for (File file : publicKeys.keySet()) {
            // Search signing key ring
            PGPPublicKeyRing publicKeyRing = publicKeys.get(file);
            if (publicKeyRing.getPublicKey(sigKeyFp.getKeyId()) == null) {
                continue;
            }
            String utcSigDate = df.format(signature.getCreationTime());
            OpenPgpV4Fingerprint primaryKeyFp = new OpenPgpV4Fingerprint(publicKeyRing);
            print_ln(utcSigDate + " " + sigKeyFp.toString() + " " + primaryKeyFp.toString() + " signed by " + file.getName());
        }
    }
}

18 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static PGPSignature getLatestValidSignature(PGPPublicKey publicKey, List<PGPSignature> signatures, PGPKeyRing keyRing) throws PGPException {
    List<PGPSignature> valid = new ArrayList<>();
    for (PGPSignature signature : signatures) {
        long issuerID = signature.getKeyID();
        PGPPublicKey issuer = KeyRingUtils.getPublicKeyFrom(keyRing, issuerID);
        if (issuer == null) {
            continue;
        }
        if (!isSignatureValid(signature, issuer, publicKey)) {
            continue;
        }
        if (isSignatureExpired(signature)) {
            continue;
        }
        valid.add(signature);
    }
    sortByCreationTimeAscending(valid);
    return valid.isEmpty() ? null : valid.get(valid.size() - 1);
}

18 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static PGPSignature getLatestSelfSignatureForUserId(PGPPublicKey publicKey, String userId) throws PGPException {
    List<PGPSignature> valid = new ArrayList<>();
    List<PGPSignature> signatures = getSignaturesForUserId(publicKey, userId);
    for (PGPSignature signature : signatures) {
        if (isSelfSignatureOnUserIdValid(signature, userId, publicKey)) {
            valid.add(signature);
        }
    }
    return valid.isEmpty() ? null : valid.get(valid.size() - 1);
}

18 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static List<PGPSignature> getBindingSignatures(PGPPublicKey subKey, long primaryKeyId) {
    List<PGPSignature> signatures = new ArrayList<>();
    List<PGPSignature> bindingSigs = getSignaturesOfTypes(subKey, SignatureType.SUBKEY_BINDING);
    for (PGPSignature signature : bindingSigs) {
        if (signature.getKeyID() != primaryKeyId) {
            continue;
        }
        signatures.add(signature);
    }
    return signatures;
}

18 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static boolean isSignatureValid(PGPSignature signature, PGPPublicKey issuer, PGPPublicKey target) throws PGPException {
    SignatureType signatureType = SignatureType.valueOf(signature.getSignatureType());
    switch(signatureType) {
        case BINARY_DOreplacedENT:
        case CANONICAL_TEXT_DOreplacedENT:
        case STANDALONE:
        case TIMESTAMP:
        case THIRD_PARTY_CONFIRMATION:
            throw new IllegalArgumentException("Signature is not a key signature.");
        case GENERIC_CERTIFICATION:
        case NO_CERTIFICATION:
        case CASUAL_CERTIFICATION:
        case POSITIVE_CERTIFICATION:
        case DIRECT_KEY:
            return isSelfSignatureValid(signature, issuer);
        case KEY_REVOCATION:
        case CERTIFICATION_REVOCATION:
            return isRevocationSignatureValid(signature, issuer);
        case SUBKEY_BINDING:
        case PRIMARYKEY_BINDING:
        case SUBKEY_REVOCATION:
            return isKeyOnKeySignatureValid(signature, issuer, target);
    }
    return false;
}

18 Source : KeyRingInfo.java
with Apache License 2.0
from pgpainless

public String getPrimaryUserId() throws PGPException {
    List<String> userIds = getValidUserIds();
    for (String userId : userIds) {
        PGPSignature signature = getLatestValidSignatureOnUserId(userId);
        if (signature.getHashedSubPackets().isPrimaryUserID()) {
            return userId;
        }
    }
    return null;
}

18 Source : SignatureVerifyingInputStream.java
with Apache License 2.0
from pgpainless

private void verifySignatureOrThrowSignatureException(PGPSignature signature, OpenPgpV4Fingerprint fingerprint, OnePreplacedSignature onePreplacedSignature) throws PGPException, SignatureException {
    if (onePreplacedSignature.verify(signature)) {
        LOGGER.log(LEVEL, "Verified signature of key " + Long.toHexString(signature.getKeyID()));
    } else {
        throw new SignatureException("Bad Signature of key " + signature.getKeyID());
    }
}

18 Source : SignatureVerifyingInputStream.java
with Apache License 2.0
from pgpainless

private OpenPgpV4Fingerprint findFingerprintForSignature(PGPSignature signature) {
    OpenPgpV4Fingerprint fingerprint = null;
    for (OpenPgpV4Fingerprint f : onePreplacedSignatures.keySet()) {
        if (f.getKeyId() == signature.getKeyID()) {
            fingerprint = f;
            break;
        }
    }
    return fingerprint;
}

18 Source : SignatureValidationUtil.java
with Apache License 2.0
from pgpainless

public static void validateSignatureDoesNotContainCriticalUnknownSubpackets(PGPSignature signature) throws PGPDataValidationException {
    try {
        throwIfContainsCriticalUnknownSubpacket(signature.getHashedSubPackets());
    } catch (PGPDataValidationException e) {
        throw new PGPDataValidationException("Signature has unknown critical subpacket in hashed area.\n" + e.getMessage());
    }
    try {
        throwIfContainsCriticalUnknownSubpacket(signature.getHashedSubPackets());
    } catch (PGPDataValidationException e) {
        throw new PGPDataValidationException("Signature has unknown critical subpacket in unhashed area.\n" + e.getMessage());
    }
}

18 Source : DetachedSignature.java
with Apache License 2.0
from pgpainless

public clreplaced DetachedSignature {

    private final PGPSignature signature;

    private final OpenPgpV4Fingerprint fingerprint;

    private boolean verified;

    public DetachedSignature(PGPSignature signature, OpenPgpV4Fingerprint fingerprint) {
        this.signature = signature;
        this.fingerprint = fingerprint;
    }

    public void setVerified(boolean verified) {
        this.verified = verified;
    }

    public boolean isVerified() {
        return verified;
    }

    public PGPSignature getSignature() {
        return signature;
    }

    public OpenPgpV4Fingerprint getFingerprint() {
        return fingerprint;
    }
}

17 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static boolean isKeyOnKeySignatureValid(PGPSignature signature, PGPPublicKey issuer, PGPPublicKey target) throws PGPException {
    signature.init(ImplementationFactory.getInstance().getPGPContentVerifierBuilderProvider(), issuer);
    return signature.verifyCertification(issuer, target);
}

17 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static boolean isSelfSignatureOnUserIdValid(PGPSignature signature, String userId, PGPPublicKey publicKey) throws PGPException {
    signature.init(ImplementationFactory.getInstance().getPGPContentVerifierBuilderProvider(), publicKey);
    return signature.verifyCertification(userId, publicKey);
}

17 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static boolean isSignatureExpired(PGPSignature signature) {
    long expiration = signature.getHashedSubPackets().getSignatureExpirationTime();
    if (expiration == 0) {
        return false;
    }
    Date now = new Date();
    Date creation = signature.getCreationTime();
    return now.after(new Date(creation.getTime() + 1000 * expiration));
}

17 Source : OpenPgpKeyAttributeUtil.java
with Apache License 2.0
from pgpainless

public static List<HashAlgorithm> getPreferredHashAlgorithms(PGPPublicKey publicKey) {
    List<HashAlgorithm> hashAlgorithms = new ArrayList<>();
    // TODO: I'd replacedume that we have to use publicKey.getKeySignatures() here, but that is empty...
    Iterator<?> keySignatures = publicKey.getSignatures();
    while (keySignatures.hasNext()) {
        PGPSignature signature = (PGPSignature) keySignatures.next();
        if (signature.getKeyID() != publicKey.getKeyID()) {
            // Signature from a foreign key. Skip.
            continue;
        }
        SignatureType signatureType = SignatureType.valueOf(signature.getSignatureType());
        if (signatureType == SignatureType.POSITIVE_CERTIFICATION || signatureType == SignatureType.GENERIC_CERTIFICATION) {
            int[] hashAlgos = signature.getHashedSubPackets().getPreferredHashAlgorithms();
            if (hashAlgos == null) {
                continue;
            }
            for (int h : hashAlgos) {
                hashAlgorithms.add(HashAlgorithm.fromId(h));
            }
            // Exit the loop after the first key signature with hash algorithms.
            // TODO: Find out, if it is possible that there are multiple key signatures which specify preferred
            // algorithms and how to deal with that.
            break;
        }
    }
    return hashAlgorithms;
}

17 Source : SignatureVerifyingInputStream.java
with Apache License 2.0
from pgpainless

private void validateOnePreplacedSignatures() throws IOException {
    PGPSignatureList signatureList = findPgpSignatureList();
    try {
        for (PGPSignature signature : signatureList) {
            OpenPgpV4Fingerprint fingerprint = findFingerprintForSignature(signature);
            OnePreplacedSignature onePreplacedSignature = findOnePreplacedSignature(fingerprint);
            if (onePreplacedSignature == null) {
                LOGGER.log(LEVEL, "Found Signature without respective OnePreplacedSignature packet -> skip");
                continue;
            }
            verifySignatureOrThrowSignatureException(signature, fingerprint, onePreplacedSignature);
        }
    } catch (PGPException | SignatureException e) {
        throw new IOException(e.getMessage(), e);
    }
}

17 Source : SignatureValidationUtil.java
with Apache License 2.0
from pgpainless

public static void validateSignatureDoesNotContainCriticalUnknownNotations(PGPSignature signature) throws PGPDataValidationException {
    PGPSignatureSubpacketVector hashedSubpackets = signature.getHashedSubPackets();
    try {
        throwIfSubpacketsContainCriticalUnknownNotation(hashedSubpackets);
    } catch (PGPDataValidationException e) {
        throw new PGPDataValidationException("Signature contains unknown critical notation in hashed area:\n" + e.getMessage());
    }
    PGPSignatureSubpacketVector unhashedSubpackets = signature.getUnhashedSubPackets();
    try {
        throwIfSubpacketsContainCriticalUnknownNotation(unhashedSubpackets);
    } catch (PGPDataValidationException e) {
        throw new PGPDataValidationException("Signature contains unknown critical notation in unhashed area:\n" + e.getMessage());
    }
}

17 Source : SignatureValidationUtil.java
with Apache License 2.0
from pgpainless

public static void validateHashedAreaHreplacedignatureCreationTime(PGPSignature signature) throws PGPDataValidationException {
    PGPSignatureSubpacketVector hashedSubpackets = signature.getHashedSubPackets();
    if (hashedSubpackets.getSignatureCreationTime() == null) {
        throw new PGPDataValidationException("Hashed area of the signature MUST carry signature creation time subpacket.");
    }
}

17 Source : SignatureValidationUtil.java
with Apache License 2.0
from pgpainless

public static void validateSignatureCreationTimeIsNotInUnhashedArea(PGPSignature signature) throws PGPDataValidationException {
    PGPSignatureSubpacketVector unhashedSubpackets = signature.getUnhashedSubPackets();
    Date unhashedCreationTime = unhashedSubpackets.getSignatureCreationTime();
    if (unhashedCreationTime == null) {
        return;
    }
    throw new PGPDataValidationException("Signature creation time MUST be in hashed area of the signature.");
}

17 Source : OnePassSignature.java
with Apache License 2.0
from pgpainless

public clreplaced OnePreplacedSignature {

    private final PGPOnePreplacedSignature onePreplacedSignature;

    private final OpenPgpV4Fingerprint fingerprint;

    private PGPSignature signature;

    private boolean verified;

    public OnePreplacedSignature(PGPOnePreplacedSignature onePreplacedSignature, OpenPgpV4Fingerprint fingerprint) {
        this.onePreplacedSignature = onePreplacedSignature;
        this.fingerprint = fingerprint;
    }

    public boolean isVerified() {
        return verified;
    }

    public PGPOnePreplacedSignature getOnePreplacedSignature() {
        return onePreplacedSignature;
    }

    public OpenPgpV4Fingerprint getFingerprint() {
        return fingerprint;
    }

    public boolean verify(PGPSignature signature) throws PGPException {
        this.verified = getOnePreplacedSignature().verify(signature);
        if (verified) {
            this.signature = signature;
        }
        return verified;
    }

    public PGPSignature getSignature() {
        return signature;
    }
}

17 Source : PgpSignatory.java
with MIT License
from ghnor

/**
 * Exhausts {@code toSign}, and writes the signature to {@code signatureDestination}.
 *
 * The caller is responsible for closing the streams, though the output WILL be flushed.
 */
@Override
public void sign(InputStream toSign, OutputStream signatureDestination) {
    PGPSignatureGenerator generator = createSignatureGenerator();
    try {
        feedGeneratorWith(toSign, generator);
        PGPSignature signature = generator.generate();
        writeSignatureTo(signatureDestination, signature);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (PGPException e) {
        throw new UncheckedException(e);
    }
}

16 Source : KeyRingInfo.java
with Apache License 2.0
from pgpainless

/**
 * Return the date on which the key ring was last modified.
 * This date corresponds to the date of the last signature that was made on this key ring by the primary key.
 *
 * @return last modification date.
 */
public Date getLastModified() {
    Iterator<PGPSignature> signatures = getPublicKey().getSignatures();
    long last = 0L;
    while (signatures.hasNext()) {
        PGPSignature signature = signatures.next();
        if (getKeyId() != signature.getKeyID()) {
            // Throw away signatures made from others
            continue;
        }
        last = Math.max(last, signature.getCreationTime().getTime());
    }
    return new Date(last);
}

16 Source : PgpSignatory.java
with MIT License
from ghnor

private void writeSignatureTo(OutputStream signatureDestination, PGPSignature pgpSignature) throws PGPException, IOException {
    // BCPGOutputStream seems to do some internal buffering, it's unclear whether it's stricly required here though
    BCPGOutputStream bufferedOutput = new BCPGOutputStream(signatureDestination);
    pgpSignature.encode(bufferedOutput);
    bufferedOutput.flush();
}

15 Source : Verify.java
with Apache License 2.0
from pgpainless

@Override
public void run() {
    Date notBeforeDate = parseNotBefore();
    Date notAfterDate = parseNotAfter();
    Map<File, PGPPublicKeyRing> publicKeys = readCertificatesFromFiles();
    if (publicKeys.isEmpty()) {
        err_ln("No certificates supplied.");
        System.exit(19);
    }
    OpenPgpMetadata metadata;
    try (FileInputStream sigIn = new FileInputStream(signature)) {
        DecryptionStream verifier = PGPainless.decryptAndOrVerify().onInputStream(System.in).doNotDecrypt().verifyDetachedSignature(sigIn).verifyWith(new HashSet<>(publicKeys.values())).ignoreMissingPublicKeys().build();
        OutputStream out = new NullOutputStream();
        Streams.pipeAll(verifier, out);
        verifier.close();
        metadata = verifier.getResult();
    } catch (FileNotFoundException e) {
        err_ln("Signature file not found:");
        err_ln(e.getMessage());
        System.exit(1);
        return;
    } catch (IOException | PGPException e) {
        err_ln("Signature validation failed.");
        err_ln(e.getMessage());
        System.exit(1);
        return;
    }
    Map<OpenPgpV4Fingerprint, PGPSignature> signaturesInTimeRange = new HashMap<>();
    for (OpenPgpV4Fingerprint fingerprint : metadata.getVerifiedSignatures().keySet()) {
        PGPSignature signature = metadata.getVerifiedSignatures().get(fingerprint);
        Date creationTime = signature.getCreationTime();
        if (!creationTime.before(notBeforeDate) && !creationTime.after(notAfterDate)) {
            signaturesInTimeRange.put(fingerprint, signature);
        }
    }
    if (signaturesInTimeRange.isEmpty()) {
        err_ln("No valid signatures found.");
        System.exit(3);
    }
    printValidSignatures(signaturesInTimeRange, publicKeys);
}

15 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static boolean isRevocationSignatureValid(PGPSignature signature, PGPPublicKey publicKey) throws PGPException {
    if (!PGPainless.getPolicy().getRevocationSignatureHashAlgorithmPolicy().isAcceptable(signature.getHashAlgorithm())) {
        return false;
    }
    for (Iterator<String> it = publicKey.getUserIDs(); it.hasNext(); ) {
        String userId = it.next();
        boolean valid = isSelfSignatureOnUserIdValid(signature, userId, publicKey);
        if (valid) {
            return true;
        }
    }
    return false;
}

15 Source : SignatureUtils.java
with Apache License 2.0
from pgpainless

public static boolean isSelfSignatureValid(PGPSignature signature, PGPPublicKey publicKey) throws PGPException {
    if (!PGPainless.getPolicy().getSignatureHashAlgorithmPolicy().isAcceptable(signature.getHashAlgorithm())) {
        return false;
    }
    for (Iterator<String> it = publicKey.getUserIDs(); it.hasNext(); ) {
        String userId = it.next();
        boolean valid = isSelfSignatureOnUserIdValid(signature, userId, publicKey);
        if (valid) {
            return true;
        }
    }
    return false;
}

15 Source : OpenPgpKeyAttributeUtil.java
with Apache License 2.0
from pgpainless

/**
 * Return the hash algorithm that was used in the latest self signature.
 *
 * @param publicKey public key
 * @return list of hash algorithm
 */
public static List<HashAlgorithm> guessPreferredHashAlgorithms(PGPPublicKey publicKey) {
    HashAlgorithm hashAlgorithm = null;
    Date lastCreationDate = null;
    Iterator<?> keySignatures = publicKey.getSignatures();
    while (keySignatures.hasNext()) {
        PGPSignature signature = (PGPSignature) keySignatures.next();
        if (signature.getKeyID() != publicKey.getKeyID()) {
            continue;
        }
        SignatureType signatureType = SignatureType.valueOf(signature.getSignatureType());
        if (signatureType != SignatureType.POSITIVE_CERTIFICATION && signatureType != SignatureType.GENERIC_CERTIFICATION) {
            continue;
        }
        Date creationDate = signature.getCreationTime();
        if (lastCreationDate == null || lastCreationDate.before(creationDate)) {
            lastCreationDate = creationDate;
            hashAlgorithm = HashAlgorithm.fromId(signature.getHashAlgorithm());
        }
    }
    if (hashAlgorithm == null) {
        return Collections.emptyList();
    }
    return Collections.singletonList(hashAlgorithm);
}

15 Source : SecretKeyRingEditor.java
with Apache License 2.0
from pgpainless

@Override
public PGPSignature createRevocationCertificate(long subKeyId, SecretKeyRingProtector secretKeyRingProtector, RevocationAttributes revocationAttributes) throws PGPException {
    PGPPublicKey revokeeSubKey = secretKeyRing.getPublicKey(subKeyId);
    if (revokeeSubKey == null) {
        throw new NoSuchElementException("No subkey with id " + Long.toHexString(subKeyId) + " found.");
    }
    PGPSignature revocationCertificate = generateRevocation(secretKeyRingProtector, revokeeSubKey, revocationAttributes);
    return revocationCertificate;
}

15 Source : KeyRingInfo.java
with Apache License 2.0
from pgpainless

/**
 * Return the date on which the primary key was revoked, or null if it has not yet been revoked.
 *
 * @return revocation date or null
 */
public Date getRevocationDate() {
    Iterator<PGPSignature> revocations = getPublicKey().getSignaturesOfType(SignatureType.KEY_REVOCATION.getCode());
    while (revocations.hasNext()) {
        PGPSignature revocation = revocations.next();
        if (getKeyId() != revocation.getKeyID()) {
            // Throw away signatures made from others
            continue;
        }
        return revocation.getCreationTime();
    }
    return null;
}

15 Source : GPG.java
with GNU Lesser General Public License v2.1
from ImpactDevelopment

/**
 * Verify signed data
 *
 * @param signedData
 * @param signatureData
 * @return the PGPPublicKey that created this signature, if it's valid.  null if not valid, or unknown public key.
 */
private static PGPPublicKey verify(byte[] signedData, byte[] signatureData) {
    try {
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(PGPUtil.getDecoderStream(new ByteArrayInputStream(signatureData)));
        PGPSignature sig = ((PGPSignatureList) pgpFact.nextObject()).get(0);
        PGPPublicKey key = KEYRING.getPublicKey(sig.getKeyID());
        if (key == null) {
            System.out.println("WARNING: signature from unknown public key " + sig.getKeyID());
            return null;
        }
        sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), key);
        sig.update(signedData);
        if (!sig.verify()) {
            return null;
        }
        return key;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

14 Source : Sign.java
with Apache License 2.0
from pgpainless

@Override
public void run() {
    PGPSecretKeyRing[] secretKeys = new PGPSecretKeyRing[secretKeyFile.length];
    for (int i = 0, secretKeyFileLength = secretKeyFile.length; i < secretKeyFileLength; i++) {
        File file = secretKeyFile[i];
        try {
            PGPSecretKeyRing secretKey = PGPainless.readKeyRing().secretKeyRing(new FileInputStream(file));
            secretKeys[i] = secretKey;
        } catch (IOException | PGPException e) {
            err_ln("Error reading secret key ring " + file.getName());
            err_ln(e.getMessage());
            System.exit(1);
            return;
        }
    }
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        EncryptionBuilderInterface.DoreplacedentType doreplacedentType = PGPainless.encryptAndOrSign().onOutputStream(out).doNotEncrypt().createDetachedSignature().signWith(new UnprotectedKeysProtector(), secretKeys);
        EncryptionBuilderInterface.Armor builder = type == Type.text ? doreplacedentType.signCanonicalText() : doreplacedentType.signBinaryDoreplacedent();
        EncryptionStream encryptionStream = armor ? builder.asciiArmor() : builder.noArmor();
        Streams.pipeAll(System.in, encryptionStream);
        encryptionStream.close();
        PGPSignature signature = encryptionStream.getResult().getSignatures().iterator().next();
        print_ln(Print.toString(signature.getEncoded(), armor));
    } catch (PGPException | IOException e) {
        err_ln("Error signing data.");
        err_ln(e.getMessage());
        System.exit(1);
    }
}

14 Source : Encrypt.java
with Apache License 2.0
from pgpainless

@Override
public void run() {
    if (certs.length == 0 && withPreplacedword.length == 0) {
        err_ln("Please either provide --with-preplacedword or at least one CERT");
        System.exit(19);
    }
    PGPPublicKeyRing[] publicKeys = new PGPPublicKeyRing[certs.length];
    for (int i = 0; i < certs.length; i++) {
        try (InputStream fileIn = new FileInputStream(certs[i])) {
            PGPPublicKeyRing publicKey = PGPainless.readKeyRing().publicKeyRing(fileIn);
            publicKeys[i] = publicKey;
        } catch (IOException e) {
            err_ln("Cannot read certificate " + certs[i].getName());
            err_ln(e.getMessage());
            System.exit(1);
        }
    }
    PGPSecretKeyRing[] secretKeys = new PGPSecretKeyRing[signWith.length];
    for (int i = 0; i < signWith.length; i++) {
        try (FileInputStream fileIn = new FileInputStream(signWith[i])) {
            PGPSecretKeyRing secretKey = PGPainless.readKeyRing().secretKeyRing(fileIn);
            secretKeys[i] = secretKey;
        } catch (IOException | PGPException e) {
            err_ln("Cannot read secret key from file " + signWith[i].getName());
            err_ln(e.getMessage());
            System.exit(1);
        }
    }
    Preplacedphrase[] preplacedphraseArray = new Preplacedphrase[withPreplacedword.length];
    for (int i = 0; i < withPreplacedword.length; i++) {
        String preplacedword = withPreplacedword[i];
        preplacedphraseArray[i] = Preplacedphrase.fromPreplacedword(preplacedword);
    }
    Map<Long, Preplacedphrase> preplacedphraseMap = new HashMap<>();
    Scanner scanner = null;
    for (PGPSecretKeyRing ring : secretKeys) {
        for (PGPSecretKey key : ring) {
            // Skip non-signing keys
            PGPSignature signature = (PGPSignature) key.getPublicKey().getSignatures().next();
            int flags = signature.getHashedSubPackets().getKeyFlags();
            if (!key.isSigningKey() || !KeyFlag.hasKeyFlag(flags, KeyFlag.SIGN_DATA)) {
                // Key cannot sign
                continue;
            }
            if (key.getKeyEncryptionAlgorithm() == SymmetricKeyAlgorithm.NULL.getAlgorithmId()) {
                preplacedphraseMap.put(key.getKeyID(), Preplacedphrase.emptyPreplacedphrase());
            } else {
                print_ln("Please provide the preplacedphrase for key " + new OpenPgpV4Fingerprint(key));
                if (scanner == null) {
                    scanner = new Scanner(System.in);
                }
                String preplacedword = scanner.nextLine();
                Preplacedphrase preplacedphrase = Preplacedphrase.fromPreplacedword(preplacedword.trim());
                preplacedphraseMap.put(key.getKeyID(), preplacedphrase);
            }
        }
    }
    EncryptionBuilderInterface.DetachedSign builder = PGPainless.encryptAndOrSign().onOutputStream(System.out).toRecipients(publicKeys).and().forPreplacedphrases(preplacedphraseArray).usingSecureAlgorithms();
    EncryptionBuilderInterface.Armor builder_armor;
    if (signWith.length != 0) {
        EncryptionBuilderInterface.DoreplacedentType doreplacedentType = builder.signWith(new PreplacedphraseMapKeyRingProtector(preplacedphraseMap, KeyRingProtectionSettings.secureDefaultSettings(), null), secretKeys);
        if (type == Type.text || type == Type.mime) {
            builder_armor = doreplacedentType.signCanonicalText();
        } else {
            builder_armor = doreplacedentType.signBinaryDoreplacedent();
        }
    } else {
        builder_armor = builder.doNotSign();
    }
    try {
        EncryptionStream encryptionStream = !armor ? builder_armor.noArmor() : builder_armor.asciiArmor();
        Streams.pipeAll(System.in, encryptionStream);
        encryptionStream.close();
    } catch (IOException | PGPException e) {
        err_ln("An error happened.");
        err_ln(e.getMessage());
        System.exit(1);
    }
}

14 Source : Decrypt.java
with Apache License 2.0
from pgpainless

@Override
public void run() {
    if (verifyOut == null ^ certs == null) {
        err_ln("To enable signature verification, both --verify-out and at least one --verify-with argument must be supplied.");
        System.exit(23);
    }
    if (sessionKeyOut != null || withSessionKey != null) {
        err_ln("session key in and out are not yet supported.");
        System.exit(1);
    }
    PGPSecretKeyRingCollection secretKeys;
    try {
        List<PGPSecretKeyRing> secretKeyRings = loadKeysFromFiles(keys);
        secretKeys = new PGPSecretKeyRingCollection(secretKeyRings);
    } catch (PGPException | IOException e) {
        err_ln(e.getMessage());
        System.exit(1);
        return;
    }
    List<PGPPublicKeyRing> verifyWith = new ArrayList<>();
    if (certs != null) {
        for (File f : certs) {
            try {
                verifyWith.add(PGPainless.readKeyRing().publicKeyRing(new FileInputStream(f)));
            } catch (IOException e) {
            }
        }
    }
    DecryptionBuilderInterface.Verify builder = PGPainless.decryptAndOrVerify().onInputStream(System.in).decryptWith(secretKeys);
    DecryptionStream decryptionStream = null;
    try {
        if (certs != null) {
            decryptionStream = builder.verifyWith(new HashSet<>(verifyWith)).ignoreMissingPublicKeys().build();
        } else {
            decryptionStream = builder.doNotVerify().build();
        }
    } catch (IOException | PGPException e) {
        System.exit(1);
        return;
    }
    try {
        Streams.pipeAll(decryptionStream, System.out);
        decryptionStream.close();
    } catch (IOException e) {
        err_ln("Unable to decrypt: " + e.getMessage());
        System.exit(29);
    }
    if (verifyOut == null) {
        return;
    }
    OpenPgpMetadata metadata = decryptionStream.getResult();
    StringBuilder sb = new StringBuilder();
    for (OpenPgpV4Fingerprint fingerprint : metadata.getVerifiedSignatures().keySet()) {
        PGPPublicKeyRing verifier = null;
        for (PGPPublicKeyRing ring : verifyWith) {
            if (ring.getPublicKey(fingerprint.getKeyId()) != null) {
                verifier = ring;
                break;
            }
        }
        PGPSignature signature = metadata.getVerifiedSignatures().get(fingerprint);
        sb.append(df.format(signature.getCreationTime())).append(' ').append(fingerprint).append(' ').append(new OpenPgpV4Fingerprint(verifier)).append('\n');
    }
    try {
        verifyOut.createNewFile();
        PrintStream verifyPrinter = new PrintStream(new FileOutputStream(verifyOut));
        // CHECKSTYLE:OFF
        verifyPrinter.println(sb.toString());
        // CHECKSTYLE:ON
        verifyPrinter.close();
    } catch (IOException e) {
    }
}

14 Source : EncryptionStream.java
with Apache License 2.0
from pgpainless

private void writeSignatures() throws IOException {
    for (OpenPgpV4Fingerprint fingerprint : signatureGenerators.keySet()) {
        PGPSignatureGenerator signatureGenerator = signatureGenerators.get(fingerprint);
        try {
            PGPSignature signature = signatureGenerator.generate();
            if (!detachedSignature) {
                signature.encode(outermostStream);
            }
            resultBuilder.addDetachedSignature(new DetachedSignature(signature, fingerprint));
        } catch (PGPException e) {
            throw new IOException(e);
        }
    }
}

13 Source : OldSignatureSubpacketsArePreservedOnNewSig.java
with Apache License 2.0
from pgpainless

@ParameterizedTest
@MethodSource("org.pgpainless.util.TestUtil#provideImplementationFactories")
public void verifyOldSignatureSubpacketsArePreservedOnNewExpirationDateSig(ImplementationFactory implementationFactory) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, InterruptedException, IOException {
    ImplementationFactory.setFactoryImplementation(implementationFactory);
    PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().simpleEcKeyRing("Alice <[email protected]>");
    OpenPgpV4Fingerprint subkeyFingerprint = new OpenPgpV4Fingerprint(PGPainless.inspectKeyRing(secretKeys).getPublicKeys().get(1));
    PGPSignature oldSignature = PGPainless.inspectKeyRing(secretKeys).getLatestValidSelfOrBindingSignatureOnKey(subkeyFingerprint);
    PGPSignatureSubpacketVector oldPackets = oldSignature.getHashedSubPackets();
    replacedertEquals(0, oldPackets.getKeyExpirationTime());
    Thread.sleep(1000);
    secretKeys = PGPainless.modifyKeyRing(secretKeys).setExpirationDate(subkeyFingerprint, new Date(), new UnprotectedKeysProtector()).done();
    PGPSignature newSignature = PGPainless.inspectKeyRing(secretKeys).getLatestValidSelfOrBindingSignatureOnKey(subkeyFingerprint);
    PGPSignatureSubpacketVector newPackets = newSignature.getHashedSubPackets();
    replacedertNotEquals(0, newPackets.getKeyExpirationTime());
    replacedertArrayEquals(oldPackets.getPreferredHashAlgorithms(), newPackets.getPreferredHashAlgorithms());
}

13 Source : SecretKeyRingEditor.java
with Apache License 2.0
from pgpainless

private PGPSecretKeyRing revokeSubKey(SecretKeyRingProtector protector, PGPPublicKey revokeeSubKey, RevocationAttributes revocationAttributes) throws PGPException {
    PGPSignature subKeyRevocation = generateRevocation(protector, revokeeSubKey, revocationAttributes);
    revokeeSubKey = PGPPublicKey.addCertification(revokeeSubKey, subKeyRevocation);
    // Inject revoked public key into key ring
    PGPPublicKeyRing publicKeyRing = KeyRingUtils.publicKeyRingFrom(secretKeyRing);
    publicKeyRing = PGPPublicKeyRing.insertPublicKey(publicKeyRing, revokeeSubKey);
    return PGPSecretKeyRing.replacePublicKeys(secretKeyRing, publicKeyRing);
}

13 Source : SecretKeyRingEditor.java
with Apache License 2.0
from pgpainless

@Override
public PGPSignature createRevocationCertificate(OpenPgpV4Fingerprint fingerprint, SecretKeyRingProtector secretKeyRingProtector, RevocationAttributes revocationAttributes) throws PGPException {
    PGPPublicKey revokeeSubKey = secretKeyRing.getPublicKey(fingerprint.getKeyId());
    if (revokeeSubKey == null) {
        throw new NoSuchElementException("No subkey with fingerprint " + fingerprint + " found.");
    }
    PGPSignature revocationCertificate = generateRevocation(secretKeyRingProtector, revokeeSubKey, revocationAttributes);
    return revocationCertificate;
}

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

@SuppressWarnings("rawtypes")
private static String resolveAlgorithm(PGPPublicKey key) throws PGPException {
    for (Iterator iter = key.getSignatures(); iter.hasNext(); ) {
        PGPSignature sig = (PGPSignature) iter.next();
        return PGPUtil.getSignatureName(sig.getKeyAlgorithm(), sig.getHashAlgorithm());
    }
    return null;
}

12 Source : SecretKeyRingEditor.java
with Apache License 2.0
from pgpainless

private static PGPPublicKey addUserIdToPubKey(String userId, PGPPrivateKey privateKey, PGPPublicKey publicKey) throws PGPException {
    if (privateKey.getKeyID() != publicKey.getKeyID()) {
        throw new IllegalArgumentException("Key-ID mismatch!");
    }
    // Create signature with new user-id and add it to the public key
    PGPSignatureGenerator signatureGenerator = SignatureUtils.getSignatureGeneratorFor(publicKey);
    signatureGenerator.init(SignatureType.POSITIVE_CERTIFICATION.getCode(), privateKey);
    PGPSignature userIdSignature = signatureGenerator.generateCertification(userId, publicKey);
    publicKey = PGPPublicKey.addCertification(publicKey, userId, userIdSignature);
    return publicKey;
}

12 Source : DecryptionStreamFactory.java
with Apache License 2.0
from pgpainless

public static DecryptionStream create(@Nonnull InputStream inputStream, @Nullable PGPSecretKeyRingCollection decryptionKeys, @Nullable SecretKeyRingProtector decryptor, @Nullable Preplacedphrase decryptionPreplacedphrase, @Nullable List<PGPSignature> detachedSignatures, @Nullable Set<PGPPublicKeyRing> verificationKeys, @Nullable MissingPublicKeyCallback missingPublicKeyCallback) throws IOException, PGPException {
    InputStream pgpInputStream;
    DecryptionStreamFactory factory = new DecryptionStreamFactory(decryptionKeys, decryptor, decryptionPreplacedphrase, verificationKeys, missingPublicKeyCallback);
    if (detachedSignatures != null) {
        pgpInputStream = inputStream;
        for (PGPSignature signature : detachedSignatures) {
            PGPPublicKey signingKey = factory.findSignatureVerificationKey(signature.getKeyID());
            if (signingKey == null) {
                continue;
            }
            signature.init(ImplementationFactory.getInstance().getPGPContentVerifierBuilderProvider(), signingKey);
            factory.resultBuilder.addDetachedSignature(new DetachedSignature(signature, new OpenPgpV4Fingerprint(signingKey)));
        }
    } else {
        PGPObjectFactory objectFactory = new PGPObjectFactory(PGPUtil.getDecoderStream(inputStream), keyFingerprintCalculator);
        pgpInputStream = factory.processPGPPackets(objectFactory, 1);
    }
    return new DecryptionStream(pgpInputStream, factory.resultBuilder, factory.integrityProtectedStreams);
}

11 Source : SecretKeyRingEditor.java
with Apache License 2.0
from pgpainless

private PGPSignature getPreviousSignature(PGPSecretKey primaryKey, PGPPublicKey subjectPubKey) {
    PGPSignature oldSignature = null;
    if (primaryKey.getKeyID() == subjectPubKey.getKeyID()) {
        Iterator<PGPSignature> keySignatures = subjectPubKey.getSignaturesForKeyID(primaryKey.getKeyID());
        while (keySignatures.hasNext()) {
            PGPSignature next = keySignatures.next();
            if (next.getSignatureType() == PGPSignature.POSITIVE_CERTIFICATION) {
                oldSignature = next;
            }
        }
        if (oldSignature == null) {
            throw new IllegalStateException("Key " + new OpenPgpV4Fingerprint(subjectPubKey) + " does not have a previous positive signature.");
        }
    } else {
        Iterator bindingSignatures = subjectPubKey.getSignaturesOfType(SignatureType.SUBKEY_BINDING.getCode());
        while (bindingSignatures.hasNext()) {
            oldSignature = (PGPSignature) bindingSignatures.next();
        }
    }
    if (oldSignature == null) {
        throw new IllegalStateException("Key " + new OpenPgpV4Fingerprint(subjectPubKey) + " does not have a previous subkey binding signature.");
    }
    return oldSignature;
}

9 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());
}

7 Source : BCUtil.java
with Apache License 2.0
from pgpainless

public static Set<Long> signingKeyIds(@Nonnull PGPSecretKeyRing ring) {
    Set<Long> ids = new HashSet<>();
    Iterator<PGPPublicKey> it = ring.getPublicKeys();
    while (it.hasNext()) {
        PGPPublicKey k = it.next();
        boolean signingKey = false;
        Iterator<?> sit = k.getSignatures();
        while (sit.hasNext()) {
            Object n = sit.next();
            if (!(n instanceof PGPSignature)) {
                continue;
            }
            PGPSignature s = (PGPSignature) n;
            if (!s.hreplacedubpackets()) {
                continue;
            }
            try {
                s.verifyCertification(ring.getPublicKey(s.getKeyID()));
            } catch (PGPException e) {
                LOGGER.log(Level.WARNING, "Could not verify signature on " + Long.toHexString(k.getKeyID()) + " made by " + Long.toHexString(s.getKeyID()));
                continue;
            }
            PGPSignatureSubpacketVector hashed = s.getHashedSubPackets();
            if (KeyFlag.fromBitmask(hashed.getKeyFlags()).contains(KeyFlag.SIGN_DATA)) {
                signingKey = true;
                break;
            }
        }
        if (signingKey) {
            ids.add(k.getKeyID());
        }
    }
    return ids;
}

5 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());
}

2 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());
}

0 Source : SecretKeyRingEditor.java
with Apache License 2.0
from pgpainless

private PGPSignature generateRevocation(SecretKeyRingProtector protector, PGPPublicKey revokeeSubKey, RevocationAttributes revocationAttributes) throws PGPException {
    PGPSecretKey primaryKey = secretKeyRing.getSecretKey();
    PGPSignatureGenerator signatureGenerator = SignatureUtils.getSignatureGeneratorFor(primaryKey);
    PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
    subpacketGenerator.setIssuerFingerprint(false, primaryKey);
    if (revocationAttributes != null) {
        subpacketGenerator.setRevocationReason(false, revocationAttributes.getReason().code(), revocationAttributes.getDescription());
    }
    PGPSignatureSubpacketVector subPackets = subpacketGenerator.generate();
    signatureGenerator.setHashedSubpackets(subPackets);
    PGPPrivateKey privateKey = primaryKey.extractPrivateKey(protector.getDecryptor(primaryKey.getKeyID()));
    SignatureType type = revokeeSubKey.isMasterKey() ? SignatureType.KEY_REVOCATION : SignatureType.SUBKEY_REVOCATION;
    signatureGenerator.init(type.getCode(), privateKey);
    // Generate revocation
    PGPSignature subKeyRevocation = signatureGenerator.generateCertification(primaryKey.getPublicKey(), revokeeSubKey);
    return subKeyRevocation;
}

0 Source : SecretKeyRingEditor.java
with Apache License 2.0
from pgpainless

private SecretKeyRingEditorInterface doRevokeUserId(String userId, long subKeyId, SecretKeyRingProtector protector, RevocationAttributes revocationAttributes) throws PGPException {
    PGPPublicKey publicKey = KeyRingUtils.requirePublicKeyFrom(secretKeyRing, subKeyId);
    PGPSecretKey primaryKey = secretKeyRing.getSecretKey();
    PGPPrivateKey privateKey = unlockSecretKey(primaryKey, protector);
    PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
    subpacketGenerator.setSignatureCreationTime(false, new Date());
    subpacketGenerator.setRevocable(false, false);
    subpacketGenerator.setIssuerFingerprint(false, primaryKey);
    if (revocationAttributes != null) {
        RevocationAttributes.Reason reason = revocationAttributes.getReason();
        if (reason != RevocationAttributes.Reason.NO_REASON && reason != RevocationAttributes.Reason.USER_ID_NO_LONGER_VALID) {
            throw new IllegalArgumentException("Revocation reason must either be NO_REASON or USER_ID_NO_LONGER_VALID");
        }
        subpacketGenerator.setRevocationReason(false, revocationAttributes.getReason().code(), revocationAttributes.getDescription());
    }
    PGPSignatureGenerator signatureGenerator = SignatureUtils.getSignatureGeneratorFor(primaryKey);
    signatureGenerator.setHashedSubpackets(subpacketGenerator.generate());
    signatureGenerator.init(SignatureType.CERTIFICATION_REVOCATION.getCode(), privateKey);
    PGPSignature revocationSignature = signatureGenerator.generateCertification(userId, publicKey);
    publicKey = PGPPublicKey.addCertification(publicKey, userId, revocationSignature);
    PGPPublicKeyRing publicKeyRing = KeyRingUtils.publicKeyRingFrom(secretKeyRing);
    publicKeyRing = PGPPublicKeyRing.insertPublicKey(publicKeyRing, publicKey);
    secretKeyRing = PGPSecretKeyRing.replacePublicKeys(secretKeyRing, publicKeyRing);
    return this;
}

See More Examples