1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2025-12-10 06:11:08 +01:00

Clean up BCUtils class

This commit is contained in:
Paul Schaub 2021-05-29 12:43:31 +02:00
parent 13c7572c8c
commit 1a5baa0fa4
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
9 changed files with 137 additions and 312 deletions

View file

@ -15,20 +15,30 @@
*/
package org.pgpainless.key.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import javax.annotation.Nonnull;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyRing;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.key.protection.UnlockSecretKey;
import org.pgpainless.util.selection.key.PublicKeySelectionStrategy;
import org.pgpainless.util.selection.key.impl.And;
import org.pgpainless.util.selection.key.impl.KeyBelongsToKeyRing;
import org.pgpainless.util.selection.key.impl.NoRevocation;
public class KeyRingUtils {
@ -138,4 +148,53 @@ public class KeyRingUtils {
public static PGPPrivateKey unlockSecretKey(PGPSecretKey secretKey, SecretKeyRingProtector protector) throws PGPException {
return UnlockSecretKey.unlockSecretKey(secretKey, protector);
}
/*
PGPXxxKeyRing -> PGPXxxKeyRingCollection
*/
public static PGPPublicKeyRingCollection keyRingsToKeyRingCollection(@Nonnull PGPPublicKeyRing... rings)
throws IOException, PGPException {
return new PGPPublicKeyRingCollection(Arrays.asList(rings));
}
public static PGPSecretKeyRingCollection keyRingsToKeyRingCollection(@Nonnull PGPSecretKeyRing... rings)
throws IOException, PGPException {
return new PGPSecretKeyRingCollection(Arrays.asList(rings));
}
/**
* Remove all keys from the key ring, are either not having a subkey signature from the master key
* (identified by {@code masterKeyId}), or are revoked ("normal" key revocation, as well as subkey revocation).
*
* @param ring key ring
* @param masterKey master key
* @return "cleaned" key ring
*/
public static PGPSecretKeyRing removeUnassociatedKeysFromKeyRing(@Nonnull PGPSecretKeyRing ring,
@Nonnull PGPPublicKey masterKey) {
if (!masterKey.isMasterKey()) {
throw new IllegalArgumentException("Given key is not a master key.");
}
// Only select keys which are signed by the master key and not revoked.
PublicKeySelectionStrategy selector = new And.PubKeySelectionStrategy(
new KeyBelongsToKeyRing.PubkeySelectionStrategy(masterKey),
new NoRevocation.PubKeySelectionStrategy());
PGPSecretKeyRing cleaned = ring;
Iterator<PGPSecretKey> secretKeys = ring.getSecretKeys();
while (secretKeys.hasNext()) {
PGPSecretKey secretKey = secretKeys.next();
if (!selector.accept(secretKey.getPublicKey())) {
cleaned = PGPSecretKeyRing.removeSecretKey(cleaned, secretKey);
}
}
return cleaned;
}
public static boolean keyRingContainsKeyWithId(@Nonnull PGPPublicKeyRing ring,
long keyId) {
return ring.getPublicKey(keyId) != null;
}
}

View file

@ -15,16 +15,22 @@
*/
package org.pgpainless.signature;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import org.bouncycastle.bcpg.sig.KeyExpirationTime;
import org.bouncycastle.bcpg.sig.RevocationReason;
import org.bouncycastle.bcpg.sig.SignatureExpirationTime;
import org.bouncycastle.openpgp.PGPMarker;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.PGPSignatureList;
import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder;
import org.pgpainless.PGPainless;
import org.pgpainless.algorithm.HashAlgorithm;
@ -34,6 +40,7 @@ import org.pgpainless.key.util.OpenPgpKeyAttributeUtil;
import org.pgpainless.key.util.RevocationAttributes;
import org.pgpainless.policy.Policy;
import org.pgpainless.signature.subpackets.SignatureSubpacketsUtil;
import org.pgpainless.util.BCUtil;
/**
* Utility methods related to signatures.
@ -167,4 +174,25 @@ public class SignatureUtils {
}
return RevocationAttributes.Reason.isHardRevocation(reasonSubpacket.getRevocationReason());
}
/**
* Parse an ASCII encoded list of OpenPGP signatures into a {@link PGPSignatureList}.
*
* @param encodedSignatures ASCII armored signature list
* @return signature list
* @throws IOException if the signatures cannot be read
*/
public static PGPSignatureList readSignatures(String encodedSignatures) throws IOException {
InputStream inputStream = BCUtil.getPgpDecoderInputStream(encodedSignatures.getBytes(Charset.forName("UTF8")));
PGPObjectFactory objectFactory = new PGPObjectFactory(inputStream, ImplementationFactory.getInstance().getKeyFingerprintCalculator());
Object next = objectFactory.nextObject();
while (next != null) {
if (next instanceof PGPMarker) {
next = objectFactory.nextObject();
continue;
}
return (PGPSignatureList) next;
}
return null;
}
}

View file

@ -16,100 +16,14 @@
package org.pgpainless.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyRing;
import org.bouncycastle.openpgp.PGPMarker;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureList;
import org.bouncycastle.openpgp.PGPSignatureSubpacketVector;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.util.io.Streams;
import org.pgpainless.algorithm.KeyFlag;
import org.pgpainless.implementation.ImplementationFactory;
import org.pgpainless.util.selection.key.PublicKeySelectionStrategy;
import org.pgpainless.util.selection.key.impl.And;
import org.pgpainless.util.selection.key.impl.KeyBelongsToKeyRing;
import org.pgpainless.util.selection.key.impl.NoRevocation;
public class BCUtil {
private static final Logger LOGGER = Logger.getLogger(BCUtil.class.getName());
public static Date getExpirationDate(Date creationDate, long validSeconds) {
if (validSeconds == 0) {
return null;
}
return new Date(creationDate.getTime() + 1000 * validSeconds);
}
/*
PGPXxxKeyRing -> PGPXxxKeyRingCollection
*/
public static PGPPublicKeyRingCollection keyRingsToKeyRingCollection(@Nonnull PGPPublicKeyRing... rings)
throws IOException, PGPException {
return new PGPPublicKeyRingCollection(Arrays.asList(rings));
}
public static PGPSecretKeyRingCollection keyRingsToKeyRingCollection(@Nonnull PGPSecretKeyRing... rings)
throws IOException, PGPException {
return new PGPSecretKeyRingCollection(Arrays.asList(rings));
}
/*
PGPXxxKeyRingCollection -> PGPXxxKeyRing
*/
public static PGPSecretKeyRing getKeyRingFromCollection(@Nonnull PGPSecretKeyRingCollection collection,
@Nonnull Long id)
throws PGPException {
PGPSecretKeyRing uncleanedRing = collection.getSecretKeyRing(id);
// Determine ids of signed keys
Set<Long> signedKeyIds = new HashSet<>();
signedKeyIds.add(id); // Add the signing key itself
Iterator<PGPPublicKey> signedPubKeys = uncleanedRing.getKeysWithSignaturesBy(id);
while (signedPubKeys.hasNext()) {
signedKeyIds.add(signedPubKeys.next().getKeyID());
}
PGPSecretKeyRing cleanedRing = uncleanedRing;
Iterator<PGPSecretKey> secretKeys = uncleanedRing.getSecretKeys();
while (secretKeys.hasNext()) {
PGPSecretKey secretKey = secretKeys.next();
if (!signedKeyIds.contains(secretKey.getKeyID())) {
cleanedRing = PGPSecretKeyRing.removeSecretKey(cleanedRing, secretKey);
}
}
return cleanedRing;
}
public static PGPPublicKeyRing getKeyRingFromCollection(@Nonnull PGPPublicKeyRingCollection collection,
@Nonnull Long id)
throws PGPException {
PGPPublicKey key = collection.getPublicKey(id);
return removeUnassociatedKeysFromKeyRing(collection.getPublicKeyRing(id), key);
}
public static InputStream getPgpDecoderInputStream(@Nonnull byte[] bytes)
throws IOException {
return getPgpDecoderInputStream(new ByteArrayInputStream(bytes));
@ -120,163 +34,4 @@ public class BCUtil {
return PGPUtil.getDecoderStream(inputStream);
}
public static byte[] getDecodedBytes(@Nonnull byte[] bytes)
throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Streams.pipeAll(getPgpDecoderInputStream(bytes), buffer);
return buffer.toByteArray();
}
public static byte[] getDecodedBytes(@Nonnull InputStream inputStream)
throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Streams.pipeAll(inputStream, buffer);
return getDecodedBytes(buffer.toByteArray());
}
/**
* Remove all keys from the key ring, are either not having a subkey signature from the master key
* (identified by {@code masterKeyId}), or are revoked ("normal" key revocation, as well as subkey revocation).
*
* @param ring key ring
* @param masterKey master key
* @return "cleaned" key ring
*/
public static PGPPublicKeyRing removeUnassociatedKeysFromKeyRing(@Nonnull PGPPublicKeyRing ring,
@Nonnull PGPPublicKey masterKey) {
if (!masterKey.isMasterKey()) {
throw new IllegalArgumentException("Given key is not a master key.");
}
// Only select keys which are signed by the master key and not revoked.
PublicKeySelectionStrategy selector = new And.PubKeySelectionStrategy(
new KeyBelongsToKeyRing.PubkeySelectionStrategy(masterKey),
new NoRevocation.PubKeySelectionStrategy());
PGPPublicKeyRing cleaned = ring;
Iterator<PGPPublicKey> publicKeys = ring.getPublicKeys();
while (publicKeys.hasNext()) {
PGPPublicKey publicKey = publicKeys.next();
if (!selector.accept(publicKey)) {
cleaned = PGPPublicKeyRing.removePublicKey(cleaned, publicKey);
}
}
return cleaned;
}
/**
* Remove all keys from the key ring, are either not having a subkey signature from the master key
* (identified by {@code masterKeyId}), or are revoked ("normal" key revocation, as well as subkey revocation).
*
* @param ring key ring
* @param masterKey master key
* @return "cleaned" key ring
*/
public static PGPSecretKeyRing removeUnassociatedKeysFromKeyRing(@Nonnull PGPSecretKeyRing ring,
@Nonnull PGPPublicKey masterKey) {
if (!masterKey.isMasterKey()) {
throw new IllegalArgumentException("Given key is not a master key.");
}
// Only select keys which are signed by the master key and not revoked.
PublicKeySelectionStrategy selector = new And.PubKeySelectionStrategy(
new KeyBelongsToKeyRing.PubkeySelectionStrategy(masterKey),
new NoRevocation.PubKeySelectionStrategy());
PGPSecretKeyRing cleaned = ring;
Iterator<PGPSecretKey> secretKeys = ring.getSecretKeys();
while (secretKeys.hasNext()) {
PGPSecretKey secretKey = secretKeys.next();
if (!selector.accept(secretKey.getPublicKey())) {
cleaned = PGPSecretKeyRing.removeSecretKey(cleaned, secretKey);
}
}
return cleaned;
}
public static PGPPublicKey getMasterKeyFrom(@Nonnull PGPKeyRing ring) {
Iterator<PGPPublicKey> it = ring.getPublicKeys();
while (it.hasNext()) {
PGPPublicKey k = it.next();
if (k.isMasterKey()) {
// There can only be one master key, so we can immediately return
return k;
}
}
return null;
}
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.hasSubpackets()) {
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;
}
public static boolean keyRingContainsKeyWithId(@Nonnull PGPPublicKeyRing ring,
long keyId) {
return ring.getPublicKey(keyId) != null;
}
public static boolean keyRingContainsKeyWithId(@Nonnull PGPSecretKeyRing ring,
long keyId) {
return ring.getSecretKey(keyId) != null;
}
/**
* Parse an ASCII encoded list of OpenPGP signatures into a {@link PGPSignatureList}.
*
* @param encodedSignatures ASCII armored signature list
* @return signature list
* @throws IOException if the signatures cannot be read
*/
public static PGPSignatureList readSignatures(String encodedSignatures) throws IOException {
InputStream inputStream = getPgpDecoderInputStream(encodedSignatures.getBytes(Charset.forName("UTF8")));
PGPObjectFactory objectFactory = new PGPObjectFactory(inputStream, ImplementationFactory.getInstance().getKeyFingerprintCalculator());
Object next = objectFactory.nextObject();
while (next != null) {
if (next instanceof PGPMarker) {
next = objectFactory.nextObject();
continue;
}
return (PGPSignatureList) next;
}
return null;
}
}