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

Various code cleanup

This commit is contained in:
Paul Schaub 2021-12-28 13:32:50 +01:00
parent 39686949d2
commit ce7b69269b
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
55 changed files with 182 additions and 194 deletions

View file

@ -71,7 +71,6 @@ public final class PGPainless {
*
* @param key key or certificate
* @return ascii armored string
* @throws IOException
*/
public static String asciiArmor(@Nonnull PGPKeyRing key) throws IOException {
if (key instanceof PGPSecretKeyRing) {

View file

@ -22,7 +22,7 @@ public class DecryptionBuilder implements DecryptionBuilderInterface {
return new DecryptWithImpl(inputStream);
}
class DecryptWithImpl implements DecryptWith {
static class DecryptWithImpl implements DecryptWith {
private final BufferedInputStream inputStream;

View file

@ -104,7 +104,8 @@ public final class DecryptionStreamFactory {
long issuerKeyId = SignatureUtils.determineIssuerKeyId(signature);
PGPPublicKeyRing signingKeyRing = findSignatureVerificationKeyRing(issuerKeyId);
if (signingKeyRing == null) {
SignatureValidationException ex = new SignatureValidationException("Missing verification certificate " + Long.toHexString(issuerKeyId));
SignatureValidationException ex = new SignatureValidationException(
"Missing verification certificate " + Long.toHexString(issuerKeyId));
resultBuilder.addInvalidDetachedSignature(new SignatureVerification(signature, null), ex);
continue;
}
@ -112,16 +113,19 @@ public final class DecryptionStreamFactory {
SubkeyIdentifier signingKeyIdentifier = new SubkeyIdentifier(signingKeyRing, signingKey.getKeyID());
try {
signature.init(verifierBuilderProvider, signingKey);
DetachedSignatureCheck detachedSignature = new DetachedSignatureCheck(signature, signingKeyRing, signingKeyIdentifier);
DetachedSignatureCheck detachedSignature =
new DetachedSignatureCheck(signature, signingKeyRing, signingKeyIdentifier);
detachedSignatureChecks.add(detachedSignature);
} catch (PGPException e) {
SignatureValidationException ex = new SignatureValidationException("Cannot verify detached signature made by " + signingKeyIdentifier + ".", e);
SignatureValidationException ex = new SignatureValidationException(
"Cannot verify detached signature made by " + signingKeyIdentifier + ".", e);
resultBuilder.addInvalidDetachedSignature(new SignatureVerification(signature, signingKeyIdentifier), ex);
}
}
}
private DecryptionStream parseOpenPGPDataAndCreateDecryptionStream(InputStream inputStream) throws IOException, PGPException {
private DecryptionStream parseOpenPGPDataAndCreateDecryptionStream(InputStream inputStream)
throws IOException, PGPException {
// Make sure we handle armored and non-armored data properly
BufferedInputStream bufferedIn = new BufferedInputStream(inputStream, 512);
bufferedIn.mark(512);
@ -185,7 +189,8 @@ public final class DecryptionStreamFactory {
resultBuilder);
}
private InputStream processPGPPackets(@Nonnull PGPObjectFactory objectFactory, int depth) throws IOException, PGPException {
private InputStream processPGPPackets(@Nonnull PGPObjectFactory objectFactory, int depth)
throws IOException, PGPException {
if (depth >= MAX_PACKET_NESTING_DEPTH) {
throw new PGPException("Maximum depth of nested packages exceeded.");
}
@ -226,9 +231,13 @@ public final class DecryptionStreamFactory {
return processPGPPackets(factory, ++depth);
}
private IntegrityProtectedInputStream decryptWithProvidedSessionKey(PGPEncryptedDataList pgpEncryptedDataList, SessionKey sessionKey) throws PGPException {
private IntegrityProtectedInputStream decryptWithProvidedSessionKey(
PGPEncryptedDataList pgpEncryptedDataList,
SessionKey sessionKey)
throws PGPException {
PGPSessionKey pgpSessionKey = new PGPSessionKey(sessionKey.getAlgorithm().getAlgorithmId(), sessionKey.getKey());
SessionKeyDataDecryptorFactory decryptorFactory = ImplementationFactory.getInstance().provideSessionKeyDataDecryptorFactory(pgpSessionKey);
SessionKeyDataDecryptorFactory decryptorFactory =
ImplementationFactory.getInstance().provideSessionKeyDataDecryptorFactory(pgpSessionKey);
InputStream decryptedDataStream = null;
PGPEncryptedData encryptedData = null;
for (PGPEncryptedData pgpEncryptedData : pgpEncryptedDataList) {
@ -254,7 +263,8 @@ public final class DecryptionStreamFactory {
resultBuilder.setSessionKey(sessionKey);
throwIfAlgorithmIsRejected(sessionKey.getAlgorithm());
integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(decryptedDataStream, encryptedData, options);
integrityProtectedEncryptedInputStream =
new IntegrityProtectedInputStream(decryptedDataStream, encryptedData, options);
return integrityProtectedEncryptedInputStream;
}
@ -271,14 +281,20 @@ public final class DecryptionStreamFactory {
return processPGPPackets(objectFactory, ++depth);
}
private InputStream processOnePassSignatureList(@Nonnull PGPObjectFactory objectFactory, PGPOnePassSignatureList onePassSignatures, int depth)
private InputStream processOnePassSignatureList(
@Nonnull PGPObjectFactory objectFactory,
PGPOnePassSignatureList onePassSignatures,
int depth)
throws PGPException, IOException {
LOGGER.debug("Depth {}: Encountered PGPOnePassSignatureList of size {}", depth, onePassSignatures.size());
initOnePassSignatures(onePassSignatures);
return processPGPPackets(objectFactory, depth);
}
private InputStream processPGPLiteralData(@Nonnull PGPObjectFactory objectFactory, PGPLiteralData pgpLiteralData, int depth) throws IOException {
private InputStream processPGPLiteralData(
@Nonnull PGPObjectFactory objectFactory,
PGPLiteralData pgpLiteralData,
int depth) {
LOGGER.debug("Depth {}: Found PGPLiteralData", depth);
InputStream literalDataInputStream = pgpLiteralData.getInputStream();
@ -342,7 +358,8 @@ public final class DecryptionStreamFactory {
throwIfAlgorithmIsRejected(sessionKey.getAlgorithm());
integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(decryptedDataStream, pbeEncryptedData, options);
integrityProtectedEncryptedInputStream =
new IntegrityProtectedInputStream(decryptedDataStream, pbeEncryptedData, options);
return integrityProtectedEncryptedInputStream;
} catch (PGPException e) {
@ -375,7 +392,8 @@ public final class DecryptionStreamFactory {
continue;
}
privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData, postponedDueToMissingPassphrase, true);
privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData,
postponedDueToMissingPassphrase, true);
}
}
}
@ -405,7 +423,8 @@ public final class DecryptionStreamFactory {
if (secretKey == null) {
LOGGER.debug("Key " + Long.toHexString(keyId) + " is not valid or not capable for decryption.");
} else {
privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData, postponedDueToMissingPassphrase, true);
privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData,
postponedDueToMissingPassphrase, true);
}
}
if (privateKey == null) {
@ -437,7 +456,8 @@ public final class DecryptionStreamFactory {
PGPSecretKeyRing secretKeys = findDecryptionKeyRing(keyId.getKeyId());
PGPSecretKey secretKey = secretKeys.getSecretKey(keyId.getSubkeyId());
PGPPrivateKey privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData, postponedDueToMissingPassphrase, false);
PGPPrivateKey privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData,
postponedDueToMissingPassphrase, false);
if (privateKey == null) {
continue;
}
@ -524,19 +544,24 @@ public final class DecryptionStreamFactory {
}
throwIfAlgorithmIsRejected(symmetricKeyAlgorithm);
integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(encryptedSessionKey.getDataStream(dataDecryptor), encryptedSessionKey, options);
integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(
encryptedSessionKey.getDataStream(dataDecryptor), encryptedSessionKey, options);
return integrityProtectedEncryptedInputStream;
}
private void throwIfAlgorithmIsRejected(SymmetricKeyAlgorithm algorithm) throws UnacceptableAlgorithmException {
private void throwIfAlgorithmIsRejected(SymmetricKeyAlgorithm algorithm)
throws UnacceptableAlgorithmException {
if (!PGPainless.getPolicy().getSymmetricKeyDecryptionAlgorithmPolicy().isAcceptable(algorithm)) {
throw new UnacceptableAlgorithmException("Data is "
+ (algorithm == SymmetricKeyAlgorithm.NULL ? "unencrypted" : "encrypted with symmetric algorithm " + algorithm) + " which is not acceptable as per PGPainless' policy.\n" +
+ (algorithm == SymmetricKeyAlgorithm.NULL ?
"unencrypted" :
"encrypted with symmetric algorithm " + algorithm) + " which is not acceptable as per PGPainless' policy.\n" +
"To mark this algorithm as acceptable, use PGPainless.getPolicy().setSymmetricKeyDecryptionAlgorithmPolicy().");
}
}
private void initOnePassSignatures(@Nonnull PGPOnePassSignatureList onePassSignatureList) throws PGPException {
private void initOnePassSignatures(@Nonnull PGPOnePassSignatureList onePassSignatureList)
throws PGPException {
Iterator<PGPOnePassSignature> iterator = onePassSignatureList.iterator();
if (!iterator.hasNext()) {
throw new PGPException("Verification failed - No OnePassSignatures found");
@ -545,14 +570,16 @@ public final class DecryptionStreamFactory {
processOnePassSignatures(iterator);
}
private void processOnePassSignatures(Iterator<PGPOnePassSignature> signatures) throws PGPException {
private void processOnePassSignatures(Iterator<PGPOnePassSignature> signatures)
throws PGPException {
while (signatures.hasNext()) {
PGPOnePassSignature signature = signatures.next();
processOnePassSignature(signature);
}
}
private void processOnePassSignature(PGPOnePassSignature signature) throws PGPException {
private void processOnePassSignature(PGPOnePassSignature signature)
throws PGPException {
final long keyId = signature.getKeyID();
LOGGER.debug("Encountered OnePassSignature from {}", Long.toHexString(keyId));

View file

@ -7,6 +7,7 @@ package org.pgpainless.decryption_verification;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -74,11 +75,11 @@ public final class MessageInspector {
*
* @param message OpenPGP message
* @return encryption info
* @throws PGPException
* @throws IOException
*/
public static EncryptionInfo determineEncryptionInfoForMessage(String message) throws PGPException, IOException {
return determineEncryptionInfoForMessage(new ByteArrayInputStream(message.getBytes("UTF-8")));
@SuppressWarnings("CharsetObjectCanBeUsed")
Charset charset = Charset.forName("UTF-8");
return determineEncryptionInfoForMessage(new ByteArrayInputStream(message.getBytes(charset)));
}
/**
@ -87,8 +88,6 @@ public final class MessageInspector {
*
* @param dataIn openpgp message
* @return encryption information
* @throws IOException
* @throws PGPException
*/
public static EncryptionInfo determineEncryptionInfoForMessage(InputStream dataIn) throws IOException, PGPException {
InputStream decoded = ArmorUtils.getDecoderStream(dataIn);

View file

@ -93,7 +93,7 @@ public abstract class SignatureInputStream extends FilterInputStream {
return read;
}
public void parseAndCombineSignatures() throws IOException {
public void parseAndCombineSignatures() {
if (objectFactory == null) {
return;
}
@ -117,7 +117,8 @@ public abstract class SignatureInputStream extends FilterInputStream {
check.setSignature(signature);
resultBuilder.addInvalidInbandSignature(new SignatureVerification(signature, null),
new SignatureValidationException("Missing verification certificate " + Long.toHexString(signature.getKeyID())));
new SignatureValidationException(
"Missing verification certificate " + Long.toHexString(signature.getKeyID())));
}
}
}
@ -150,13 +151,16 @@ public abstract class SignatureInputStream extends FilterInputStream {
}
try {
signatureWasCreatedInBounds(options.getVerifyNotBefore(), options.getVerifyNotAfter()).verify(opSignature.getSignature());
signatureWasCreatedInBounds(options.getVerifyNotBefore(),
options.getVerifyNotAfter()).verify(opSignature.getSignature());
CertificateValidator.validateCertificateAndVerifyOnePassSignature(opSignature, policy);
resultBuilder.addVerifiedInbandSignature(new SignatureVerification(opSignature.getSignature(), opSignature.getSigningKey()));
resultBuilder.addVerifiedInbandSignature(
new SignatureVerification(opSignature.getSignature(), opSignature.getSigningKey()));
} catch (SignatureValidationException e) {
LOGGER.warn("One-pass-signature verification failed for signature made by key {}: {}",
opSignature.getSigningKey(), e.getMessage(), e);
resultBuilder.addInvalidInbandSignature(new SignatureVerification(opSignature.getSignature(), opSignature.getSigningKey()), e);
resultBuilder.addInvalidInbandSignature(
new SignatureVerification(opSignature.getSignature(), opSignature.getSigningKey()), e);
}
}
}
@ -165,13 +169,17 @@ public abstract class SignatureInputStream extends FilterInputStream {
Policy policy = PGPainless.getPolicy();
for (DetachedSignatureCheck s : detachedSignatures) {
try {
signatureWasCreatedInBounds(options.getVerifyNotBefore(), options.getVerifyNotAfter()).verify(s.getSignature());
CertificateValidator.validateCertificateAndVerifyInitializedSignature(s.getSignature(), (PGPPublicKeyRing) s.getSigningKeyRing(), policy);
resultBuilder.addVerifiedDetachedSignature(new SignatureVerification(s.getSignature(), s.getSigningKeyIdentifier()));
signatureWasCreatedInBounds(options.getVerifyNotBefore(),
options.getVerifyNotAfter()).verify(s.getSignature());
CertificateValidator.validateCertificateAndVerifyInitializedSignature(s.getSignature(),
(PGPPublicKeyRing) s.getSigningKeyRing(), policy);
resultBuilder.addVerifiedDetachedSignature(new SignatureVerification(s.getSignature(),
s.getSigningKeyIdentifier()));
} catch (SignatureValidationException e) {
LOGGER.warn("One-pass-signature verification failed for signature made by key {}: {}",
s.getSigningKeyIdentifier(), e.getMessage(), e);
resultBuilder.addInvalidDetachedSignature(new SignatureVerification(s.getSignature(), s.getSigningKeyIdentifier()), e);
resultBuilder.addInvalidDetachedSignature(new SignatureVerification(s.getSignature(),
s.getSigningKeyIdentifier()), e);
}
}
}

View file

@ -254,10 +254,7 @@ public final class EncryptionStream extends OutputStream {
// One-Pass-Signatures are bracketed. That means we have to append the signatures in reverse order
// compared to the one-pass-signature packets.
List<SubkeyIdentifier> signingKeys = new ArrayList<>();
for (SubkeyIdentifier signingKey : signingOptions.getSigningMethods().keySet()) {
signingKeys.add(signingKey);
}
List<SubkeyIdentifier> signingKeys = new ArrayList<>(signingOptions.getSigningMethods().keySet());
for (int i = signingKeys.size() - 1; i >= 0; i--) {
SubkeyIdentifier signingKey = signingKeys.get(i);
SigningOptions.SigningMethod signingMethod = signingOptions.getSigningMethods().get(signingKey);

View file

@ -18,6 +18,7 @@ import org.bouncycastle.util.encoders.Hex;
*
*/
public abstract class OpenPgpFingerprint implements CharSequence, Comparable<OpenPgpFingerprint> {
@SuppressWarnings("CharsetObjectCanBeUsed")
protected static final Charset utf8 = Charset.forName("UTF-8");
protected final String fingerprint;

View file

@ -54,6 +54,7 @@ import org.pgpainless.util.Passphrase;
public class KeyRingBuilder implements KeyRingBuilderInterface<KeyRingBuilder> {
@SuppressWarnings("CharsetObjectCanBeUsed")
private final Charset UTF8 = Charset.forName("UTF-8");
private KeySpec primaryKeySpec;

View file

@ -35,7 +35,7 @@ public interface KeyType {
/**
* Return the strength of the key in bits.
* @return
* @return strength of the key in bits
*/
int getBitStrength();

View file

@ -163,11 +163,9 @@ public class KeyRingInfo {
// Subkey is hard revoked
return false;
} else {
if (!SignatureUtils.isSignatureExpired(revocation)
&& revocation.getCreationTime().after(binding.getCreationTime())) {
// Key is soft-revoked, not yet re-bound
return false;
}
// Key is soft-revoked, not yet re-bound
return SignatureUtils.isSignatureExpired(revocation)
|| !revocation.getCreationTime().after(binding.getCreationTime());
}
}

View file

@ -48,7 +48,6 @@ public interface SecretKeyRingEditorInterface {
* certification signature.
* @param protector protector to unlock the primary secret key
* @return the builder
* @throws PGPException
*/
SecretKeyRingEditorInterface addUserId(
@Nonnull CharSequence userId,

View file

@ -29,6 +29,7 @@ public class KeyRingReader {
public static final int MAX_ITERATIONS = 10000;
@SuppressWarnings("CharsetObjectCanBeUsed")
public static final Charset UTF8 = Charset.forName("UTF-8");
public PGPPublicKeyRing publicKeyRing(@Nonnull InputStream inputStream) throws IOException {
@ -141,7 +142,6 @@ public class KeyRingReader {
* @param inputStream input stream
* @param maxIterations max iterations before abort
* @return public key ring collection
* @throws IOException
*/
public static PGPPublicKeyRingCollection readPublicKeyRingCollection(@Nonnull InputStream inputStream, int maxIterations)
throws IOException, PGPException {

View file

@ -112,7 +112,7 @@ public final class UserId implements CharSequence {
}
@Override
public CharSequence subSequence(int i, int i1) {
public @Nonnull CharSequence subSequence(int i, int i1) {
return toString().subSequence(i, i1);
}

View file

@ -195,7 +195,9 @@ public final class SignatureUtils {
* @throws IOException if the signatures cannot be read
*/
public static List<PGPSignature> readSignatures(String encodedSignatures) throws IOException, PGPException {
byte[] bytes = encodedSignatures.getBytes(Charset.forName("UTF8"));
@SuppressWarnings("CharsetObjectCanBeUsed")
Charset utf8 = Charset.forName("UTF-8");
byte[] bytes = encodedSignatures.getBytes(utf8);
return readSignatures(bytes);
}

View file

@ -114,7 +114,6 @@ public abstract class AbstractSignatureBuilder<B extends AbstractSignatureBuilde
* and with hashed and unhashed subpackets.
*
* @return pgp signature generator
* @throws PGPException
*/
protected PGPSignatureGenerator buildAndInitSignatureGenerator() throws PGPException {
PGPSignatureGenerator generator = new PGPSignatureGenerator(

View file

@ -84,7 +84,6 @@ public class ThirdPartyCertificationSignatureBuilder extends AbstractSignatureBu
* @param certifiedKey key ring
* @param userId user-id to certify
* @return signature
* @throws PGPException
*/
public PGPSignature build(PGPPublicKeyRing certifiedKey, String userId) throws PGPException {
return buildAndInitSignatureGenerator().generateCertification(userId, certifiedKey.getPublicKey());
@ -95,7 +94,6 @@ public class ThirdPartyCertificationSignatureBuilder extends AbstractSignatureBu
* @param certifiedKey key ring
* @param userAttribute user-attributes to certify
* @return signature
* @throws PGPException
*/
public PGPSignature build(PGPPublicKeyRing certifiedKey, PGPUserAttributeSubpacketVector userAttribute)
throws PGPException {

View file

@ -68,7 +68,7 @@ public final class BCUtil {
return true;
}
int len = (expected.length < supplied.length) ? expected.length : supplied.length;
int len = Math.min(expected.length, supplied.length);
int nonEqual = expected.length ^ supplied.length;

View file

@ -9,6 +9,8 @@ import java.io.InputStream;
import org.bouncycastle.bcpg.ArmoredInputStream;
import javax.annotation.Nonnull;
/**
* Utility class that causes read(bytes, offset, length) to properly throw exceptions
* caused by faulty CRC checksums.
@ -72,7 +74,7 @@ public class CRCingArmoredInputStreamWrapper extends ArmoredInputStream {
}
@Override
public int read(byte[] b) throws IOException {
public int read(@Nonnull byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**

View file

@ -68,7 +68,6 @@ public final class StreamGeneratorWrapper {
* @param modificationDate modification date
* @param buffer buffer
* @return encoding stream
* @throws IOException
*/
public OutputStream open(OutputStream outputStream, String filename, Date modificationDate, byte[] buffer) throws IOException {
if (literalDataGenerator != null) {
@ -80,8 +79,6 @@ public final class StreamGeneratorWrapper {
/**
* Close all encoding streams opened by this generator wrapper.
*
* @throws IOException
*/
public void close() throws IOException {
if (literalDataGenerator != null) {