From 0e61f29b84a30a5fbae441b578bd962a7759a0e6 Mon Sep 17 00:00:00 2001 From: aboruch Date: Tue, 31 Oct 2017 12:55:05 +0100 Subject: [PATCH 1/4] Replace J-U-L with slf4j --- build.gradle | 2 + src/main/java/org/c02e/jpgpj/Decryptor.java | 44 +++++++++--------- src/main/java/org/c02e/jpgpj/Encryptor.java | 46 +++++++++---------- .../org/c02e/jpgpj/DecryptorSpec.groovy | 7 +-- .../org/c02e/jpgpj/EncryptorSpec.groovy | 8 +--- 5 files changed, 50 insertions(+), 57 deletions(-) diff --git a/build.gradle b/build.gradle index 0c34d96..76e7fa5 100644 --- a/build.gradle +++ b/build.gradle @@ -17,6 +17,8 @@ dependencies { compile 'org.bouncycastle:bcpg-jdk15on:1.58' testCompile 'org.codehaus.groovy:groovy-all:2.4.7' testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' + compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.6' + } javadoc { diff --git a/src/main/java/org/c02e/jpgpj/Decryptor.java b/src/main/java/org/c02e/jpgpj/Decryptor.java index e93594a..de84f91 100644 --- a/src/main/java/org/c02e/jpgpj/Decryptor.java +++ b/src/main/java/org/c02e/jpgpj/Decryptor.java @@ -12,8 +12,8 @@ import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; -import java.util.logging.Level; -import java.util.logging.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.openpgp.PGPCompressedData; import org.bouncycastle.openpgp.PGPDataValidationException; @@ -71,7 +71,8 @@ public class Decryptor { protected boolean verificationRequired; protected String symmetricPassphrase; protected Ring ring; - protected Logger log = Logger.getLogger(Decryptor.class.getName()); + protected Logger log = LoggerFactory.getLogger(Decryptor.class.getName()); + /** Constructs a decryptor with an empty key ring. */ public Decryptor() { @@ -173,8 +174,7 @@ public FileMetadata decrypt(File ciphertext, File plaintext) output.close(); plaintext.delete(); } catch (Exception ee) { - log.log(Level.SEVERE, "failed to delete bad output file " - + plaintext, ee); + log.error("failed to delete bad output file {}", plaintext, ee); } throw e; } finally { @@ -229,8 +229,8 @@ protected List unpack(Iterator packets, while (packets.hasNext()) { Object packet = packets.next(); - if (log.isLoggable(Level.FINEST)) - log.finest("unpack " + packet.getClass()); + if (log.isTraceEnabled()) + log.trace("unpack {} ", packet.getClass()); if (packet instanceof PGPMarker) { // no-op @@ -273,7 +273,7 @@ protected List unpack(Iterator packets, throw new PGPException("unexpected packet: " + packet.getClass()); } } - log.finest("unpacked all"); + log.trace("unpacked all"); // fail if verification required and any signature is bad verify(verifiers, meta); @@ -337,12 +337,12 @@ protected InputStream decrypt(Iterator data) !Util.isEmpty(subkey.passphrase)) return decrypt(pke, subkey); - else if (log.isLoggable(Level.INFO)) - log.info("not using decryption key " + subkey); + else if (log.isInfoEnabled()) + log.info("not using decryption key {} ", subkey); } else { - if (log.isLoggable(Level.INFO)) - log.info("not found decryption key " + + if (log.isInfoEnabled()) + log.info("not found decryption key {} ", Util.formatKeyId(pke.getKeyID())); } @@ -364,8 +364,8 @@ protected InputStream decrypt(PGPPublicKeyEncryptedData data, Subkey subkey) if (data == null || subkey == null) throw new DecryptionException("no suitable decryption key found"); - if (log.isLoggable(Level.INFO)) - log.info("using decryption key " + subkey); + if (log.isInfoEnabled()) + log.info("using decryption key {} ", subkey); return data.getDataStream(buildPublicKeyDecryptor(subkey)); } @@ -431,8 +431,8 @@ protected void verify(List verifiers, List meta) if (!verifier.verify()) throw new VerificationException( "bad signature for key " + verifier.key); - else if (log.isLoggable(Level.FINE)) - log.fine("good signature for key " + verifier.key); + else if (log.isDebugEnabled()) + log.debug("good signature for key {} ", verifier.key); Key key = verifier.getSignedBy(); for (FileMetadata file : meta) @@ -549,8 +549,8 @@ public void setSig(PGPSignature s) throws PGPException { key = getRing().findById(s.getKeyID()); if (key == null) { - if (Decryptor.this.log.isLoggable(Level.INFO)) - Decryptor.this.log.info("not found verification key " + + if (Decryptor.this.log.isInfoEnabled()) + Decryptor.this.log.info("not found verification key {} ", Util.formatKeyId(s.getKeyID())); return; } @@ -561,7 +561,7 @@ public void setSig(PGPSignature s) throws PGPException { else s.init(getVerifierProvider(), subkey.getPublicKey()); - if (Decryptor.this.log.isLoggable(Level.INFO)) + if (Decryptor.this.log.isInfoEnabled()) Decryptor.this.log.info((key == null ? "not " : "") + "using verification key " + subkey); } @@ -571,8 +571,8 @@ public void setSig1(PGPOnePassSignature s) throws PGPException { key = getRing().findById(s.getKeyID()); if (key == null) { - if (Decryptor.this.log.isLoggable(Level.INFO)) - Decryptor.this.log.info("not found verification key " + + if (Decryptor.this.log.isInfoEnabled()) + Decryptor.this.log.info("not found verification key {}", Util.formatKeyId(s.getKeyID())); return; } @@ -583,7 +583,7 @@ public void setSig1(PGPOnePassSignature s) throws PGPException { else s.init(getVerifierProvider(), subkey.getPublicKey()); - if (Decryptor.this.log.isLoggable(Level.INFO)) + if (Decryptor.this.log.isInfoEnabled()) Decryptor.this.log.info((key == null ? "not " : "") + "using verification key " + subkey); } diff --git a/src/main/java/org/c02e/jpgpj/Encryptor.java b/src/main/java/org/c02e/jpgpj/Encryptor.java index be72e0c..c6b5258 100644 --- a/src/main/java/org/c02e/jpgpj/Encryptor.java +++ b/src/main/java/org/c02e/jpgpj/Encryptor.java @@ -12,8 +12,8 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.bcpg.BCPGOutputStream; import org.bouncycastle.openpgp.PGPCompressedDataGenerator; @@ -80,7 +80,7 @@ public class Encryptor { protected int keyDerivationWorkFactor; protected Ring ring; - protected Logger log = Logger.getLogger(Encryptor.class.getName()); + protected Logger log = LoggerFactory.getLogger(Encryptor.class.getName()); /** Constructs an encryptor with an empty key ring. */ public Encryptor() { @@ -278,8 +278,8 @@ public void encrypt(File plaintext, File ciphertext) output.close(); ciphertext.delete(); } catch (Exception ee) { - log.log(Level.SEVERE, "failed to delete bad output file " - + plaintext, ee); + log.error("failed to delete bad output file {} ", + plaintext, ee); } throw e; } finally { @@ -379,8 +379,8 @@ protected OutputStream armor(OutputStream out) { */ protected OutputStream encrypt(OutputStream out, FileMetadata meta) throws IOException, PGPException { - if (log.isLoggable(Level.FINEST)) - log.finest("using encryption algorithm " + encryptionAlgorithm); + if (log.isTraceEnabled()) + log.trace("using encryption algorithm {} ", encryptionAlgorithm); if (encryptionAlgorithm == EncryptionAlgorithm.Unencrypted) return null; @@ -404,9 +404,8 @@ protected OutputStream encrypt(OutputStream out, FileMetadata meta) */ protected OutputStream compress(OutputStream out, FileMetadata meta) throws IOException, PGPException { - if (log.isLoggable(Level.FINEST)) - log.finest("using compression algorithm " + compressionAlgorithm + - " -" + compressionLevel); + if (log.isTraceEnabled()) + log.trace("using compression algorithm {} - {} ", compressionAlgorithm, compressionLevel); if (compressionAlgorithm == CompressionAlgorithm.Uncompressed || compressionLevel < 1 || compressionLevel > 9) @@ -436,8 +435,8 @@ protected OutputStream packet(OutputStream out, FileMetadata meta) */ protected SigningOutputStream sign(OutputStream out, FileMetadata meta) throws IOException, PGPException { - if (log.isLoggable(Level.FINEST)) - log.finest("using signing algorithm " + signingAlgorithm); + if (log.isTraceEnabled()) + log.trace("using signing algorithm {} ", signingAlgorithm); if (signingAlgorithm == HashingAlgorithm.Unsigned) return null; @@ -447,8 +446,8 @@ protected SigningOutputStream sign(OutputStream out, FileMetadata meta) for (int i = signers.size() - 1; i >= 0; i--) { Subkey subkey = signers.get(i).getSigning(); if (subkey == null || Util.isEmpty(subkey.passphrase)) { - if (log.isLoggable(Level.INFO)) - log.info("not using signing key " + subkey); + if (log.isInfoEnabled()) + log.info("not using signing key {}",subkey); signers.remove(i); } } @@ -492,8 +491,8 @@ protected PGPEncryptedDataGenerator buildEncryptor() { */ protected PublicKeyKeyEncryptionMethodGenerator buildPublicKeyEncryptor( Key key) { - if (log.isLoggable(Level.INFO)) - log.info("using encryption key " + key.getEncryption()); + if (log.isInfoEnabled()) + log.info("using encryption key {}", key.getEncryption()); PGPPublicKey publicKey = key.getEncryption().getPublicKey(); return new BcPublicKeyKeyEncryptionMethodGenerator(publicKey); @@ -505,10 +504,9 @@ protected PublicKeyKeyEncryptionMethodGenerator buildPublicKeyEncryptor( */ protected PBEKeyEncryptionMethodGenerator buildSymmetricKeyEncryptor() throws PGPException { - if (log.isLoggable(Level.INFO)) - log.info("using symmetric encryption with " + - keyDerivationAlgorithm + " hash, work factor " + - keyDerivationWorkFactor); + if (log.isInfoEnabled()) + log.info("using symmetric encryption with {} hash, work factor {} ", + keyDerivationAlgorithm, keyDerivationWorkFactor); int algo = keyDerivationAlgorithm.ordinal(); return new BcPBEKeyEncryptionMethodGenerator( @@ -524,8 +522,8 @@ protected PGPSignatureGenerator buildSigner(Key key, FileMetadata meta) throws PGPException { Subkey subkey = key.getSigning(); - if (log.isLoggable(Level.INFO)) - log.info("using signing key " + subkey); + if (log.isInfoEnabled()) + log.info("using signing key {} ", subkey); PGPContentSignerBuilder builder = buildSignerBuilder( subkey.getPublicKey().getAlgorithm(), @@ -537,8 +535,8 @@ protected PGPSignatureGenerator buildSigner(Key key, FileMetadata meta) String uid = key.getSigningUid(); if (!Util.isEmpty(uid)) { - if (log.isLoggable(Level.FINE)) - log.fine("using signing uid " + uid); + if (log.isDebugEnabled()) + log.debug("using signing uid {}", uid); PGPSignatureSubpacketGenerator signer = new PGPSignatureSubpacketGenerator(); diff --git a/src/test/groovy/org/c02e/jpgpj/DecryptorSpec.groovy b/src/test/groovy/org/c02e/jpgpj/DecryptorSpec.groovy index 601fc3b..3d0de3b 100644 --- a/src/test/groovy/org/c02e/jpgpj/DecryptorSpec.groovy +++ b/src/test/groovy/org/c02e/jpgpj/DecryptorSpec.groovy @@ -1,16 +1,13 @@ package org.c02e.jpgpj import java.text.SimpleDateFormat -import java.util.logging.Level -import java.util.logging.Logger import spock.lang.Specification class DecryptorSpec extends Specification { /* - static { - Logger.getLogger('').handlers*.level = Level.FINEST - Logger.getLogger('org.c02e.jpgpj.Decryptor').level = Level.FINEST + static{ + System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE"); } */ diff --git a/src/test/groovy/org/c02e/jpgpj/EncryptorSpec.groovy b/src/test/groovy/org/c02e/jpgpj/EncryptorSpec.groovy index d3b4921..59f938b 100644 --- a/src/test/groovy/org/c02e/jpgpj/EncryptorSpec.groovy +++ b/src/test/groovy/org/c02e/jpgpj/EncryptorSpec.groovy @@ -1,17 +1,13 @@ package org.c02e.jpgpj -import java.util.logging.Level -import java.util.logging.Logger import org.bouncycastle.openpgp.PGPException import spock.lang.Specification class EncryptorSpec extends Specification { /* - static { - Logger.getLogger('').handlers*.level = Level.FINEST - Logger.getLogger('org.c02e.jpgpj.Decryptor').level = Level.FINEST - Logger.getLogger('org.c02e.jpgpj.Encryptor').level = Level.FINEST + static{ + System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE"); } */ From 5ce36b63a51c2c120bd8b3ca865123545a858d26 Mon Sep 17 00:00:00 2001 From: aboruch Date: Sun, 12 Nov 2017 18:17:39 +0100 Subject: [PATCH 2/4] Removed checking level of logger --- src/main/java/org/c02e/jpgpj/Decryptor.java | 163 +++++++++++--------- src/main/java/org/c02e/jpgpj/Encryptor.java | 24 +-- 2 files changed, 99 insertions(+), 88 deletions(-) diff --git a/src/main/java/org/c02e/jpgpj/Decryptor.java b/src/main/java/org/c02e/jpgpj/Decryptor.java index de84f91..1321847 100644 --- a/src/main/java/org/c02e/jpgpj/Decryptor.java +++ b/src/main/java/org/c02e/jpgpj/Decryptor.java @@ -74,19 +74,25 @@ public class Decryptor { protected Logger log = LoggerFactory.getLogger(Decryptor.class.getName()); - /** Constructs a decryptor with an empty key ring. */ + /** + * Constructs a decryptor with an empty key ring. + */ public Decryptor() { this(new Ring()); } - /** Constructs a decryptor with the specified key ring. */ + /** + * Constructs a decryptor with the specified key ring. + */ public Decryptor(Ring ring) { verificationRequired = true; symmetricPassphrase = ""; setRing(ring); } - /** Constructs a decryptor with the specified keys. */ + /** + * Constructs a decryptor with the specified keys. + */ public Decryptor(Key... keys) { this(new Ring(keys)); } @@ -107,22 +113,30 @@ public void setVerificationRequired(boolean x) { verificationRequired = x; } - /** Passphrase to use to decrypt with a symmetric key. */ + /** + * Passphrase to use to decrypt with a symmetric key. + */ public String getSymmetricPassphrase() { return symmetricPassphrase; } - /** Passphrase to use to decrypt with a symmetric key. */ + /** + * Passphrase to use to decrypt with a symmetric key. + */ public void setSymmetricPassphrase(String x) { symmetricPassphrase = x != null ? x : ""; } - /** Keys to use for decryption and verification. */ + /** + * Keys to use for decryption and verification. + */ public Ring getRing() { return ring; } - /** Keys to use for decryption and verification. */ + /** + * Keys to use for decryption and verification. + */ protected void setRing(Ring x) { ring = x != null ? x : new Ring(); } @@ -133,28 +147,29 @@ protected void setRing(Ring x) { * verifies its signatures. If a file already exists in the output file's * location, it will be deleted. If an exception occurs during decryption, * the output file will be deleted. + * * @param ciphertext File containing a PGP message, in binary or - * ASCII Armor format. - * @param plaintext Location of the file into which to decrypt the message. + * ASCII Armor format. + * @param plaintext Location of the file into which to decrypt the message. * @return Metadata of original file, and the list of keys that signed * the message with a verified signature. The original file metadata * values are optional, and may be missing or incorrect. - * @throws IOException if an IO error occurs reading from or writing to - * the underlying input or output streams. - * @throws PGPException if the PGP message is not formatted correctly. - * @throws PassphraseException if an incorrect passphrase was supplied - * for one of the decryption keys, or as the - * {@link #getSymmetricPassphrase()}. - * @throws DecryptionException if the message was not encrypted for any - * of the keys supplied for decryption. + * @throws IOException if an IO error occurs reading from or writing to + * the underlying input or output streams. + * @throws PGPException if the PGP message is not formatted correctly. + * @throws PassphraseException if an incorrect passphrase was supplied + * for one of the decryption keys, or as the + * {@link #getSymmetricPassphrase()}. + * @throws DecryptionException if the message was not encrypted for any + * of the keys supplied for decryption. * @throws VerificationException if {@link #isVerificationRequired} and - * the message was not signed by any of the keys supplied for verification. + * the message was not signed by any of the keys supplied for verification. */ public FileMetadata decrypt(File ciphertext, File plaintext) - throws IOException, PGPException { + throws IOException, PGPException { if (ciphertext.equals(plaintext)) throw new IOException("cannot decrypt " + ciphertext + - " over itself"); + " over itself"); // delete old output file plaintext.delete(); @@ -163,9 +178,9 @@ public FileMetadata decrypt(File ciphertext, File plaintext) OutputStream output = null; try { input = new BufferedInputStream( - new FileInputStream(ciphertext), 0x1000); + new FileInputStream(ciphertext), 0x1000); output = new BufferedOutputStream( - new FileOutputStream(plaintext), 0x1000); + new FileOutputStream(plaintext), 0x1000); return decrypt(input, output); } catch (Exception e) { // delete output file if anything went wrong @@ -178,8 +193,14 @@ public FileMetadata decrypt(File ciphertext, File plaintext) } throw e; } finally { - try { output.close(); } catch (Exception e) {} - try { input.close(); } catch (Exception e) {} + try { + output.close(); + } catch (Exception e) { + } + try { + input.close(); + } catch (Exception e) { + } } } @@ -191,24 +212,25 @@ public FileMetadata decrypt(File ciphertext, File plaintext) * Note that the full decrypted content will be written to the output stream * before the message is verified, so you may want to buffer the content * and not write it to its final destination until this method returns. + * * @param ciphertext PGP message, in binary or ASCII Armor format. - * @param plaintext Decrypted content. + * @param plaintext Decrypted content. * @return Metadata of original file, and the list of keys that signed * the message with a verified signature. The original file metadata * values are optional, and may be missing or incorrect. - * @throws IOException if an IO error occurs reading from or writing to - * the underlying input or output streams. - * @throws PGPException if the PGP message is not formatted correctly. - * @throws PassphraseException if an incorrect passphrase was supplied - * for one of the decryption keys, or as the - * {@link #getSymmetricPassphrase()}. - * @throws DecryptionException if the message was not encrypted for any - * of the keys supplied for decryption. + * @throws IOException if an IO error occurs reading from or writing to + * the underlying input or output streams. + * @throws PGPException if the PGP message is not formatted correctly. + * @throws PassphraseException if an incorrect passphrase was supplied + * for one of the decryption keys, or as the + * {@link #getSymmetricPassphrase()}. + * @throws DecryptionException if the message was not encrypted for any + * of the keys supplied for decryption. * @throws VerificationException if {@link #isVerificationRequired} and - * the message was not signed by any of the keys supplied for verification. + * the message was not signed by any of the keys supplied for verification. */ public FileMetadata decrypt(InputStream ciphertext, OutputStream plaintext) - throws IOException, PGPException { + throws IOException, PGPException { List meta = unpack(parse(unarmor(ciphertext)), plaintext); if (meta.size() > 1) throw new PGPException("content contained more than one file"); @@ -222,15 +244,14 @@ public FileMetadata decrypt(InputStream ciphertext, OutputStream plaintext) * writing the decrypted message content into the output stream. */ protected List unpack(Iterator packets, - OutputStream plaintext) throws IOException, PGPException { + OutputStream plaintext) throws IOException, PGPException { List meta = new ArrayList(); List verifiers = new ArrayList(); while (packets.hasNext()) { Object packet = packets.next(); - if (log.isTraceEnabled()) - log.trace("unpack {} ", packet.getClass()); + log.trace("unpack {} ", packet.getClass()); if (packet instanceof PGPMarker) { // no-op @@ -245,8 +266,8 @@ protected List unpack(Iterator packets, // when in message header, initialize verifiers for these sigs if (Util.isEmpty(verifiers)) verifiers = buildVerifiers(list.iterator()); - // when in message trailer, match sigs to one-pass sigs - // in already initialized verifiers + // when in message trailer, match sigs to one-pass sigs + // in already initialized verifiers else matchSignatures(list.iterator(), verifiers); @@ -285,7 +306,7 @@ protected List unpack(Iterator packets, * for which a verification key is available. */ protected List buildVerifiers(Iterator signatures) - throws PGPException { + throws PGPException { ArrayList verifiers = new ArrayList(); while (signatures.hasNext()) { Verifier verifier = null; @@ -306,7 +327,7 @@ else if (signature instanceof PGPOnePassSignature) * Matches the specified trailing signatures to the specified verifiers. */ protected void matchSignatures(Iterator signatures, - List verifiers) { + List verifiers) { while (signatures.hasNext()) { PGPSignature signature = signatures.next(); @@ -319,7 +340,7 @@ protected void matchSignatures(Iterator signatures, * Decrypts the encrypted data as the returned input stream. */ protected InputStream decrypt(Iterator data) - throws IOException, PGPException { + throws IOException, PGPException { PGPPBEEncryptedData pbe = null; while (data.hasNext()) { @@ -337,12 +358,10 @@ protected InputStream decrypt(Iterator data) !Util.isEmpty(subkey.passphrase)) return decrypt(pke, subkey); - else if (log.isInfoEnabled()) - log.info("not using decryption key {} ", subkey); + log.info("not using decryption key {} ", subkey); } else { - if (log.isInfoEnabled()) - log.info("not found decryption key {} ", + log.info("not found decryption key {} ", Util.formatKeyId(pke.getKeyID())); } @@ -360,12 +379,12 @@ else if (log.isInfoEnabled()) * Decrypts the encrypted data as the returned input stream. */ protected InputStream decrypt(PGPPublicKeyEncryptedData data, Subkey subkey) - throws IOException, PGPException { + throws IOException, PGPException { if (data == null || subkey == null) throw new DecryptionException("no suitable decryption key found"); - if (log.isInfoEnabled()) - log.info("using decryption key {} ", subkey); + log.info("using decryption key {} ", subkey); + return data.getDataStream(buildPublicKeyDecryptor(subkey)); } @@ -373,16 +392,16 @@ protected InputStream decrypt(PGPPublicKeyEncryptedData data, Subkey subkey) * Decrypts the encrypted data as the returned input stream. */ protected InputStream decrypt(PGPPBEEncryptedData data) - throws IOException, PGPException { + throws IOException, PGPException { if (data == null || Util.isEmpty(symmetricPassphrase)) throw new DecryptionException("no suitable decryption key found"); try { return data.getDataStream(buildSymmetricKeyDecryptor( - symmetricPassphrase)); + symmetricPassphrase)); } catch (PGPDataValidationException e) { throw new PassphraseException( - "incorrect passphrase for symmetric key", e); + "incorrect passphrase for symmetric key", e); } } @@ -392,14 +411,14 @@ protected InputStream decrypt(PGPPBEEncryptedData data) * with the specified list of verifiers (if verification required). */ protected long copy(InputStream i, OutputStream o, - List verifiers) throws IOException, PGPException { + List verifiers) throws IOException, PGPException { long total = 0; byte[] buf = getCopyBuffer(); int len = i.read(buf); if (verificationRequired && Util.isEmpty(verifiers)) throw new VerificationException( - "content not signed with a required key"); + "content not signed with a required key"); while (len != -1) { total += len; @@ -424,14 +443,14 @@ protected long copy(InputStream i, OutputStream o, * with verified signatures to the file metadata. */ protected void verify(List verifiers, List meta) - throws PGPException { + throws PGPException { if (!verificationRequired) return; for (Verifier verifier : verifiers) { if (!verifier.verify()) throw new VerificationException( - "bad signature for key " + verifier.key); - else if (log.isDebugEnabled()) + "bad signature for key " + verifier.key); + else log.debug("good signature for key {} ", verifier.key); Key key = verifier.getSignedBy(); @@ -445,16 +464,17 @@ else if (log.isDebugEnabled()) * (to convert ascii-armored content back into binary data). */ protected InputStream unarmor(InputStream stream) - throws IOException, PGPException { + throws IOException, PGPException { return PGPUtil.getDecoderStream(stream); } /** * Separates stream into PGP packets. + * * @see PGPObjectFactory */ protected Iterator parse(InputStream stream) - throws IOException, PGPException { + throws IOException, PGPException { // before BCPG v1.55 // PGPObjectFactory.iterator() doesn't work for decryption // because its next() method prematurely calls nextObject() @@ -466,6 +486,7 @@ protected Iterator parse(InputStream stream) return new Iterator() { boolean checkedNext = false; Object nextElement = null; + public boolean hasNext() { if (!checkedNext) { checkedNext = true; @@ -477,11 +498,13 @@ public boolean hasNext() { } return nextElement != null; } + public Object next() { if (!hasNext()) throw new NoSuchElementException(); checkedNext = false; return nextElement; } + public void remove() { throw new UnsupportedOperationException(); } @@ -499,7 +522,7 @@ protected PGPContentVerifierBuilderProvider getVerifierProvider() { * Builds a symmetric-encryption decryptor for the specified passphrase. */ protected PublicKeyDataDecryptorFactory buildPublicKeyDecryptor( - Subkey subkey) throws PGPException { + Subkey subkey) throws PGPException { PGPPrivateKey privateKey = subkey.getPrivateKey(); if (privateKey == null) throw new PGPException("no private key for " + subkey); @@ -510,11 +533,11 @@ protected PublicKeyDataDecryptorFactory buildPublicKeyDecryptor( * Builds a symmetric-key decryptor for the specified passphrase. */ protected PBEDataDecryptorFactory buildSymmetricKeyDecryptor( - String passphrase) { + String passphrase) { char[] chars = !Util.isEmpty(passphrase) ? - passphrase.toCharArray() : new char[0]; + passphrase.toCharArray() : new char[0]; return new BcPBEDataDecryptorFactory(chars, - new BcPGPDigestCalculatorProvider()); + new BcPGPDigestCalculatorProvider()); } protected byte[] getCopyBuffer() { @@ -549,8 +572,7 @@ public void setSig(PGPSignature s) throws PGPException { key = getRing().findById(s.getKeyID()); if (key == null) { - if (Decryptor.this.log.isInfoEnabled()) - Decryptor.this.log.info("not found verification key {} ", + Decryptor.this.log.info("not found verification key {} ", Util.formatKeyId(s.getKeyID())); return; } @@ -561,8 +583,7 @@ public void setSig(PGPSignature s) throws PGPException { else s.init(getVerifierProvider(), subkey.getPublicKey()); - if (Decryptor.this.log.isInfoEnabled()) - Decryptor.this.log.info((key == null ? "not " : "") + + Decryptor.this.log.info((key == null ? "not " : "") + "using verification key " + subkey); } @@ -571,8 +592,7 @@ public void setSig1(PGPOnePassSignature s) throws PGPException { key = getRing().findById(s.getKeyID()); if (key == null) { - if (Decryptor.this.log.isInfoEnabled()) - Decryptor.this.log.info("not found verification key {}", + Decryptor.this.log.info("not found verification key {}", Util.formatKeyId(s.getKeyID())); return; } @@ -583,8 +603,7 @@ public void setSig1(PGPOnePassSignature s) throws PGPException { else s.init(getVerifierProvider(), subkey.getPublicKey()); - if (Decryptor.this.log.isInfoEnabled()) - Decryptor.this.log.info((key == null ? "not " : "") + + Decryptor.this.log.info((key == null ? "not " : "") + "using verification key " + subkey); } diff --git a/src/main/java/org/c02e/jpgpj/Encryptor.java b/src/main/java/org/c02e/jpgpj/Encryptor.java index c6b5258..5cc5b28 100644 --- a/src/main/java/org/c02e/jpgpj/Encryptor.java +++ b/src/main/java/org/c02e/jpgpj/Encryptor.java @@ -379,8 +379,7 @@ protected OutputStream armor(OutputStream out) { */ protected OutputStream encrypt(OutputStream out, FileMetadata meta) throws IOException, PGPException { - if (log.isTraceEnabled()) - log.trace("using encryption algorithm {} ", encryptionAlgorithm); + log.trace("using encryption algorithm {} ", encryptionAlgorithm); if (encryptionAlgorithm == EncryptionAlgorithm.Unencrypted) return null; @@ -404,8 +403,7 @@ protected OutputStream encrypt(OutputStream out, FileMetadata meta) */ protected OutputStream compress(OutputStream out, FileMetadata meta) throws IOException, PGPException { - if (log.isTraceEnabled()) - log.trace("using compression algorithm {} - {} ", compressionAlgorithm, compressionLevel); + log.trace("using compression algorithm {} - {} ", compressionAlgorithm, compressionLevel); if (compressionAlgorithm == CompressionAlgorithm.Uncompressed || compressionLevel < 1 || compressionLevel > 9) @@ -435,8 +433,7 @@ protected OutputStream packet(OutputStream out, FileMetadata meta) */ protected SigningOutputStream sign(OutputStream out, FileMetadata meta) throws IOException, PGPException { - if (log.isTraceEnabled()) - log.trace("using signing algorithm {} ", signingAlgorithm); + log.trace("using signing algorithm {} ", signingAlgorithm); if (signingAlgorithm == HashingAlgorithm.Unsigned) return null; @@ -446,8 +443,7 @@ protected SigningOutputStream sign(OutputStream out, FileMetadata meta) for (int i = signers.size() - 1; i >= 0; i--) { Subkey subkey = signers.get(i).getSigning(); if (subkey == null || Util.isEmpty(subkey.passphrase)) { - if (log.isInfoEnabled()) - log.info("not using signing key {}",subkey); + log.info("not using signing key {}",subkey); signers.remove(i); } } @@ -491,8 +487,7 @@ protected PGPEncryptedDataGenerator buildEncryptor() { */ protected PublicKeyKeyEncryptionMethodGenerator buildPublicKeyEncryptor( Key key) { - if (log.isInfoEnabled()) - log.info("using encryption key {}", key.getEncryption()); + log.info("using encryption key {}", key.getEncryption()); PGPPublicKey publicKey = key.getEncryption().getPublicKey(); return new BcPublicKeyKeyEncryptionMethodGenerator(publicKey); @@ -504,8 +499,7 @@ protected PublicKeyKeyEncryptionMethodGenerator buildPublicKeyEncryptor( */ protected PBEKeyEncryptionMethodGenerator buildSymmetricKeyEncryptor() throws PGPException { - if (log.isInfoEnabled()) - log.info("using symmetric encryption with {} hash, work factor {} ", + log.info("using symmetric encryption with {} hash, work factor {} ", keyDerivationAlgorithm, keyDerivationWorkFactor); int algo = keyDerivationAlgorithm.ordinal(); @@ -522,8 +516,7 @@ protected PGPSignatureGenerator buildSigner(Key key, FileMetadata meta) throws PGPException { Subkey subkey = key.getSigning(); - if (log.isInfoEnabled()) - log.info("using signing key {} ", subkey); + log.info("using signing key {} ", subkey); PGPContentSignerBuilder builder = buildSignerBuilder( subkey.getPublicKey().getAlgorithm(), @@ -535,8 +528,7 @@ protected PGPSignatureGenerator buildSigner(Key key, FileMetadata meta) String uid = key.getSigningUid(); if (!Util.isEmpty(uid)) { - if (log.isDebugEnabled()) - log.debug("using signing uid {}", uid); + log.debug("using signing uid {}", uid); PGPSignatureSubpacketGenerator signer = new PGPSignatureSubpacketGenerator(); From e8031bfe76d82a6f27b65cda659f8de3fa4f2c2d Mon Sep 17 00:00:00 2001 From: aboruch Date: Sun, 12 Nov 2017 19:02:17 +0100 Subject: [PATCH 3/4] Restore original format code in Decryptor.class --- src/main/java/org/c02e/jpgpj/Decryptor.java | 140 ++++++++------------ 1 file changed, 58 insertions(+), 82 deletions(-) diff --git a/src/main/java/org/c02e/jpgpj/Decryptor.java b/src/main/java/org/c02e/jpgpj/Decryptor.java index 1321847..7ac3bc2 100644 --- a/src/main/java/org/c02e/jpgpj/Decryptor.java +++ b/src/main/java/org/c02e/jpgpj/Decryptor.java @@ -74,25 +74,19 @@ public class Decryptor { protected Logger log = LoggerFactory.getLogger(Decryptor.class.getName()); - /** - * Constructs a decryptor with an empty key ring. - */ + /** Constructs a decryptor with an empty key ring. */ public Decryptor() { this(new Ring()); } - /** - * Constructs a decryptor with the specified key ring. - */ + /** Constructs a decryptor with the specified key ring. */ public Decryptor(Ring ring) { verificationRequired = true; symmetricPassphrase = ""; setRing(ring); } - /** - * Constructs a decryptor with the specified keys. - */ + /** Constructs a decryptor with the specified keys. */ public Decryptor(Key... keys) { this(new Ring(keys)); } @@ -113,30 +107,22 @@ public void setVerificationRequired(boolean x) { verificationRequired = x; } - /** - * Passphrase to use to decrypt with a symmetric key. - */ + /** Passphrase to use to decrypt with a symmetric key. */ public String getSymmetricPassphrase() { return symmetricPassphrase; } - /** - * Passphrase to use to decrypt with a symmetric key. - */ + /** Passphrase to use to decrypt with a symmetric key. */ public void setSymmetricPassphrase(String x) { symmetricPassphrase = x != null ? x : ""; } - /** - * Keys to use for decryption and verification. - */ + /** Keys to use for decryption and verification. */ public Ring getRing() { return ring; } - /** - * Keys to use for decryption and verification. - */ + /** Keys to use for decryption and verification. */ protected void setRing(Ring x) { ring = x != null ? x : new Ring(); } @@ -147,29 +133,28 @@ protected void setRing(Ring x) { * verifies its signatures. If a file already exists in the output file's * location, it will be deleted. If an exception occurs during decryption, * the output file will be deleted. - * * @param ciphertext File containing a PGP message, in binary or - * ASCII Armor format. - * @param plaintext Location of the file into which to decrypt the message. + * ASCII Armor format. + * @param plaintext Location of the file into which to decrypt the message. * @return Metadata of original file, and the list of keys that signed * the message with a verified signature. The original file metadata * values are optional, and may be missing or incorrect. - * @throws IOException if an IO error occurs reading from or writing to - * the underlying input or output streams. - * @throws PGPException if the PGP message is not formatted correctly. - * @throws PassphraseException if an incorrect passphrase was supplied - * for one of the decryption keys, or as the - * {@link #getSymmetricPassphrase()}. - * @throws DecryptionException if the message was not encrypted for any - * of the keys supplied for decryption. + * @throws IOException if an IO error occurs reading from or writing to + * the underlying input or output streams. + * @throws PGPException if the PGP message is not formatted correctly. + * @throws PassphraseException if an incorrect passphrase was supplied + * for one of the decryption keys, or as the + * {@link #getSymmetricPassphrase()}. + * @throws DecryptionException if the message was not encrypted for any + * of the keys supplied for decryption. * @throws VerificationException if {@link #isVerificationRequired} and - * the message was not signed by any of the keys supplied for verification. + * the message was not signed by any of the keys supplied for verification. */ public FileMetadata decrypt(File ciphertext, File plaintext) - throws IOException, PGPException { + throws IOException, PGPException { if (ciphertext.equals(plaintext)) throw new IOException("cannot decrypt " + ciphertext + - " over itself"); + " over itself"); // delete old output file plaintext.delete(); @@ -178,9 +163,9 @@ public FileMetadata decrypt(File ciphertext, File plaintext) OutputStream output = null; try { input = new BufferedInputStream( - new FileInputStream(ciphertext), 0x1000); + new FileInputStream(ciphertext), 0x1000); output = new BufferedOutputStream( - new FileOutputStream(plaintext), 0x1000); + new FileOutputStream(plaintext), 0x1000); return decrypt(input, output); } catch (Exception e) { // delete output file if anything went wrong @@ -193,14 +178,8 @@ public FileMetadata decrypt(File ciphertext, File plaintext) } throw e; } finally { - try { - output.close(); - } catch (Exception e) { - } - try { - input.close(); - } catch (Exception e) { - } + try { output.close(); } catch (Exception e) {} + try { input.close(); } catch (Exception e) {} } } @@ -212,25 +191,24 @@ public FileMetadata decrypt(File ciphertext, File plaintext) * Note that the full decrypted content will be written to the output stream * before the message is verified, so you may want to buffer the content * and not write it to its final destination until this method returns. - * * @param ciphertext PGP message, in binary or ASCII Armor format. - * @param plaintext Decrypted content. + * @param plaintext Decrypted content. * @return Metadata of original file, and the list of keys that signed * the message with a verified signature. The original file metadata * values are optional, and may be missing or incorrect. - * @throws IOException if an IO error occurs reading from or writing to - * the underlying input or output streams. - * @throws PGPException if the PGP message is not formatted correctly. - * @throws PassphraseException if an incorrect passphrase was supplied - * for one of the decryption keys, or as the - * {@link #getSymmetricPassphrase()}. - * @throws DecryptionException if the message was not encrypted for any - * of the keys supplied for decryption. + * @throws IOException if an IO error occurs reading from or writing to + * the underlying input or output streams. + * @throws PGPException if the PGP message is not formatted correctly. + * @throws PassphraseException if an incorrect passphrase was supplied + * for one of the decryption keys, or as the + * {@link #getSymmetricPassphrase()}. + * @throws DecryptionException if the message was not encrypted for any + * of the keys supplied for decryption. * @throws VerificationException if {@link #isVerificationRequired} and - * the message was not signed by any of the keys supplied for verification. + * the message was not signed by any of the keys supplied for verification. */ public FileMetadata decrypt(InputStream ciphertext, OutputStream plaintext) - throws IOException, PGPException { + throws IOException, PGPException { List meta = unpack(parse(unarmor(ciphertext)), plaintext); if (meta.size() > 1) throw new PGPException("content contained more than one file"); @@ -244,7 +222,7 @@ public FileMetadata decrypt(InputStream ciphertext, OutputStream plaintext) * writing the decrypted message content into the output stream. */ protected List unpack(Iterator packets, - OutputStream plaintext) throws IOException, PGPException { + OutputStream plaintext) throws IOException, PGPException { List meta = new ArrayList(); List verifiers = new ArrayList(); @@ -266,8 +244,8 @@ protected List unpack(Iterator packets, // when in message header, initialize verifiers for these sigs if (Util.isEmpty(verifiers)) verifiers = buildVerifiers(list.iterator()); - // when in message trailer, match sigs to one-pass sigs - // in already initialized verifiers + // when in message trailer, match sigs to one-pass sigs + // in already initialized verifiers else matchSignatures(list.iterator(), verifiers); @@ -306,7 +284,7 @@ protected List unpack(Iterator packets, * for which a verification key is available. */ protected List buildVerifiers(Iterator signatures) - throws PGPException { + throws PGPException { ArrayList verifiers = new ArrayList(); while (signatures.hasNext()) { Verifier verifier = null; @@ -327,7 +305,7 @@ else if (signature instanceof PGPOnePassSignature) * Matches the specified trailing signatures to the specified verifiers. */ protected void matchSignatures(Iterator signatures, - List verifiers) { + List verifiers) { while (signatures.hasNext()) { PGPSignature signature = signatures.next(); @@ -340,7 +318,7 @@ protected void matchSignatures(Iterator signatures, * Decrypts the encrypted data as the returned input stream. */ protected InputStream decrypt(Iterator data) - throws IOException, PGPException { + throws IOException, PGPException { PGPPBEEncryptedData pbe = null; while (data.hasNext()) { @@ -358,10 +336,12 @@ protected InputStream decrypt(Iterator data) !Util.isEmpty(subkey.passphrase)) return decrypt(pke, subkey); - log.info("not using decryption key {} ", subkey); + else if (log.isInfoEnabled()) + log.info("not using decryption key {} ", subkey); } else { - log.info("not found decryption key {} ", + if (log.isInfoEnabled()) + log.info("not found decryption key {} ", Util.formatKeyId(pke.getKeyID())); } @@ -379,7 +359,7 @@ protected InputStream decrypt(Iterator data) * Decrypts the encrypted data as the returned input stream. */ protected InputStream decrypt(PGPPublicKeyEncryptedData data, Subkey subkey) - throws IOException, PGPException { + throws IOException, PGPException { if (data == null || subkey == null) throw new DecryptionException("no suitable decryption key found"); @@ -392,16 +372,16 @@ protected InputStream decrypt(PGPPublicKeyEncryptedData data, Subkey subkey) * Decrypts the encrypted data as the returned input stream. */ protected InputStream decrypt(PGPPBEEncryptedData data) - throws IOException, PGPException { + throws IOException, PGPException { if (data == null || Util.isEmpty(symmetricPassphrase)) throw new DecryptionException("no suitable decryption key found"); try { return data.getDataStream(buildSymmetricKeyDecryptor( - symmetricPassphrase)); + symmetricPassphrase)); } catch (PGPDataValidationException e) { throw new PassphraseException( - "incorrect passphrase for symmetric key", e); + "incorrect passphrase for symmetric key", e); } } @@ -411,14 +391,14 @@ protected InputStream decrypt(PGPPBEEncryptedData data) * with the specified list of verifiers (if verification required). */ protected long copy(InputStream i, OutputStream o, - List verifiers) throws IOException, PGPException { + List verifiers) throws IOException, PGPException { long total = 0; byte[] buf = getCopyBuffer(); int len = i.read(buf); if (verificationRequired && Util.isEmpty(verifiers)) throw new VerificationException( - "content not signed with a required key"); + "content not signed with a required key"); while (len != -1) { total += len; @@ -443,7 +423,7 @@ protected long copy(InputStream i, OutputStream o, * with verified signatures to the file metadata. */ protected void verify(List verifiers, List meta) - throws PGPException { + throws PGPException { if (!verificationRequired) return; for (Verifier verifier : verifiers) { @@ -464,17 +444,16 @@ protected void verify(List verifiers, List meta) * (to convert ascii-armored content back into binary data). */ protected InputStream unarmor(InputStream stream) - throws IOException, PGPException { + throws IOException, PGPException { return PGPUtil.getDecoderStream(stream); } /** * Separates stream into PGP packets. - * * @see PGPObjectFactory */ protected Iterator parse(InputStream stream) - throws IOException, PGPException { + throws IOException, PGPException { // before BCPG v1.55 // PGPObjectFactory.iterator() doesn't work for decryption // because its next() method prematurely calls nextObject() @@ -486,7 +465,6 @@ protected Iterator parse(InputStream stream) return new Iterator() { boolean checkedNext = false; Object nextElement = null; - public boolean hasNext() { if (!checkedNext) { checkedNext = true; @@ -498,13 +476,11 @@ public boolean hasNext() { } return nextElement != null; } - public Object next() { if (!hasNext()) throw new NoSuchElementException(); checkedNext = false; return nextElement; } - public void remove() { throw new UnsupportedOperationException(); } @@ -522,7 +498,7 @@ protected PGPContentVerifierBuilderProvider getVerifierProvider() { * Builds a symmetric-encryption decryptor for the specified passphrase. */ protected PublicKeyDataDecryptorFactory buildPublicKeyDecryptor( - Subkey subkey) throws PGPException { + Subkey subkey) throws PGPException { PGPPrivateKey privateKey = subkey.getPrivateKey(); if (privateKey == null) throw new PGPException("no private key for " + subkey); @@ -533,11 +509,11 @@ protected PublicKeyDataDecryptorFactory buildPublicKeyDecryptor( * Builds a symmetric-key decryptor for the specified passphrase. */ protected PBEDataDecryptorFactory buildSymmetricKeyDecryptor( - String passphrase) { + String passphrase) { char[] chars = !Util.isEmpty(passphrase) ? - passphrase.toCharArray() : new char[0]; + passphrase.toCharArray() : new char[0]; return new BcPBEDataDecryptorFactory(chars, - new BcPGPDigestCalculatorProvider()); + new BcPGPDigestCalculatorProvider()); } protected byte[] getCopyBuffer() { From 6f2bc0adc5cec74d753e040b196cd161eff436eb Mon Sep 17 00:00:00 2001 From: aboruch Date: Mon, 13 Nov 2017 09:11:01 +0100 Subject: [PATCH 4/4] Remove two isEnabled after restore --- src/main/java/org/c02e/jpgpj/Decryptor.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/c02e/jpgpj/Decryptor.java b/src/main/java/org/c02e/jpgpj/Decryptor.java index 7ac3bc2..68d0537 100644 --- a/src/main/java/org/c02e/jpgpj/Decryptor.java +++ b/src/main/java/org/c02e/jpgpj/Decryptor.java @@ -336,12 +336,10 @@ protected InputStream decrypt(Iterator data) !Util.isEmpty(subkey.passphrase)) return decrypt(pke, subkey); - else if (log.isInfoEnabled()) - log.info("not using decryption key {} ", subkey); + log.info("not using decryption key {} ", subkey); } else { - if (log.isInfoEnabled()) - log.info("not found decryption key {} ", + log.info("not found decryption key {} ", Util.formatKeyId(pke.getKeyID())); }