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) {

View File

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

View File

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

View File

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

View File

@ -11,7 +11,6 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
@ -120,7 +119,6 @@ public class PostponeDecryptionUsingKeyWithMissingPassphraseTest {
@Test
public void missingPassphraseFirst() throws PGPException, IOException {
SecretKeyRingProtector protector1 = new CachingSecretKeyRingProtector(new SecretKeyPassphraseProvider() {
@Nullable
@Override
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.");
@ -151,7 +149,6 @@ public class PostponeDecryptionUsingKeyWithMissingPassphraseTest {
public void missingPassphraseSecond() throws PGPException, IOException {
SecretKeyRingProtector protector1 = SecretKeyRingProtector.unlockEachKeyWith(p1, k1);
SecretKeyRingProtector protector2 = new CachingSecretKeyRingProtector(new SecretKeyPassphraseProvider() {
@Nullable
@Override
public Passphrase getPassphraseFor(Long keyId) {
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
public void messagePassphraseFirst() throws PGPException, IOException {
SecretKeyPassphraseProvider provider = new SecretKeyPassphraseProvider() {
@Nullable
@Override
public Passphrase getPassphraseFor(Long keyId) {
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 {
// 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 String testMessage =

View File

@ -16,16 +16,11 @@ import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.junit.jupiter.api.Test;
import org.pgpainless.PGPainless;
import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.util.KeyRingUtils;
public class ConvertKeys {
/**
* This example demonstrates how to extract a public key certificate from a secret key.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/
@Test
public void secretKeyToCertificate() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
@ -33,7 +28,7 @@ public class ConvertKeys {
PGPSecretKeyRing secretKey = PGPainless.generateKeyRing()
.modernKeyRing(userId, null);
// Extract certificate (public key) from secret key
PGPPublicKeyRing certificate = KeyRingUtils.publicKeyRingFrom(secretKey);
PGPPublicKeyRing certificate = PGPainless.extractCertificate(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 method can be combined with public key based encryption and signing.
*
* @throws PGPException
* @throws IOException
*/
@Test
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.rsa.RsaLength;
import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.util.KeyRingUtils;
import org.pgpainless.key.util.UserId;
import org.pgpainless.util.Passphrase;
@ -55,13 +54,10 @@ public class GenerateKeys {
* encryption subkey.
*
* This is the recommended way to generate OpenPGP keys with PGPainless.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/
@Test
public void generateModernEcKey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
public void generateModernEcKey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
// Define a primary user-id
String userId = "gbaker@pgpainless.org";
// Set a password to protect the secret key
@ -70,10 +66,10 @@ public class GenerateKeys {
PGPSecretKeyRing secretKey = PGPainless.generateKeyRing()
.modernKeyRing(userId, password);
// 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
String asciiArmoredPublicKey = PGPainless.asciiArmor(publicKey);
assertTrue(asciiArmoredPublicKey.startsWith("-----BEGIN PGP PUBLIC KEY BLOCK-----"));
KeyRingInfo keyInfo = new KeyRingInfo(secretKey);
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.
*
* This method is recommended if the application has to deal with legacy clients with poor algorithm support.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/
@Test
public void generateSimpleRSAKey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
public void generateSimpleRSAKey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
// Define a primary user-id
String userId = "mpage@pgpainless.org";
// Set a password to protect the secret key
@ -118,13 +111,10 @@ public class GenerateKeys {
* and a single ECDH encryption subkey.
*
* This method is recommended if small keys and high performance are desired.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/
@Test
public void generateSimpleECKey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
public void generateSimpleECKey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
// Define a primary user-id
String userId = "mhelms@pgpainless.org";
// Set a password to protect the secret key
@ -173,13 +163,10 @@ public class GenerateKeys {
* {@link org.pgpainless.key.generation.KeyRingBuilder#setExpirationDate(Date)}.
* Lastly you can decide whether to set a passphrase to protect the secret key using
* {@link org.pgpainless.key.generation.KeyRingBuilder#setPassphrase(Passphrase)}.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/
@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.
// The example below corresponds to "Morgan Carpenter (Pride!) <mcarpenter@pgpainless.org>"
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.
*
* @throws PGPException
*/
@Test
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.
* Only the passphrase of the targeted key will be changed. All other keys remain untouched.
*
* @throws PGPException
*/
@Test
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.
*
* @throws PGPException
*/
@Test
public void addUserId() throws PGPException {
@ -167,10 +161,6 @@ public class ModifyKeys {
* manually.
*
* Once the subkey is added, it can be decrypted using the provided subkey passphrase.
*
* @throws PGPException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
*/
@Test
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.
* The provided expiration date will be set on each user-id certification signature.
*
* @throws PGPException
*/
@Test
public void setKeyExpirationDate() throws PGPException {
@ -223,8 +211,6 @@ public class ModifyKeys {
/**
* This example demonstrates how to revoke a user-id on a key.
*
* @throws PGPException
*/
@Test
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.
*
* @throws IOException
*/
@Test
public void readCertificate() throws IOException {
@ -55,12 +53,9 @@ public class ReadKeys {
/**
* This example demonstrates how to parse an ASCII armored secret key.
*
* @throws PGPException
* @throws IOException
*/
@Test
public void readSecretKey() throws PGPException, IOException {
public void readSecretKey() throws IOException {
String key = "\n" +
"-----BEGIN PGP PRIVATE KEY BLOCK-----\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.
*
* 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.
*
* @throws PGPException
* @throws IOException
* and a single public key block containing multiple public key packets.
*/
@Test
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.
* The result is not human-readable, however the resulting text contains both the signed data and the signatures.
*
* @throws PGPException
* @throws IOException
*/
@Test
public void inbandSignedMessage() throws PGPException, IOException {
@ -75,9 +72,6 @@ public class Sign {
* A detached signature can be distributed alongside the message/file itself.
*
* The message/file doesn't need to be altered for detached signature creation.
*
* @throws PGPException
* @throws IOException
*/
@Test
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
* human-readable by utilizing the OpenPGP Cleartext Signature Framework.
* The resulting message contains the original (dash-escaped) message and the signatures.
*
* @throws PGPException
* @throws IOException
*/
@Test
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.
*
* @throws PGPException
* @throws IOException
*/
@Test
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
* all secret subkeys of a key.
*
* @throws PGPException
* @throws IOException
*/
@Test
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
* passphrases per subkey to unlock the secret keys.
*
* @throws PGPException
* @throws IOException
*/
@Test
public void unlockWithPerSubkeyPassphrases() throws PGPException, IOException {

View File

@ -6,7 +6,6 @@ package org.pgpainless.key;
import java.io.IOException;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.pgpainless.PGPainless;
@ -48,7 +47,7 @@ public class WeirdKeys {
"=BlPm\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);
}
@ -77,7 +76,7 @@ public class WeirdKeys {
"=h6sT\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);
}
}

View File

@ -34,6 +34,7 @@ import org.pgpainless.key.generation.type.xdh.XDHSpec;
import org.pgpainless.key.info.KeyRingInfo;
import org.pgpainless.key.protection.SecretKeyRingProtector;
import org.pgpainless.signature.subpackets.SelfSignatureSubpackets;
import org.pgpainless.util.Passphrase;
public class KeyGenerationSubpacketsTest {
@ -105,13 +106,15 @@ public class KeyGenerationSubpacketsTest {
}
@Test
public void verifyDefaultSubpacketsForSubkeyBindingSignatures() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
public void verifyDefaultSubpacketsForSubkeyBindingSignatures()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().modernKeyRing("Alice", null);
KeyRingInfo info = PGPainless.inspectKeyRing(secretKeys);
List<PGPPublicKey> keysBefore = info.getPublicKeys();
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();
@ -127,7 +130,8 @@ public class KeyGenerationSubpacketsTest {
assertNotNull(bindingSig.getHashedSubPackets().getEmbeddedSignatures().get(0));
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() {
@Override
public void modifyHashedSubpackets(SelfSignatureSubpackets hashedSubpackets) {

View File

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

View File

@ -16,7 +16,6 @@ import java.util.Iterator;
import java.util.List;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
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.SecretKeyRingProtector;
import org.pgpainless.key.protection.UnlockSecretKey;
import org.pgpainless.util.TestAllImplementations;
import org.pgpainless.util.Passphrase;
import org.pgpainless.util.TestAllImplementations;
public class AddSubKeyTest {
@ -67,7 +66,7 @@ public class AddSubKeyTest {
PGPSecretKey subKey = secretKeys.getSecretKey(subKeyId);
SecretKeyRingProtector protector = SecretKeyRingProtector.unlockEachKeyWith(
Passphrase.fromPassword("subKeyPassphrase"), secretKeys);
PGPPrivateKey privateKey = UnlockSecretKey.unlockSecretKey(subKey, protector);
UnlockSecretKey.unlockSecretKey(subKey, protector);
KeyRingInfo info = new KeyRingInfo(secretKeys);
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 static long MILLIS_IN_SEC = 1000;
public static final long MILLIS_IN_SEC = 1000;
@Test
public void bindEncryptionSubkeyAndModifyBindingSignatureHashedSubpackets() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {

View File

@ -131,7 +131,7 @@ public class ChangeSecretKeyRingPassphraseTest {
PGPSecretKey subKey = keys.next();
PGPSecretKeyRing secretKeys = PGPainless.modifyKeyRing(keyRing)
.changeSubKeyPassphraseFromOldPassphrase(primaryKey.getKeyID(), Passphrase.fromPassword("weakPassphrase"))
.changeSubKeyPassphraseFromOldPassphrase(subKey.getKeyID(), Passphrase.fromPassword("weakPassphrase"))
.withSecureDefaultSettings()
.toNoPassphrase()
.done();
@ -140,17 +140,17 @@ public class ChangeSecretKeyRingPassphraseTest {
primaryKey = keys.next();
subKey = keys.next();
extractPrivateKey(primaryKey, Passphrase.emptyPassphrase());
extractPrivateKey(subKey, Passphrase.fromPassword("weakPassphrase"));
extractPrivateKey(primaryKey, Passphrase.fromPassword("weakPassphrase"));
extractPrivateKey(subKey, Passphrase.emptyPassphrase());
final PGPSecretKey finalPrimaryKey = primaryKey;
assertThrows(PGPException.class,
() -> extractPrivateKey(finalPrimaryKey, Passphrase.fromPassword("weakPassphrase")),
() -> extractPrivateKey(finalPrimaryKey, Passphrase.emptyPassphrase()),
"Unlocking the unprotected primary key with the old passphrase must fail.");
final PGPSecretKey finalSubKey = subKey;
assertThrows(PGPException.class,
() -> extractPrivateKey(finalSubKey, Passphrase.emptyPassphrase()),
() -> extractPrivateKey(finalSubKey, Passphrase.fromPassword("weakPassphrase")),
"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 {
@Test
public void testEditorRefusesToAddWeakSubkey() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
public void testEditorRefusesToAddWeakSubkey()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException {
// ensure default policy is set
PGPainless.getPolicy().setPublicKeyAlgorithmPolicy(Policy.PublicKeyAlgorithmPolicy.defaultPublicKeyAlgorithmPolicy());
@ -45,7 +46,8 @@ public class RefuseToAddWeakSubkeyTest {
}
@Test
public void testEditorAllowsToAddWeakSubkeyIfCompliesToPublicKeyAlgorithmPolicy() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
public void testEditorAllowsToAddWeakSubkeyIfCompliesToPublicKeyAlgorithmPolicy()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing()
.modernKeyRing("Alice", null);

View File

@ -35,6 +35,7 @@ import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPUtil;
import org.junit.jupiter.api.Test;
import org.opentest4j.TestAbortedException;
import org.pgpainless.PGPainless;
import org.pgpainless.implementation.ImplementationFactory;
import org.pgpainless.key.OpenPgpV4Fingerprint;
@ -46,9 +47,17 @@ import org.pgpainless.util.TestUtils;
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
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));
@ -59,7 +68,7 @@ class KeyRingReaderTest {
@Test
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);
assertEquals(10, rings.size());
}
@ -247,7 +256,7 @@ class KeyRingReaderTest {
}
@Test
public void testReadSecretKeyIgnoresMarkerPacket() throws PGPException, IOException {
public void testReadSecretKeyIgnoresMarkerPacket() throws IOException {
String markerAndKey = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n" +
"Version: PGPainless\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.util.Iterator;
import java.util.Random;
import javax.annotation.Nullable;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyRing;
@ -32,7 +31,6 @@ public class CachingSecretKeyRingProtectorTest {
// Dummy passphrase callback that returns the doubled key-id as passphrase
private final SecretKeyPassphraseProvider dummyCallback = new SecretKeyPassphraseProvider() {
@Nullable
@Override
public Passphrase getPassphraseFor(Long keyId) {
long doubled = keyId * 2;

View File

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

View File

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

View File

@ -86,7 +86,7 @@ public class OnePassSignatureBracketingTest {
outerloop: while (true) {
Object next = objectFactory.nextObject();
if (next == null) {
break outerloop;
break;
}
if (next instanceof PGPEncryptedDataList) {
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.assertThrows;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
@ -59,13 +58,16 @@ public class ProofUtilTest {
}
@Test
public void testAddProof() throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IOException, InterruptedException {
public void testAddProof()
throws PGPException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InterruptedException {
String userId = "Alice <alice@pgpainless.org>";
PGPSecretKeyRing secretKey = PGPainless.generateKeyRing()
.modernKeyRing(userId, null);
Thread.sleep(1000L);
secretKey = new ProofUtil()
.addProof(secretKey, SecretKeyRingProtector.unprotectedKeys(), new ProofUtil.Proof("xmpp:alice@pgpainless.org"));
secretKey = new ProofUtil().addProof(
secretKey,
SecretKeyRingProtector.unprotectedKeys(),
new ProofUtil.Proof("xmpp:alice@pgpainless.org"));
KeyRingInfo info = PGPainless.inspectKeyRing(secretKey);
PGPSignature signature = info.getLatestUserIdCertification(userId);

View File

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

View File

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

View File

@ -18,8 +18,10 @@ import org.pgpainless.util.selection.keyring.impl.XMPP;
public class XmppKeyRingSelectionStrategyTest {
XMPP.PubRingSelectionStrategy pubKeySelectionStrategy = new XMPP.PubRingSelectionStrategy();
XMPP.SecRingSelectionStrategy secKeySelectionStrategy = new XMPP.SecRingSelectionStrategy();
private static final XMPP.PubRingSelectionStrategy pubKeySelectionStrategy =
new XMPP.PubRingSelectionStrategy();
private static final XMPP.SecRingSelectionStrategy secKeySelectionStrategy =
new XMPP.SecRingSelectionStrategy();
@Test
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 java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
@ -25,7 +24,8 @@ import org.pgpainless.key.util.KeyRingUtils;
public class TestEncryptCommsStorageFlagsDifferentiated {
@Test
public void testThatEncryptionDifferentiatesBetweenPurposeKeyFlags() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException, IOException {
public void testThatEncryptionDifferentiatesBetweenPurposeKeyFlags()
throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, PGPException {
PGPSecretKeyRing secretKeys = PGPainless.buildKeyRing()
.setPrimaryKey(KeySpec.getBuilder(
KeyType.RSA(RsaLength._3072),

View File

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

View File

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

View File

@ -9,7 +9,7 @@ import picocli.CommandLine;
public class SOPExecutionExceptionHandler implements CommandLine.IExecutionExceptionHandler {
@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 ?
commandLine.getExitCodeExceptionMapper().getExitCode(ex) :
commandLine.getCommandSpec().exitCodeOnExecutionException();

View File

@ -14,8 +14,8 @@ public class HexUtil {
*
* @see <a href="https://stackoverflow.com/a/9855338">
* How to convert a byte array to a hex string in Java?</a>
* @param bytes
* @return
* @param bytes bytes
* @return hex encoding
*/
public static String bytesToHex(byte[] bytes) {
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
* 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.
*/
public class ProxyOutputStream extends OutputStream {

View File

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

View File

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