1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2024-11-26 06:12:06 +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 * @param key key or certificate
* @return ascii armored string * @return ascii armored string
* @throws IOException
*/ */
public static String asciiArmor(@Nonnull PGPKeyRing key) throws IOException { public static String asciiArmor(@Nonnull PGPKeyRing key) throws IOException {
if (key instanceof PGPSecretKeyRing) { if (key instanceof PGPSecretKeyRing) {

View file

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

View file

@ -104,7 +104,8 @@ public final class DecryptionStreamFactory {
long issuerKeyId = SignatureUtils.determineIssuerKeyId(signature); long issuerKeyId = SignatureUtils.determineIssuerKeyId(signature);
PGPPublicKeyRing signingKeyRing = findSignatureVerificationKeyRing(issuerKeyId); PGPPublicKeyRing signingKeyRing = findSignatureVerificationKeyRing(issuerKeyId);
if (signingKeyRing == null) { 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); resultBuilder.addInvalidDetachedSignature(new SignatureVerification(signature, null), ex);
continue; continue;
} }
@ -112,16 +113,19 @@ public final class DecryptionStreamFactory {
SubkeyIdentifier signingKeyIdentifier = new SubkeyIdentifier(signingKeyRing, signingKey.getKeyID()); SubkeyIdentifier signingKeyIdentifier = new SubkeyIdentifier(signingKeyRing, signingKey.getKeyID());
try { try {
signature.init(verifierBuilderProvider, signingKey); signature.init(verifierBuilderProvider, signingKey);
DetachedSignatureCheck detachedSignature = new DetachedSignatureCheck(signature, signingKeyRing, signingKeyIdentifier); DetachedSignatureCheck detachedSignature =
new DetachedSignatureCheck(signature, signingKeyRing, signingKeyIdentifier);
detachedSignatureChecks.add(detachedSignature); detachedSignatureChecks.add(detachedSignature);
} catch (PGPException e) { } 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); 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 // Make sure we handle armored and non-armored data properly
BufferedInputStream bufferedIn = new BufferedInputStream(inputStream, 512); BufferedInputStream bufferedIn = new BufferedInputStream(inputStream, 512);
bufferedIn.mark(512); bufferedIn.mark(512);
@ -185,7 +189,8 @@ public final class DecryptionStreamFactory {
resultBuilder); 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) { if (depth >= MAX_PACKET_NESTING_DEPTH) {
throw new PGPException("Maximum depth of nested packages exceeded."); throw new PGPException("Maximum depth of nested packages exceeded.");
} }
@ -226,9 +231,13 @@ public final class DecryptionStreamFactory {
return processPGPPackets(factory, ++depth); 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()); PGPSessionKey pgpSessionKey = new PGPSessionKey(sessionKey.getAlgorithm().getAlgorithmId(), sessionKey.getKey());
SessionKeyDataDecryptorFactory decryptorFactory = ImplementationFactory.getInstance().provideSessionKeyDataDecryptorFactory(pgpSessionKey); SessionKeyDataDecryptorFactory decryptorFactory =
ImplementationFactory.getInstance().provideSessionKeyDataDecryptorFactory(pgpSessionKey);
InputStream decryptedDataStream = null; InputStream decryptedDataStream = null;
PGPEncryptedData encryptedData = null; PGPEncryptedData encryptedData = null;
for (PGPEncryptedData pgpEncryptedData : pgpEncryptedDataList) { for (PGPEncryptedData pgpEncryptedData : pgpEncryptedDataList) {
@ -254,7 +263,8 @@ public final class DecryptionStreamFactory {
resultBuilder.setSessionKey(sessionKey); resultBuilder.setSessionKey(sessionKey);
throwIfAlgorithmIsRejected(sessionKey.getAlgorithm()); throwIfAlgorithmIsRejected(sessionKey.getAlgorithm());
integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(decryptedDataStream, encryptedData, options); integrityProtectedEncryptedInputStream =
new IntegrityProtectedInputStream(decryptedDataStream, encryptedData, options);
return integrityProtectedEncryptedInputStream; return integrityProtectedEncryptedInputStream;
} }
@ -271,14 +281,20 @@ public final class DecryptionStreamFactory {
return processPGPPackets(objectFactory, ++depth); 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 { throws PGPException, IOException {
LOGGER.debug("Depth {}: Encountered PGPOnePassSignatureList of size {}", depth, onePassSignatures.size()); LOGGER.debug("Depth {}: Encountered PGPOnePassSignatureList of size {}", depth, onePassSignatures.size());
initOnePassSignatures(onePassSignatures); initOnePassSignatures(onePassSignatures);
return processPGPPackets(objectFactory, depth); 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); LOGGER.debug("Depth {}: Found PGPLiteralData", depth);
InputStream literalDataInputStream = pgpLiteralData.getInputStream(); InputStream literalDataInputStream = pgpLiteralData.getInputStream();
@ -342,7 +358,8 @@ public final class DecryptionStreamFactory {
throwIfAlgorithmIsRejected(sessionKey.getAlgorithm()); throwIfAlgorithmIsRejected(sessionKey.getAlgorithm());
integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(decryptedDataStream, pbeEncryptedData, options); integrityProtectedEncryptedInputStream =
new IntegrityProtectedInputStream(decryptedDataStream, pbeEncryptedData, options);
return integrityProtectedEncryptedInputStream; return integrityProtectedEncryptedInputStream;
} catch (PGPException e) { } catch (PGPException e) {
@ -375,7 +392,8 @@ public final class DecryptionStreamFactory {
continue; 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) { if (secretKey == null) {
LOGGER.debug("Key " + Long.toHexString(keyId) + " is not valid or not capable for decryption."); LOGGER.debug("Key " + Long.toHexString(keyId) + " is not valid or not capable for decryption.");
} else { } else {
privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData, postponedDueToMissingPassphrase, true); privateKey = tryPublicKeyDecryption(secretKeys, secretKey, publicKeyEncryptedData,
postponedDueToMissingPassphrase, true);
} }
} }
if (privateKey == null) { if (privateKey == null) {
@ -437,7 +456,8 @@ public final class DecryptionStreamFactory {
PGPSecretKeyRing secretKeys = findDecryptionKeyRing(keyId.getKeyId()); PGPSecretKeyRing secretKeys = findDecryptionKeyRing(keyId.getKeyId());
PGPSecretKey secretKey = secretKeys.getSecretKey(keyId.getSubkeyId()); 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) { if (privateKey == null) {
continue; continue;
} }
@ -524,19 +544,24 @@ public final class DecryptionStreamFactory {
} }
throwIfAlgorithmIsRejected(symmetricKeyAlgorithm); throwIfAlgorithmIsRejected(symmetricKeyAlgorithm);
integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(encryptedSessionKey.getDataStream(dataDecryptor), encryptedSessionKey, options); integrityProtectedEncryptedInputStream = new IntegrityProtectedInputStream(
encryptedSessionKey.getDataStream(dataDecryptor), encryptedSessionKey, options);
return integrityProtectedEncryptedInputStream; return integrityProtectedEncryptedInputStream;
} }
private void throwIfAlgorithmIsRejected(SymmetricKeyAlgorithm algorithm) throws UnacceptableAlgorithmException { private void throwIfAlgorithmIsRejected(SymmetricKeyAlgorithm algorithm)
throws UnacceptableAlgorithmException {
if (!PGPainless.getPolicy().getSymmetricKeyDecryptionAlgorithmPolicy().isAcceptable(algorithm)) { if (!PGPainless.getPolicy().getSymmetricKeyDecryptionAlgorithmPolicy().isAcceptable(algorithm)) {
throw new UnacceptableAlgorithmException("Data is " 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()."); "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(); Iterator<PGPOnePassSignature> iterator = onePassSignatureList.iterator();
if (!iterator.hasNext()) { if (!iterator.hasNext()) {
throw new PGPException("Verification failed - No OnePassSignatures found"); throw new PGPException("Verification failed - No OnePassSignatures found");
@ -545,14 +570,16 @@ public final class DecryptionStreamFactory {
processOnePassSignatures(iterator); processOnePassSignatures(iterator);
} }
private void processOnePassSignatures(Iterator<PGPOnePassSignature> signatures) throws PGPException { private void processOnePassSignatures(Iterator<PGPOnePassSignature> signatures)
throws PGPException {
while (signatures.hasNext()) { while (signatures.hasNext()) {
PGPOnePassSignature signature = signatures.next(); PGPOnePassSignature signature = signatures.next();
processOnePassSignature(signature); processOnePassSignature(signature);
} }
} }
private void processOnePassSignature(PGPOnePassSignature signature) throws PGPException { private void processOnePassSignature(PGPOnePassSignature signature)
throws PGPException {
final long keyId = signature.getKeyID(); final long keyId = signature.getKeyID();
LOGGER.debug("Encountered OnePassSignature from {}", Long.toHexString(keyId)); 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.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -74,11 +75,11 @@ public final class MessageInspector {
* *
* @param message OpenPGP message * @param message OpenPGP message
* @return encryption info * @return encryption info
* @throws PGPException
* @throws IOException
*/ */
public static EncryptionInfo determineEncryptionInfoForMessage(String message) throws PGPException, 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 * @param dataIn openpgp message
* @return encryption information * @return encryption information
* @throws IOException
* @throws PGPException
*/ */
public static EncryptionInfo determineEncryptionInfoForMessage(InputStream dataIn) throws IOException, PGPException { public static EncryptionInfo determineEncryptionInfoForMessage(InputStream dataIn) throws IOException, PGPException {
InputStream decoded = ArmorUtils.getDecoderStream(dataIn); InputStream decoded = ArmorUtils.getDecoderStream(dataIn);

View file

@ -93,7 +93,7 @@ public abstract class SignatureInputStream extends FilterInputStream {
return read; return read;
} }
public void parseAndCombineSignatures() throws IOException { public void parseAndCombineSignatures() {
if (objectFactory == null) { if (objectFactory == null) {
return; return;
} }
@ -117,7 +117,8 @@ public abstract class SignatureInputStream extends FilterInputStream {
check.setSignature(signature); check.setSignature(signature);
resultBuilder.addInvalidInbandSignature(new SignatureVerification(signature, null), 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 { try {
signatureWasCreatedInBounds(options.getVerifyNotBefore(), options.getVerifyNotAfter()).verify(opSignature.getSignature()); signatureWasCreatedInBounds(options.getVerifyNotBefore(),
options.getVerifyNotAfter()).verify(opSignature.getSignature());
CertificateValidator.validateCertificateAndVerifyOnePassSignature(opSignature, policy); CertificateValidator.validateCertificateAndVerifyOnePassSignature(opSignature, policy);
resultBuilder.addVerifiedInbandSignature(new SignatureVerification(opSignature.getSignature(), opSignature.getSigningKey())); resultBuilder.addVerifiedInbandSignature(
new SignatureVerification(opSignature.getSignature(), opSignature.getSigningKey()));
} catch (SignatureValidationException e) { } catch (SignatureValidationException e) {
LOGGER.warn("One-pass-signature verification failed for signature made by key {}: {}", LOGGER.warn("One-pass-signature verification failed for signature made by key {}: {}",
opSignature.getSigningKey(), e.getMessage(), e); 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(); Policy policy = PGPainless.getPolicy();
for (DetachedSignatureCheck s : detachedSignatures) { for (DetachedSignatureCheck s : detachedSignatures) {
try { try {
signatureWasCreatedInBounds(options.getVerifyNotBefore(), options.getVerifyNotAfter()).verify(s.getSignature()); signatureWasCreatedInBounds(options.getVerifyNotBefore(),
CertificateValidator.validateCertificateAndVerifyInitializedSignature(s.getSignature(), (PGPPublicKeyRing) s.getSigningKeyRing(), policy); options.getVerifyNotAfter()).verify(s.getSignature());
resultBuilder.addVerifiedDetachedSignature(new SignatureVerification(s.getSignature(), s.getSigningKeyIdentifier())); CertificateValidator.validateCertificateAndVerifyInitializedSignature(s.getSignature(),
(PGPPublicKeyRing) s.getSigningKeyRing(), policy);
resultBuilder.addVerifiedDetachedSignature(new SignatureVerification(s.getSignature(),
s.getSigningKeyIdentifier()));
} catch (SignatureValidationException e) { } catch (SignatureValidationException e) {
LOGGER.warn("One-pass-signature verification failed for signature made by key {}: {}", LOGGER.warn("One-pass-signature verification failed for signature made by key {}: {}",
s.getSigningKeyIdentifier(), e.getMessage(), e); 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 // One-Pass-Signatures are bracketed. That means we have to append the signatures in reverse order
// compared to the one-pass-signature packets. // compared to the one-pass-signature packets.
List<SubkeyIdentifier> signingKeys = new ArrayList<>(); List<SubkeyIdentifier> signingKeys = new ArrayList<>(signingOptions.getSigningMethods().keySet());
for (SubkeyIdentifier signingKey : signingOptions.getSigningMethods().keySet()) {
signingKeys.add(signingKey);
}
for (int i = signingKeys.size() - 1; i >= 0; i--) { for (int i = signingKeys.size() - 1; i >= 0; i--) {
SubkeyIdentifier signingKey = signingKeys.get(i); SubkeyIdentifier signingKey = signingKeys.get(i);
SigningOptions.SigningMethod signingMethod = signingOptions.getSigningMethods().get(signingKey); 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> { public abstract class OpenPgpFingerprint implements CharSequence, Comparable<OpenPgpFingerprint> {
@SuppressWarnings("CharsetObjectCanBeUsed")
protected static final Charset utf8 = Charset.forName("UTF-8"); protected static final Charset utf8 = Charset.forName("UTF-8");
protected final String fingerprint; protected final String fingerprint;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -195,7 +195,9 @@ public final class SignatureUtils {
* @throws IOException if the signatures cannot be read * @throws IOException if the signatures cannot be read
*/ */
public static List<PGPSignature> readSignatures(String encodedSignatures) throws IOException, PGPException { 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); return readSignatures(bytes);
} }

View file

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

View file

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

View file

@ -68,7 +68,7 @@ public final class BCUtil {
return true; 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; int nonEqual = expected.length ^ supplied.length;

View file

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

View file

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

View file

@ -278,12 +278,11 @@ public class AsciiArmorCRCTests {
/** /**
* This test verifies, whether PGPainless can read PGPSecretKeyRings from ASCII armored encodings * This test verifies, whether PGPainless can read PGPSecretKeyRings from ASCII armored encodings
* where the armor is missing its CRC checksum. * where the armor is missing its CRC checksum.
*
* @see <a href="https://tests.sequoia-pgp.org/#Mangled_ASCII_Armored_Key">Sequoia Test Suite</a> * @see <a href="https://tests.sequoia-pgp.org/#Mangled_ASCII_Armored_Key">Sequoia Test Suite</a>
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void missingCRCInArmoredKeyDoesNotCauseException() throws PGPException, IOException { public void missingCRCInArmoredKeyDoesNotCauseException() throws IOException {
String KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + String KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" +
"Comment: Bob's OpenPGP Transferable Secret Key\n" + "Comment: Bob's OpenPGP Transferable Secret Key\n" +
"\n" + "\n" +

View file

@ -79,7 +79,8 @@ public class CleartextSignatureVerificationTest {
public static final Random random = new Random(); public static final Random random = new Random();
@Test @Test
public void cleartextSignVerification_InMemoryMultiPassStrategy() throws IOException, PGPException { public void cleartextSignVerification_InMemoryMultiPassStrategy()
throws IOException, PGPException {
PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing(); PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing();
ConsumerOptions options = new ConsumerOptions() ConsumerOptions options = new ConsumerOptions()
.addVerificationCert(signingKeys); .addVerificationCert(signingKeys);
@ -104,7 +105,8 @@ public class CleartextSignatureVerificationTest {
} }
@Test @Test
public void cleartextSignVerification_FileBasedMultiPassStrategy() throws IOException, PGPException { public void cleartextSignVerification_FileBasedMultiPassStrategy()
throws IOException, PGPException {
PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing(); PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing();
ConsumerOptions options = new ConsumerOptions() ConsumerOptions options = new ConsumerOptions()
.addVerificationCert(signingKeys); .addVerificationCert(signingKeys);
@ -135,7 +137,8 @@ public class CleartextSignatureVerificationTest {
} }
@Test @Test
public void verifySignatureDetached() throws IOException, PGPException { public void verifySignatureDetached()
throws IOException, PGPException {
PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing(); PGPPublicKeyRing signingKeys = TestKeys.getEmilPublicKeyRing();
PGPSignature signature = SignatureUtils.readSignatures(SIGNATURE).get(0); PGPSignature signature = SignatureUtils.readSignatures(SIGNATURE).get(0);
@ -157,7 +160,8 @@ public class CleartextSignatureVerificationTest {
} }
@Test @Test
public void testOutputOfSigVerification() throws IOException, PGPException { public void testOutputOfSigVerification()
throws IOException, PGPException {
PGPSignature signature = SignatureUtils.readSignatures(SIGNATURE).get(0); PGPSignature signature = SignatureUtils.readSignatures(SIGNATURE).get(0);
ConsumerOptions options = new ConsumerOptions() ConsumerOptions options = new ConsumerOptions()
@ -177,7 +181,8 @@ public class CleartextSignatureVerificationTest {
} }
@Test @Test
public void consumingInlineSignedMessageWithCleartextSignedVerificationApiThrowsWrongConsumingMethodException() throws PGPException, IOException { public void consumingInlineSignedMessageWithCleartextSignedVerificationApiThrowsWrongConsumingMethodException()
throws IOException {
String inlineSignedMessage = "-----BEGIN PGP MESSAGE-----\n" + String inlineSignedMessage = "-----BEGIN PGP MESSAGE-----\n" +
"Version: PGPainless\n" + "Version: PGPainless\n" +
"\n" + "\n" +
@ -205,7 +210,8 @@ public class CleartextSignatureVerificationTest {
} }
@Test @Test
public void getDecoderStreamMistakensPlaintextForBase64RegressionTest() throws PGPException, IOException { public void getDecoderStreamMistakensPlaintextForBase64RegressionTest()
throws PGPException, IOException {
String message = "Foo\nBar"; // PGPUtil.getDecoderStream() would mistaken this for base64 data String message = "Foo\nBar"; // PGPUtil.getDecoderStream() would mistaken this for base64 data
ByteArrayInputStream msgIn = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)); ByteArrayInputStream msgIn = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
@ -236,7 +242,8 @@ public class CleartextSignatureVerificationTest {
} }
@Test @Test
public void testDecryptionOfVeryLongClearsignedMessage() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void testDecryptionOfVeryLongClearsignedMessage()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
String message = randomString(28, 4000); String message = randomString(28, 4000);
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice", null); PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice", null);

View file

@ -30,6 +30,7 @@ import org.pgpainless.util.TestAllImplementations;
public class DecryptAndVerifyMessageTest { public class DecryptAndVerifyMessageTest {
// Don't use StandardCharsets.UTF8 because of Android API level. // Don't use StandardCharsets.UTF8 because of Android API level.
@SuppressWarnings("CharsetObjectCanBeUsed")
private static final Charset UTF8 = Charset.forName("UTF-8"); private static final Charset UTF8 = Charset.forName("UTF-8");
private PGPSecretKeyRing juliet; private PGPSecretKeyRing juliet;

View file

@ -11,7 +11,6 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRing;
@ -120,7 +119,6 @@ public class PostponeDecryptionUsingKeyWithMissingPassphraseTest {
@Test @Test
public void missingPassphraseFirst() throws PGPException, IOException { public void missingPassphraseFirst() throws PGPException, IOException {
SecretKeyRingProtector protector1 = new CachingSecretKeyRingProtector(new SecretKeyPassphraseProvider() { SecretKeyRingProtector protector1 = new CachingSecretKeyRingProtector(new SecretKeyPassphraseProvider() {
@Nullable
@Override @Override
public Passphrase getPassphraseFor(Long keyId) { public Passphrase getPassphraseFor(Long keyId) {
fail("Although the first PKESK is for k1, we should have skipped it and tried k2 first, which has passphrase available."); fail("Although the first PKESK is for k1, we should have skipped it and tried k2 first, which has passphrase available.");
@ -151,7 +149,6 @@ public class PostponeDecryptionUsingKeyWithMissingPassphraseTest {
public void missingPassphraseSecond() throws PGPException, IOException { public void missingPassphraseSecond() throws PGPException, IOException {
SecretKeyRingProtector protector1 = SecretKeyRingProtector.unlockEachKeyWith(p1, k1); SecretKeyRingProtector protector1 = SecretKeyRingProtector.unlockEachKeyWith(p1, k1);
SecretKeyRingProtector protector2 = new CachingSecretKeyRingProtector(new SecretKeyPassphraseProvider() { SecretKeyRingProtector protector2 = new CachingSecretKeyRingProtector(new SecretKeyPassphraseProvider() {
@Nullable
@Override @Override
public Passphrase getPassphraseFor(Long keyId) { public Passphrase getPassphraseFor(Long keyId) {
fail("This callback should not get called, since the first PKESK is for k1, which has a passphrase available."); fail("This callback should not get called, since the first PKESK is for k1, which has a passphrase available.");
@ -180,7 +177,6 @@ public class PostponeDecryptionUsingKeyWithMissingPassphraseTest {
@Test @Test
public void messagePassphraseFirst() throws PGPException, IOException { public void messagePassphraseFirst() throws PGPException, IOException {
SecretKeyPassphraseProvider provider = new SecretKeyPassphraseProvider() { SecretKeyPassphraseProvider provider = new SecretKeyPassphraseProvider() {
@Nullable
@Override @Override
public Passphrase getPassphraseFor(Long keyId) { public Passphrase getPassphraseFor(Long keyId) {
fail("Since we provide a decryption passphrase, we should not try to decrypt any key."); fail("Since we provide a decryption passphrase, we should not try to decrypt any key.");

View file

@ -51,6 +51,7 @@ import org.pgpainless.util.TestAllImplementations;
public class EncryptDecryptTest { public class EncryptDecryptTest {
// Don't use StandardCharsets.UTF_8 because of Android API level. // Don't use StandardCharsets.UTF_8 because of Android API level.
@SuppressWarnings("CharsetObjectCanBeUsed")
private static final Charset UTF8 = Charset.forName("UTF-8"); private static final Charset UTF8 = Charset.forName("UTF-8");
private static final String testMessage = private static final String testMessage =

View file

@ -16,16 +16,11 @@ import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
import org.pgpainless.key.info.KeyRingInfo; import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.util.KeyRingUtils;
public class ConvertKeys { public class ConvertKeys {
/** /**
* This example demonstrates how to extract a public key certificate from a secret key. * This example demonstrates how to extract a public key certificate from a secret key.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/ */
@Test @Test
public void secretKeyToCertificate() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException { public void secretKeyToCertificate() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
@ -33,7 +28,7 @@ public class ConvertKeys {
PGPSecretKeyRing secretKey = PGPainless.generateKeyRing() PGPSecretKeyRing secretKey = PGPainless.generateKeyRing()
.modernKeyRing(userId, null); .modernKeyRing(userId, null);
// Extract certificate (public key) from secret key // Extract certificate (public key) from secret key
PGPPublicKeyRing certificate = KeyRingUtils.publicKeyRingFrom(secretKey); PGPPublicKeyRing certificate = PGPainless.extractCertificate(secretKey);
KeyRingInfo secretKeyInfo = PGPainless.inspectKeyRing(secretKey); KeyRingInfo secretKeyInfo = PGPainless.inspectKeyRing(secretKey);

View file

@ -98,9 +98,6 @@ public class Encrypt {
/** /**
* This example demonstrates how to encrypt and decrypt a message using a passphrase. * This example demonstrates how to encrypt and decrypt a message using a passphrase.
* This method can be combined with public key based encryption and signing. * This method can be combined with public key based encryption and signing.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void encryptUsingPassphrase() throws PGPException, IOException { public void encryptUsingPassphrase() throws PGPException, IOException {

View file

@ -30,7 +30,6 @@ import org.pgpainless.key.generation.type.ecc.EllipticCurve;
import org.pgpainless.key.generation.type.eddsa.EdDSACurve; import org.pgpainless.key.generation.type.eddsa.EdDSACurve;
import org.pgpainless.key.generation.type.rsa.RsaLength; import org.pgpainless.key.generation.type.rsa.RsaLength;
import org.pgpainless.key.info.KeyRingInfo; import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.util.KeyRingUtils;
import org.pgpainless.key.util.UserId; import org.pgpainless.key.util.UserId;
import org.pgpainless.util.Passphrase; import org.pgpainless.util.Passphrase;
@ -55,13 +54,10 @@ public class GenerateKeys {
* encryption subkey. * encryption subkey.
* *
* This is the recommended way to generate OpenPGP keys with PGPainless. * This is the recommended way to generate OpenPGP keys with PGPainless.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/ */
@Test @Test
public void generateModernEcKey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void generateModernEcKey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
// Define a primary user-id // Define a primary user-id
String userId = "gbaker@pgpainless.org"; String userId = "gbaker@pgpainless.org";
// Set a password to protect the secret key // Set a password to protect the secret key
@ -70,10 +66,10 @@ public class GenerateKeys {
PGPSecretKeyRing secretKey = PGPainless.generateKeyRing() PGPSecretKeyRing secretKey = PGPainless.generateKeyRing()
.modernKeyRing(userId, password); .modernKeyRing(userId, password);
// Extract public key // Extract public key
PGPPublicKeyRing publicKey = KeyRingUtils.publicKeyRingFrom(secretKey); PGPPublicKeyRing publicKey = PGPainless.extractCertificate(secretKey);
// Encode the public key to an ASCII armored string ready for sharing // Encode the public key to an ASCII armored string ready for sharing
String asciiArmoredPublicKey = PGPainless.asciiArmor(publicKey); String asciiArmoredPublicKey = PGPainless.asciiArmor(publicKey);
assertTrue(asciiArmoredPublicKey.startsWith("-----BEGIN PGP PUBLIC KEY BLOCK-----"));
KeyRingInfo keyInfo = new KeyRingInfo(secretKey); KeyRingInfo keyInfo = new KeyRingInfo(secretKey);
assertEquals(3, keyInfo.getSecretKeys().size()); assertEquals(3, keyInfo.getSecretKeys().size());
@ -91,13 +87,10 @@ public class GenerateKeys {
* The RSA key is used for both signing and certifying, as well as encryption. * The RSA key is used for both signing and certifying, as well as encryption.
* *
* This method is recommended if the application has to deal with legacy clients with poor algorithm support. * This method is recommended if the application has to deal with legacy clients with poor algorithm support.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/ */
@Test @Test
public void generateSimpleRSAKey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void generateSimpleRSAKey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
// Define a primary user-id // Define a primary user-id
String userId = "mpage@pgpainless.org"; String userId = "mpage@pgpainless.org";
// Set a password to protect the secret key // Set a password to protect the secret key
@ -118,13 +111,10 @@ public class GenerateKeys {
* and a single ECDH encryption subkey. * and a single ECDH encryption subkey.
* *
* This method is recommended if small keys and high performance are desired. * This method is recommended if small keys and high performance are desired.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/ */
@Test @Test
public void generateSimpleECKey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException { public void generateSimpleECKey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
// Define a primary user-id // Define a primary user-id
String userId = "mhelms@pgpainless.org"; String userId = "mhelms@pgpainless.org";
// Set a password to protect the secret key // Set a password to protect the secret key
@ -173,13 +163,10 @@ public class GenerateKeys {
* {@link org.pgpainless.key.generation.KeyRingBuilder#setExpirationDate(Date)}. * {@link org.pgpainless.key.generation.KeyRingBuilder#setExpirationDate(Date)}.
* Lastly you can decide whether to set a passphrase to protect the secret key using * Lastly you can decide whether to set a passphrase to protect the secret key using
* {@link org.pgpainless.key.generation.KeyRingBuilder#setPassphrase(Passphrase)}. * {@link org.pgpainless.key.generation.KeyRingBuilder#setPassphrase(Passphrase)}.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/ */
@Test @Test
public void generateCustomOpenPGPKey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException { public void generateCustomOpenPGPKey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
// Instead of providing a string, we can assemble a user-id by using the user-id builder. // Instead of providing a string, we can assemble a user-id by using the user-id builder.
// The example below corresponds to "Morgan Carpenter (Pride!) <mcarpenter@pgpainless.org>" // The example below corresponds to "Morgan Carpenter (Pride!) <mcarpenter@pgpainless.org>"
UserId userId = UserId.newBuilder() UserId userId = UserId.newBuilder()

View file

@ -90,8 +90,6 @@ public class ModifyKeys {
/** /**
* This example demonstrates how to change the passphrase of a secret key and all its subkeys. * This example demonstrates how to change the passphrase of a secret key and all its subkeys.
*
* @throws PGPException
*/ */
@Test @Test
public void changePassphrase() throws PGPException { public void changePassphrase() throws PGPException {
@ -112,8 +110,6 @@ public class ModifyKeys {
/** /**
* This example demonstrates how to change the passphrase of a single subkey in a key to a new passphrase. * This example demonstrates how to change the passphrase of a single subkey in a key to a new passphrase.
* Only the passphrase of the targeted key will be changed. All other keys remain untouched. * Only the passphrase of the targeted key will be changed. All other keys remain untouched.
*
* @throws PGPException
*/ */
@Test @Test
public void changeSingleSubkeyPassphrase() throws PGPException { public void changeSingleSubkeyPassphrase() throws PGPException {
@ -138,8 +134,6 @@ public class ModifyKeys {
/** /**
* This example demonstrates how to add an additional user-id to a key. * This example demonstrates how to add an additional user-id to a key.
*
* @throws PGPException
*/ */
@Test @Test
public void addUserId() throws PGPException { public void addUserId() throws PGPException {
@ -167,10 +161,6 @@ public class ModifyKeys {
* manually. * manually.
* *
* Once the subkey is added, it can be decrypted using the provided subkey passphrase. * Once the subkey is added, it can be decrypted using the provided subkey passphrase.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/ */
@Test @Test
public void addSubkey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void addSubkey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
@ -198,8 +188,6 @@ public class ModifyKeys {
/** /**
* This example demonstrates how to set a key expiration date. * This example demonstrates how to set a key expiration date.
* The provided expiration date will be set on each user-id certification signature. * The provided expiration date will be set on each user-id certification signature.
*
* @throws PGPException
*/ */
@Test @Test
public void setKeyExpirationDate() throws PGPException { public void setKeyExpirationDate() throws PGPException {
@ -223,8 +211,6 @@ public class ModifyKeys {
/** /**
* This example demonstrates how to revoke a user-id on a key. * This example demonstrates how to revoke a user-id on a key.
*
* @throws PGPException
*/ */
@Test @Test
public void revokeUserId() throws PGPException { public void revokeUserId() throws PGPException {

View file

@ -22,8 +22,6 @@ public class ReadKeys {
/** /**
* This example demonstrates how to parse a public key (certificate) from an ASCII armored string. * This example demonstrates how to parse a public key (certificate) from an ASCII armored string.
*
* @throws IOException
*/ */
@Test @Test
public void readCertificate() throws IOException { public void readCertificate() throws IOException {
@ -55,12 +53,9 @@ public class ReadKeys {
/** /**
* This example demonstrates how to parse an ASCII armored secret key. * This example demonstrates how to parse an ASCII armored secret key.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void readSecretKey() throws PGPException, IOException { public void readSecretKey() throws IOException {
String key = "\n" + String key = "\n" +
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" +
"Comment: Alice's OpenPGP Transferable Secret Key\n" + "Comment: Alice's OpenPGP Transferable Secret Key\n" +
@ -93,10 +88,7 @@ public class ReadKeys {
* This example demonstrates how to read a collection of multiple OpenPGP public keys (certificates) at once. * This example demonstrates how to read a collection of multiple OpenPGP public keys (certificates) at once.
* *
* Note, that a public key collection can both be a concatenation of public key blocks (like below), * Note, that a public key collection can both be a concatenation of public key blocks (like below),
* as well as a single public key block containing multiple public key packets. * and a single public key block containing multiple public key packets.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void readKeyRingCollection() throws PGPException, IOException { public void readKeyRingCollection() throws PGPException, IOException {

View file

@ -46,9 +46,6 @@ public class Sign {
/** /**
* Demonstration of how to use the PGPainless API to sign some message using inband signatures. * Demonstration of how to use the PGPainless API to sign some message using inband signatures.
* The result is not human-readable, however the resulting text contains both the signed data and the signatures. * The result is not human-readable, however the resulting text contains both the signed data and the signatures.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void inbandSignedMessage() throws PGPException, IOException { public void inbandSignedMessage() throws PGPException, IOException {
@ -75,9 +72,6 @@ public class Sign {
* A detached signature can be distributed alongside the message/file itself. * A detached signature can be distributed alongside the message/file itself.
* *
* The message/file doesn't need to be altered for detached signature creation. * The message/file doesn't need to be altered for detached signature creation.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void detachedSignedMessage() throws PGPException, IOException { public void detachedSignedMessage() throws PGPException, IOException {
@ -113,9 +107,6 @@ public class Sign {
* Demonstration of how to sign a text message in a way that keeps the message content * Demonstration of how to sign a text message in a way that keeps the message content
* human-readable by utilizing the OpenPGP Cleartext Signature Framework. * human-readable by utilizing the OpenPGP Cleartext Signature Framework.
* The resulting message contains the original (dash-escaped) message and the signatures. * The resulting message contains the original (dash-escaped) message and the signatures.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void cleartextSignedMessage() throws PGPException, IOException { public void cleartextSignedMessage() throws PGPException, IOException {

View file

@ -33,9 +33,6 @@ public class UnlockSecretKeys {
/** /**
* This example demonstrates how to create a {@link SecretKeyRingProtector} for unprotected secret keys. * This example demonstrates how to create a {@link SecretKeyRingProtector} for unprotected secret keys.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void unlockUnprotectedKeys() throws PGPException, IOException { public void unlockUnprotectedKeys() throws PGPException, IOException {
@ -50,9 +47,6 @@ public class UnlockSecretKeys {
/** /**
* This example demonstrates how to create a {@link SecretKeyRingProtector} using a single passphrase to unlock * This example demonstrates how to create a {@link SecretKeyRingProtector} using a single passphrase to unlock
* all secret subkeys of a key. * all secret subkeys of a key.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void unlockWholeKeyWithSamePassphrase() throws PGPException, IOException { public void unlockWholeKeyWithSamePassphrase() throws PGPException, IOException {
@ -68,9 +62,6 @@ public class UnlockSecretKeys {
/** /**
* This example demonstrates how to create a {@link SecretKeyRingProtector} that uses different * This example demonstrates how to create a {@link SecretKeyRingProtector} that uses different
* passphrases per subkey to unlock the secret keys. * passphrases per subkey to unlock the secret keys.
*
* @throws PGPException
* @throws IOException
*/ */
@Test @Test
public void unlockWithPerSubkeyPassphrases() throws PGPException, IOException { public void unlockWithPerSubkeyPassphrases() throws PGPException, IOException {

View file

@ -6,7 +6,6 @@ package org.pgpainless.key;
import java.io.IOException; import java.io.IOException;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
@ -48,7 +47,7 @@ public class WeirdKeys {
"=BlPm\n" + "=BlPm\n" +
"-----END PGP PRIVATE KEY BLOCK-----\n"; "-----END PGP PRIVATE KEY BLOCK-----\n";
public static PGPSecretKeyRing getTwoCryptSubkeysKey() throws IOException, PGPException { public static PGPSecretKeyRing getTwoCryptSubkeysKey() throws IOException {
return PGPainless.readKeyRing().secretKeyRing(TWO_CRYPT_SUBKEYS); return PGPainless.readKeyRing().secretKeyRing(TWO_CRYPT_SUBKEYS);
} }
@ -77,7 +76,7 @@ public class WeirdKeys {
"=h6sT\n" + "=h6sT\n" +
"-----END PGP PRIVATE KEY BLOCK-----\n"; "-----END PGP PRIVATE KEY BLOCK-----\n";
public static PGPSecretKeyRing getArchiveCommsSubkeysKey() throws IOException, PGPException { public static PGPSecretKeyRing getArchiveCommsSubkeysKey() throws IOException {
return PGPainless.readKeyRing().secretKeyRing(ARCHIVE_COMMS_SUBKEYS); return PGPainless.readKeyRing().secretKeyRing(ARCHIVE_COMMS_SUBKEYS);
} }
} }

View file

@ -34,6 +34,7 @@ import org.pgpainless.key.generation.type.xdh.XDHSpec;
import org.pgpainless.key.info.KeyRingInfo; import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.protection.SecretKeyRingProtector; import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.signature.subpackets.SelfSignatureSubpackets; import org.pgpainless.signature.subpackets.SelfSignatureSubpackets;
import org.pgpainless.util.Passphrase;
public class KeyGenerationSubpacketsTest { public class KeyGenerationSubpacketsTest {
@ -105,13 +106,15 @@ public class KeyGenerationSubpacketsTest {
} }
@Test @Test
public void verifyDefaultSubpacketsForSubkeyBindingSignatures() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void verifyDefaultSubpacketsForSubkeyBindingSignatures()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice", null); PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice", null);
KeyRingInfo info = PGPainless.inspectKeyRing(secretKeys); KeyRingInfo info = PGPainless.inspectKeyRing(secretKeys);
List<PGPPublicKey> keysBefore = info.getPublicKeys(); List<PGPPublicKey> keysBefore = info.getPublicKeys();
secretKeys = PGPainless.modifyKeyRing(secretKeys) secretKeys = PGPainless.modifyKeyRing(secretKeys)
.addSubKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519), KeyFlag.SIGN_DATA).build(), null, SecretKeyRingProtector.unprotectedKeys()) .addSubKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519), KeyFlag.SIGN_DATA).build(),
Passphrase.emptyPassphrase(), SecretKeyRingProtector.unprotectedKeys())
.done(); .done();
@ -127,7 +130,8 @@ public class KeyGenerationSubpacketsTest {
assertNotNull(bindingSig.getHashedSubPackets().getEmbeddedSignatures().get(0)); assertNotNull(bindingSig.getHashedSubPackets().getEmbeddedSignatures().get(0));
secretKeys = PGPainless.modifyKeyRing(secretKeys) secretKeys = PGPainless.modifyKeyRing(secretKeys)
.addSubKey(KeySpec.getBuilder(KeyType.XDH(XDHSpec._X25519), KeyFlag.ENCRYPT_COMMS).build(), null, .addSubKey(KeySpec.getBuilder(KeyType.XDH(XDHSpec._X25519), KeyFlag.ENCRYPT_COMMS).build(),
Passphrase.emptyPassphrase(),
new SelfSignatureSubpackets.Callback() { new SelfSignatureSubpackets.Callback() {
@Override @Override
public void modifyHashedSubpackets(SelfSignatureSubpackets hashedSubpackets) { public void modifyHashedSubpackets(SelfSignatureSubpackets hashedSubpackets) {

View file

@ -213,7 +213,8 @@ public class KeyRingInfoTest {
@TestTemplate @TestTemplate
@ExtendWith(TestAllImplementations.class) @ExtendWith(TestAllImplementations.class)
public void testGetKeysWithFlagsAndExpiry() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException { public void testGetKeysWithFlagsAndExpiry()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
PGPSecretKeyRing secretKeys = PGPainless.buildKeyRing() PGPSecretKeyRing secretKeys = PGPainless.buildKeyRing()
.setPrimaryKey(KeySpec.getBuilder( .setPrimaryKey(KeySpec.getBuilder(

View file

@ -16,7 +16,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRing;
@ -32,8 +31,8 @@ import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.protection.PasswordBasedSecretKeyRingProtector; import org.pgpainless.key.protection.PasswordBasedSecretKeyRingProtector;
import org.pgpainless.key.protection.SecretKeyRingProtector; import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.key.protection.UnlockSecretKey; import org.pgpainless.key.protection.UnlockSecretKey;
import org.pgpainless.util.TestAllImplementations;
import org.pgpainless.util.Passphrase; import org.pgpainless.util.Passphrase;
import org.pgpainless.util.TestAllImplementations;
public class AddSubKeyTest { public class AddSubKeyTest {
@ -67,7 +66,7 @@ public class AddSubKeyTest {
PGPSecretKey subKey = secretKeys.getSecretKey(subKeyId); PGPSecretKey subKey = secretKeys.getSecretKey(subKeyId);
SecretKeyRingProtector protector = SecretKeyRingProtector.unlockEachKeyWith( SecretKeyRingProtector protector = SecretKeyRingProtector.unlockEachKeyWith(
Passphrase.fromPassword("subKeyPassphrase"), secretKeys); Passphrase.fromPassword("subKeyPassphrase"), secretKeys);
PGPPrivateKey privateKey = UnlockSecretKey.unlockSecretKey(subKey, protector); UnlockSecretKey.unlockSecretKey(subKey, protector);
KeyRingInfo info = new KeyRingInfo(secretKeys); KeyRingInfo info = new KeyRingInfo(secretKeys);
assertEquals(Collections.singletonList(KeyFlag.SIGN_DATA), info.getKeyFlagsOf(subKeyId)); assertEquals(Collections.singletonList(KeyFlag.SIGN_DATA), info.getKeyFlagsOf(subKeyId));

View file

@ -36,7 +36,7 @@ import org.pgpainless.signature.subpackets.SignatureSubpacketsUtil;
public class AddSubkeyWithModifiedBindingSignatureSubpackets { public class AddSubkeyWithModifiedBindingSignatureSubpackets {
public static long MILLIS_IN_SEC = 1000; public static final long MILLIS_IN_SEC = 1000;
@Test @Test
public void bindEncryptionSubkeyAndModifyBindingSignatureHashedSubpackets() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void bindEncryptionSubkeyAndModifyBindingSignatureHashedSubpackets() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {

View file

@ -131,7 +131,7 @@ public class ChangeSecretKeyRingPassphraseTest {
PGPSecretKey subKey = keys.next(); PGPSecretKey subKey = keys.next();
PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing) PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing)
.changeSubKeyPassphraseFromOldPassphrase(primaryKey.getKeyID(), Passphrase.fromPassword("weakPassphrase")) .changeSubKeyPassphraseFromOldPassphrase(subKey.getKeyID(), Passphrase.fromPassword("weakPassphrase"))
.withSecureDefaultSettings() .withSecureDefaultSettings()
.toNoPassphrase() .toNoPassphrase()
.done(); .done();
@ -140,17 +140,17 @@ public class ChangeSecretKeyRingPassphraseTest {
primaryKey = keys.next(); primaryKey = keys.next();
subKey = keys.next(); subKey = keys.next();
extractPrivateKey(primaryKey, Passphrase.emptyPassphrase()); extractPrivateKey(primaryKey, Passphrase.fromPassword("weakPassphrase"));
extractPrivateKey(subKey, Passphrase.fromPassword("weakPassphrase")); extractPrivateKey(subKey, Passphrase.emptyPassphrase());
final PGPSecretKey finalPrimaryKey = primaryKey; final PGPSecretKey finalPrimaryKey = primaryKey;
assertThrows(PGPException.class, assertThrows(PGPException.class,
() -> extractPrivateKey(finalPrimaryKey, Passphrase.fromPassword("weakPassphrase")), () -> extractPrivateKey(finalPrimaryKey, Passphrase.emptyPassphrase()),
"Unlocking the unprotected primary key with the old passphrase must fail."); "Unlocking the unprotected primary key with the old passphrase must fail.");
final PGPSecretKey finalSubKey = subKey; final PGPSecretKey finalSubKey = subKey;
assertThrows(PGPException.class, assertThrows(PGPException.class,
() -> extractPrivateKey(finalSubKey, Passphrase.emptyPassphrase()), () -> extractPrivateKey(finalSubKey, Passphrase.fromPassword("weakPassphrase")),
"Unlocking the still protected subkey with an empty passphrase must fail."); "Unlocking the still protected subkey with an empty passphrase must fail.");
} }

View file

@ -31,7 +31,8 @@ import org.pgpainless.util.Passphrase;
public class RefuseToAddWeakSubkeyTest { public class RefuseToAddWeakSubkeyTest {
@Test @Test
public void testEditorRefusesToAddWeakSubkey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void testEditorRefusesToAddWeakSubkey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
// ensure default policy is set // ensure default policy is set
PGPainless.getPolicy().setPublicKeyAlgorithmPolicy(Policy.PublicKeyAlgorithmPolicy.defaultPublicKeyAlgorithmPolicy()); PGPainless.getPolicy().setPublicKeyAlgorithmPolicy(Policy.PublicKeyAlgorithmPolicy.defaultPublicKeyAlgorithmPolicy());
@ -45,7 +46,8 @@ public class RefuseToAddWeakSubkeyTest {
} }
@Test @Test
public void testEditorAllowsToAddWeakSubkeyIfCompliesToPublicKeyAlgorithmPolicy() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException { public void testEditorAllowsToAddWeakSubkeyIfCompliesToPublicKeyAlgorithmPolicy()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing() PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing()
.modernKeyRing("Alice", null); .modernKeyRing("Alice", null);

View file

@ -35,6 +35,7 @@ import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.PGPUtil;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.opentest4j.TestAbortedException;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
import org.pgpainless.implementation.ImplementationFactory; import org.pgpainless.implementation.ImplementationFactory;
import org.pgpainless.key.OpenPgpV4Fingerprint; import org.pgpainless.key.OpenPgpV4Fingerprint;
@ -46,9 +47,17 @@ import org.pgpainless.util.TestUtils;
class KeyRingReaderTest { class KeyRingReaderTest {
private InputStream requireResource(String resourceName) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourceName);
if (inputStream == null) {
throw new TestAbortedException("Cannot read resource " + resourceName);
}
return inputStream;
}
@Test @Test
public void assertThatPGPUtilsDetectAsciiArmoredData() throws IOException, PGPException { public void assertThatPGPUtilsDetectAsciiArmoredData() throws IOException, PGPException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("pub_keys_10_pieces.asc"); InputStream inputStream = requireResource("pub_keys_10_pieces.asc");
InputStream possiblyArmored = PGPUtil.getDecoderStream(PGPUtil.getDecoderStream(inputStream)); InputStream possiblyArmored = PGPUtil.getDecoderStream(PGPUtil.getDecoderStream(inputStream));
@ -59,7 +68,7 @@ class KeyRingReaderTest {
@Test @Test
void publicKeyRingCollectionFromStream() throws IOException, PGPException { void publicKeyRingCollectionFromStream() throws IOException, PGPException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("pub_keys_10_pieces.asc"); InputStream inputStream = requireResource("pub_keys_10_pieces.asc");
PGPPublicKeyRingCollection rings = PGPainless.readKeyRing().publicKeyRingCollection(inputStream); PGPPublicKeyRingCollection rings = PGPainless.readKeyRing().publicKeyRingCollection(inputStream);
assertEquals(10, rings.size()); assertEquals(10, rings.size());
} }
@ -247,7 +256,7 @@ class KeyRingReaderTest {
} }
@Test @Test
public void testReadSecretKeyIgnoresMarkerPacket() throws PGPException, IOException { public void testReadSecretKeyIgnoresMarkerPacket() throws IOException {
String markerAndKey = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" + String markerAndKey = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" +
"Version: PGPainless\n" + "Version: PGPainless\n" +
"Comment: Secret Key with prepended Marker Packet\n" + "Comment: Secret Key with prepended Marker Packet\n" +

View file

@ -14,7 +14,6 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Iterator; import java.util.Iterator;
import java.util.Random; import java.util.Random;
import javax.annotation.Nullable;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyRing; import org.bouncycastle.openpgp.PGPKeyRing;
@ -32,7 +31,6 @@ public class CachingSecretKeyRingProtectorTest {
// Dummy passphrase callback that returns the doubled key-id as passphrase // Dummy passphrase callback that returns the doubled key-id as passphrase
private final SecretKeyPassphraseProvider dummyCallback = new SecretKeyPassphraseProvider() { private final SecretKeyPassphraseProvider dummyCallback = new SecretKeyPassphraseProvider() {
@Nullable
@Override @Override
public Passphrase getPassphraseFor(Long keyId) { public Passphrase getPassphraseFor(Long keyId) {
long doubled = keyId * 2; long doubled = keyId * 2;

View file

@ -16,7 +16,6 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKey;
@ -28,8 +27,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.pgpainless.PGPainless; import org.pgpainless.PGPainless;
import org.pgpainless.key.TestKeys; import org.pgpainless.key.TestKeys;
import org.pgpainless.key.protection.passphrase_provider.SecretKeyPassphraseProvider; import org.pgpainless.key.protection.passphrase_provider.SecretKeyPassphraseProvider;
import org.pgpainless.util.TestAllImplementations;
import org.pgpainless.util.Passphrase; import org.pgpainless.util.Passphrase;
import org.pgpainless.util.TestAllImplementations;
public class SecretKeyRingProtectorTest { public class SecretKeyRingProtectorTest {
@ -108,7 +107,6 @@ public class SecretKeyRingProtectorTest {
passphraseMap.put(1L, Passphrase.emptyPassphrase()); passphraseMap.put(1L, Passphrase.emptyPassphrase());
CachingSecretKeyRingProtector protector = new CachingSecretKeyRingProtector(passphraseMap, CachingSecretKeyRingProtector protector = new CachingSecretKeyRingProtector(passphraseMap,
KeyRingProtectionSettings.secureDefaultSettings(), new SecretKeyPassphraseProvider() { KeyRingProtectionSettings.secureDefaultSettings(), new SecretKeyPassphraseProvider() {
@Nullable
@Override @Override
public Passphrase getPassphraseFor(Long keyId) { public Passphrase getPassphraseFor(Long keyId) {
return Passphrase.fromPassword("missingP455w0rd"); return Passphrase.fromPassword("missingP455w0rd");

View file

@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test;
public class UnprotectedKeysProtectorTest { public class UnprotectedKeysProtectorTest {
private UnprotectedKeysProtector protector = new UnprotectedKeysProtector(); private final UnprotectedKeysProtector protector = new UnprotectedKeysProtector();
@Test @Test
public void testKeyProtectorReturnsNullDecryptor() { public void testKeyProtectorReturnsNullDecryptor() {

View file

@ -86,7 +86,7 @@ public class OnePassSignatureBracketingTest {
outerloop: while (true) { outerloop: while (true) {
Object next = objectFactory.nextObject(); Object next = objectFactory.nextObject();
if (next == null) { if (next == null) {
break outerloop; break;
} }
if (next instanceof PGPEncryptedDataList) { if (next instanceof PGPEncryptedDataList) {
PGPEncryptedDataList encryptedDataList = (PGPEncryptedDataList) next; PGPEncryptedDataList encryptedDataList = (PGPEncryptedDataList) next;

View file

@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -59,13 +58,16 @@ public class ProofUtilTest {
} }
@Test @Test
public void testAddProof() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException, InterruptedException { public void testAddProof()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InterruptedException {
String userId = "Alice <alice@pgpainless.org>"; String userId = "Alice <alice@pgpainless.org>";
PGPSecretKeyRing secretKey = PGPainless.generateKeyRing() PGPSecretKeyRing secretKey = PGPainless.generateKeyRing()
.modernKeyRing(userId, null); .modernKeyRing(userId, null);
Thread.sleep(1000L); Thread.sleep(1000L);
secretKey = new ProofUtil() secretKey = new ProofUtil().addProof(
.addProof(secretKey, SecretKeyRingProtector.unprotectedKeys(), new ProofUtil.Proof("xmpp:alice@pgpainless.org")); secretKey,
SecretKeyRingProtector.unprotectedKeys(),
new ProofUtil.Proof("xmpp:alice@pgpainless.org"));
KeyRingInfo info = PGPainless.inspectKeyRing(secretKey); KeyRingInfo info = PGPainless.inspectKeyRing(secretKey);
PGPSignature signature = info.getLatestUserIdCertification(userId); PGPSignature signature = info.getLatestUserIdCertification(userId);

View file

@ -6,7 +6,6 @@ package org.pgpainless.util;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Collections; import java.util.Collections;
@ -28,7 +27,8 @@ import org.pgpainless.key.util.OpenPgpKeyAttributeUtil;
public class GuessPreferredHashAlgorithmTest { public class GuessPreferredHashAlgorithmTest {
@Test @Test
public void guessPreferredHashAlgorithmsAssumesHashAlgoUsedBySelfSig() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, IOException { public void guessPreferredHashAlgorithmsAssumesHashAlgoUsedBySelfSig()
throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
PGPSecretKeyRing secretKeys = PGPainless.buildKeyRing() PGPSecretKeyRing secretKeys = PGPainless.buildKeyRing()
.setPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519), .setPrimaryKey(KeySpec.getBuilder(KeyType.EDDSA(EdDSACurve._Ed25519),
KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA) KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA)

View file

@ -18,8 +18,10 @@ import org.pgpainless.util.selection.keyring.impl.Wildcard;
public class WildcardKeyRingSelectionStrategyTest { public class WildcardKeyRingSelectionStrategyTest {
Wildcard.PubRingSelectionStrategy<String> pubKeySelectionStrategy = new Wildcard.PubRingSelectionStrategy<>(); private static final Wildcard.PubRingSelectionStrategy<String> pubKeySelectionStrategy
Wildcard.SecRingSelectionStrategy<String> secKeySelectionStrategy = new Wildcard.SecRingSelectionStrategy<>(); = new Wildcard.PubRingSelectionStrategy<>();
private static final Wildcard.SecRingSelectionStrategy<String> secKeySelectionStrategy
= new Wildcard.SecRingSelectionStrategy<>();
@Test @Test
public void testStratAcceptsMatchingUIDsOnPubKey() throws IOException { public void testStratAcceptsMatchingUIDsOnPubKey() throws IOException {

View file

@ -18,8 +18,10 @@ import org.pgpainless.util.selection.keyring.impl.XMPP;
public class XmppKeyRingSelectionStrategyTest { public class XmppKeyRingSelectionStrategyTest {
XMPP.PubRingSelectionStrategy pubKeySelectionStrategy = new XMPP.PubRingSelectionStrategy(); private static final XMPP.PubRingSelectionStrategy pubKeySelectionStrategy =
XMPP.SecRingSelectionStrategy secKeySelectionStrategy = new XMPP.SecRingSelectionStrategy(); new XMPP.PubRingSelectionStrategy();
private static final XMPP.SecRingSelectionStrategy secKeySelectionStrategy =
new XMPP.SecRingSelectionStrategy();
@Test @Test
public void testMatchingXmppUIDAcceptedOnPubKey() throws IOException { public void testMatchingXmppUIDAcceptedOnPubKey() throws IOException {

View file

@ -6,7 +6,6 @@ package org.pgpainless.weird_keys;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -25,7 +24,8 @@ import org.pgpainless.key.util.KeyRingUtils;
public class TestEncryptCommsStorageFlagsDifferentiated { public class TestEncryptCommsStorageFlagsDifferentiated {
@Test @Test
public void testThatEncryptionDifferentiatesBetweenPurposeKeyFlags() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, IOException { public void testThatEncryptionDifferentiatesBetweenPurposeKeyFlags()
throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
PGPSecretKeyRing secretKeys = PGPainless.buildKeyRing() PGPSecretKeyRing secretKeys = PGPainless.buildKeyRing()
.setPrimaryKey(KeySpec.getBuilder( .setPrimaryKey(KeySpec.getBuilder(
KeyType.RSA(RsaLength._3072), KeyType.RSA(RsaLength._3072),

View file

@ -41,7 +41,7 @@ public class GenerateKeyImpl implements GenerateKey {
} }
@Override @Override
public Ready generate() throws SOPGPException.MissingArg, SOPGPException.UnsupportedAsymmetricAlgo, IOException { public Ready generate() throws SOPGPException.MissingArg, SOPGPException.UnsupportedAsymmetricAlgo {
Iterator<String> userIdIterator = userIds.iterator(); Iterator<String> userIdIterator = userIds.iterator();
if (!userIdIterator.hasNext()) { if (!userIdIterator.hasNext()) {
throw new SOPGPException.MissingArg("Missing user-id."); throw new SOPGPException.MissingArg("Missing user-id.");

View file

@ -25,7 +25,7 @@ import sop.operation.Verify;
public class VerifyImpl implements Verify { public class VerifyImpl implements Verify {
ConsumerOptions options = new ConsumerOptions(); private final ConsumerOptions options = new ConsumerOptions();
@Override @Override
public Verify notBefore(Date timestamp) throws SOPGPException.UnsupportedOption { public Verify notBefore(Date timestamp) throws SOPGPException.UnsupportedOption {

View file

@ -9,7 +9,7 @@ import picocli.CommandLine;
public class SOPExecutionExceptionHandler implements CommandLine.IExecutionExceptionHandler { public class SOPExecutionExceptionHandler implements CommandLine.IExecutionExceptionHandler {
@Override @Override
public int handleExecutionException(Exception ex, CommandLine commandLine, CommandLine.ParseResult parseResult) throws Exception { public int handleExecutionException(Exception ex, CommandLine commandLine, CommandLine.ParseResult parseResult) {
int exitCode = commandLine.getExitCodeExceptionMapper() != null ? int exitCode = commandLine.getExitCodeExceptionMapper() != null ?
commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getExitCodeExceptionMapper().getExitCode(ex) :
commandLine.getCommandSpec().exitCodeOnExecutionException(); commandLine.getCommandSpec().exitCodeOnExecutionException();

View file

@ -14,8 +14,8 @@ public class HexUtil {
* *
* @see <a href="https://stackoverflow.com/a/9855338"> * @see <a href="https://stackoverflow.com/a/9855338">
* How to convert a byte array to a hex string in Java?</a> * How to convert a byte array to a hex string in Java?</a>
* @param bytes * @param bytes bytes
* @return * @return hex encoding
*/ */
public static String bytesToHex(byte[] bytes) { public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2]; char[] hexChars = new char[bytes.length * 2];

View file

@ -13,7 +13,7 @@ import java.io.OutputStream;
* At that point, first all the buffered data is being written to the underlying stream, followed by any successive * At that point, first all the buffered data is being written to the underlying stream, followed by any successive
* data that may get written to the {@link ProxyOutputStream}. * data that may get written to the {@link ProxyOutputStream}.
* *
* This class is useful if we need to provide an {@link OutputStream} at one point in time where the final * This class is useful if we need to provide an {@link OutputStream} at one point in time when the final
* target output stream is not yet known. * target output stream is not yet known.
*/ */
public class ProxyOutputStream extends OutputStream { public class ProxyOutputStream extends OutputStream {

View file

@ -14,8 +14,8 @@ import java.util.TimeZone;
*/ */
public class UTCUtil { public class UTCUtil {
public static SimpleDateFormat UTC_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); public static final SimpleDateFormat UTC_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public static SimpleDateFormat[] UTC_PARSERS = new SimpleDateFormat[] { public static final SimpleDateFormat[] UTC_PARSERS = new SimpleDateFormat[] {
UTC_FORMATTER, UTC_FORMATTER,
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"),
new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"), new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"),
@ -38,6 +38,7 @@ public class UTCUtil {
try { try {
return parser.parse(dateString); return parser.parse(dateString);
} catch (ParseException e) { } catch (ParseException e) {
// Try next parser
} }
} }
return null; return null;

View file

@ -18,6 +18,7 @@ import org.junit.jupiter.api.Test;
*/ */
public class HexUtilTest { public class HexUtilTest {
@SuppressWarnings("CharsetObjectCanBeUsed")
private static final Charset ASCII = Charset.forName("US-ASCII"); private static final Charset ASCII = Charset.forName("US-ASCII");
@Test @Test