Class Encryptor

java.lang.Object
org.c02e.jpgpj.Encryptor
All Implemented Interfaces:
Cloneable

public class Encryptor extends Object implements Cloneable
Encrypts and signs PGP messages using the encryption and signing Keys supplied on this object's Ring.

To encode a message with ASCII Armor, setAsciiArmored(boolean) to true. To encrypt a message with a passphrase (instead of, or in addition to, a public-key pair), use setSymmetricPassphrase(java.lang.String) to supply the passphrase.

To encrypt without signing, setSigningAlgorithm(org.c02e.jpgpj.HashingAlgorithm) to HashingAlgorithm.Unsigned. To sign without encrypting, setEncryptionAlgorithm(org.c02e.jpgpj.EncryptionAlgorithm) to EncryptionAlgorithm.Unencrypted. To turn off compression, setCompressionAlgorithm(org.c02e.jpgpj.CompressionAlgorithm) to CompressionAlgorithm.Uncompressed.


 Here's an example of Alice encrypting and signing a file for Bob:
 new Encryptor(
     new Key(new File("path/to/my/keys/alice-sec.gpg"), "password123"),
     new Key(new File("path/to/my/keys/bob-pub.gpg"))
 ).encrypt(
     new File("path/to/plaintext.txt"),
     new File("path/to/ciphertext.txt.gpg")
 );
 
This is equivalent to the following `gpg` command (where Alice has an `alice` secret key and a `bob` public key on her keyring, and enters "password123" when prompted for her passphrase):

 gpg --sign --encrypt --local-user alice --recipient alice --recipient bob \
     --output path/to/ciphertext.txt.gpg path/to/plaintext.txt
 
  • Field Details

    • MAX_ENCRYPT_COPY_BUFFER_SIZE

      public static final int MAX_ENCRYPT_COPY_BUFFER_SIZE
      See Also:
    • DEFAULT_ASCII_ARMORED

      public static final boolean DEFAULT_ASCII_ARMORED
      See Also:
    • DEFAULT_REMOVE_DEFAULT_ARMORED_VERSION_HEADER

      public static final boolean DEFAULT_REMOVE_DEFAULT_ARMORED_VERSION_HEADER
      See Also:
    • DEFAULT_COMPRESSION_LEVEL

      public static final int DEFAULT_COMPRESSION_LEVEL
      See Also:
    • DEFAULT_COMPRESSION_ALGORITHM

      public static final CompressionAlgorithm DEFAULT_COMPRESSION_ALGORITHM
    • DEFAULT_ENCRYPTION_ALGORITHM

      public static final EncryptionAlgorithm DEFAULT_ENCRYPTION_ALGORITHM
    • DEFAULT_SIGNING_ALGORITHM

      public static final HashingAlgorithm DEFAULT_SIGNING_ALGORITHM
    • DEFAULT_KEY_DERIVATION_ALGORITHM

      public static final HashingAlgorithm DEFAULT_KEY_DERIVATION_ALGORITHM
    • DEFAULT_KEY_DERIVATION_ALGORITHM_WORK_FACTOR

      public static final int DEFAULT_KEY_DERIVATION_ALGORITHM_WORK_FACTOR
      See Also:
    • DEFAULT_MAX_FILE_BUFFER_SIZE

      public static final int DEFAULT_MAX_FILE_BUFFER_SIZE
      See Also:
    • DEFAULT_LOGGING_ENABLED

      public static final boolean DEFAULT_LOGGING_ENABLED
      See Also:
    • asciiArmored

      protected boolean asciiArmored
    • removeDefaultArmoredVersionHeader

      protected boolean removeDefaultArmoredVersionHeader
    • armoredHeaders

      protected Map<String,String> armoredHeaders
    • armorHeadersCallback

      protected EncryptedAsciiArmorHeadersCallback armorHeadersCallback
    • compressionLevel

      protected int compressionLevel
    • compressionAlgorithm

      protected CompressionAlgorithm compressionAlgorithm
    • encryptionAlgorithm

      protected EncryptionAlgorithm encryptionAlgorithm
    • signingAlgorithm

      protected HashingAlgorithm signingAlgorithm
    • symmetricPassphraseChars

      protected char[] symmetricPassphraseChars
    • symmetricPassphrase

      @Deprecated protected String symmetricPassphrase
      Deprecated.
      Null unless explicitly set by user.
    • keyDerivationAlgorithm

      protected HashingAlgorithm keyDerivationAlgorithm
    • keyDerivationWorkFactor

      protected int keyDerivationWorkFactor
    • maxFileBufferSize

      protected int maxFileBufferSize
    • loggingEnabled

      protected boolean loggingEnabled
    • ring

      protected Ring ring
    • log

      protected final org.slf4j.Logger log
  • Constructor Details

    • Encryptor

      public Encryptor()
      Constructs an encryptor with an empty key ring.
    • Encryptor

      public Encryptor(Ring ring)
      Constructs an encryptor with the specified key ring.
    • Encryptor

      public Encryptor(Key... keys)
      Constructs an encryptor with the specified keys.
  • Method Details

    • isAsciiArmored

      public boolean isAsciiArmored()
      Returns:
      true to encode final output with ASCII Armor. Defaults to false.
      See Also:
    • setAsciiArmored

      public void setAsciiArmored(boolean x)
      Parameters:
      x - true to encode final output with ASCII Armor. Defaults to false.
      See Also:
    • withAsciiArmored

      public Encryptor withAsciiArmored(boolean x)
      See Also:
    • getArmorHeadersCallback

      public EncryptedAsciiArmorHeadersCallback getArmorHeadersCallback()
      Returns:
      The last set EncryptedAsciiArmorHeadersCallback
      See Also:
    • setArmorHeadersCallback

      public void setArmorHeadersCallback(EncryptedAsciiArmorHeadersCallback x)
      Allows users to provide a callback that will be invoked for each encrypted armored output in order to allow them to set specified headers besides the global ones set by the encryptor. Note: affects the output only if armored setting is used.
      Parameters:
      x - The callback to invoke - null if none
      See Also:
    • withArmorHeadersCallback

      public Encryptor withArmorHeadersCallback(EncryptedAsciiArmorHeadersCallback x)
      See Also:
    • isRemoveDefaultArmoredVersionHeader

      public boolean isRemoveDefaultArmoredVersionHeader()
      By default the ArmoredOutputStream adds a "Version" header - this setting allows users to remove this header (and perhaps replace it and/or add others - see headers manipulation methods).
      Returns:
      true if "Version" should be removed - default=false
      See Also:
    • setRemoveDefaultArmoredVersionHeader

      public void setRemoveDefaultArmoredVersionHeader(boolean x)
      By default the ArmoredOutputStream adds a "Version" header - this setting allows users to remove this header (and perhaps replace it and/or add others - see headers manipulation methods). Note: affects the output only if armored setting is used.
      Parameters:
      x - true if "Version" should be removed - default=false. Note: relevant only if armored setting was also set.
      See Also:
    • withRemoveDefaultArmoredVersionHeader

      public Encryptor withRemoveDefaultArmoredVersionHeader(boolean x)
      See Also:
    • getArmoredHeader

      public String getArmoredHeader(String name)
      Retrieves the value for the specified armored header.
      Parameters:
      name - Case sensitive name of header to get
      Returns:
      The header value - null if header not set
      Throws:
      NullPointerException - If no header name provided
    • getArmoredHeaders

      public Map<String,String> getArmoredHeaders()
      Returns:
      An unmodifiable Map of the current armored headers - Note: header name access is case sensitive
    • setArmoredHeaders

      public void setArmoredHeaders(Map<String,String> headers)
      Replaces the current armored headers with the provided ones. Note: affects the output only if armored setting is used.
      Parameters:
      headers - The new headers to set - may be null/empty. Note:
    • withArmoredHeaders

      public Encryptor withArmoredHeaders(Map<String,String> headers)
      See Also:
    • addArmoredHeaders

      public void addArmoredHeaders(Map<String,String> headers)
      Adds the specified headers - replaces existing ones and adds the new ones. Note: affects the output only if armored setting is used.
      Parameters:
      headers - The headers to add - may be null/empty. Note: header names are case sensitive.
    • updateArmoredHeader

      public String updateArmoredHeader(String name, String value)
      Sets the specified header value - replaces it if already set. Note: affects the output only if armored setting is used.
      Parameters:
      name - Case sensitive name of header to set. Note: this method can be used to override the default version header value.
      value - Value to set - if null then equivalent to header removal
      Returns:
      The replaced value - null if no previous value set
      Throws:
      NullPointerException - If no header name provided
      See Also:
    • withArmoredHeader

      public Encryptor withArmoredHeader(String name, String value)
      See Also:
    • removeArmoredHeader

      public String removeArmoredHeader(String name)
      Removes the specified armored header Note: affects the output only if armored setting is used.
      Parameters:
      name - Case sensitive name of header to remove - Note: in order to remove the version header must use setRemoveDefaultArmoredVersionHeader(boolean).
      Returns:
      The removed value - null if header was not set
      Throws:
      NullPointerException - If no header name provided
    • getCompressionLevel

      public int getCompressionLevel()
      Returns:
      Compression level, from 1 (fastest and biggest) to 9 (slowest and smallest). Defaults to 6.
      See Also:
    • setCompressionLevel

      public void setCompressionLevel(int x)
      Parameters:
      x - Compression level, from 1 (fastest and biggest) to 9 (slowest and smallest). Defaults to 6.
      See Also:
    • withCompressionLevel

      public Encryptor withCompressionLevel(int x)
      See Also:
    • getCompressionAlgorithm

      public CompressionAlgorithm getCompressionAlgorithm()
      Returns:
      Compression algorithm to use. Defaults to CompressionAlgorithm.ZLIB.
      See Also:
    • setCompressionAlgorithm

      public void setCompressionAlgorithm(CompressionAlgorithm x)
      Parameters:
      x - Compression algorithm to use. Defaults to CompressionAlgorithm.ZLIB.
      See Also:
    • withCompressionAlgorithm

      public Encryptor withCompressionAlgorithm(CompressionAlgorithm x)
      See Also:
    • getEncryptionAlgorithm

      public EncryptionAlgorithm getEncryptionAlgorithm()
      Returns:
      Encryption algorithm to use. Defaults to EncryptionAlgorithm.AES128.
      See Also:
    • setEncryptionAlgorithm

      public void setEncryptionAlgorithm(EncryptionAlgorithm x)
      Parameters:
      x - Encryption algorithm to use. Defaults to EncryptionAlgorithm.AES128.
      See Also:
    • withEncryptionAlgorithm

      public Encryptor withEncryptionAlgorithm(EncryptionAlgorithm x)
      See Also:
    • getSigningAlgorithm

      public HashingAlgorithm getSigningAlgorithm()
      Returns:
      Signing algorithm to use. Defaults to HashingAlgorithm.SHA256.
      See Also:
    • setSigningAlgorithm

      public void setSigningAlgorithm(HashingAlgorithm x)
      Parameters:
      x - Signing algorithm to use. Defaults to HashingAlgorithm.SHA256.
      See Also:
    • withSigningAlgorithm

      public Encryptor withSigningAlgorithm(HashingAlgorithm x)
      See Also:
    • getSymmetricPassphraseChars

      public char[] getSymmetricPassphraseChars()
      Returns:
      Passphrase to use to encrypt with a symmetric key; or empty char[]. Note that this char[] itself (and not a copy) will be cached and used until clearSecrets() is called (or setSymmetricPassphraseChars(char[]) is called again with a different passphrase), and then the char[] will be zeroed.
    • setSymmetricPassphraseChars

      public void setSymmetricPassphraseChars(char[] x)
      Parameters:
      x - Passphrase to use to encrypt with a symmetric key; or empty char[]. Note that this char[] itself (and not a copy) will be cached and used until clearSecrets() is called (or setSymmetricPassphraseChars(char[]) is called again with a different passphrase, and then the char[] will be zeroed.
    • withSymmetricPassphraseChars

      public Encryptor withSymmetricPassphraseChars(char[] x)
      See Also:
    • getSymmetricPassphrase

      public String getSymmetricPassphrase()
      Returns:
      Passphrase to use to encrypt with a symmetric key; or empty string. Prefer getSymmetricPassphraseChars() to avoid creating extra copies of the passphrase in memory that cannot be cleaned up.
      See Also:
    • setSymmetricPassphrase

      public void setSymmetricPassphrase(String x)
      Parameters:
      x - Passphrase to use to encrypt with a symmetric key; or empty string. Prefer setSymmetricPassphraseChars(char[]) to avoid creating extra copies of the passphrase in memory that cannot be cleaned up.
      See Also:
    • withSymmetricPassphrase

      public Encryptor withSymmetricPassphrase(String x)
      See Also:
    • getKeyDeriviationAlgorithm

      public HashingAlgorithm getKeyDeriviationAlgorithm()
      Returns:
      Key-derivation (aka s2k digest) algorithm to use (used to convert the symmetric passphrase into an encryption key). Defaults to HashingAlgorithm.SHA512.
      See Also:
    • setKeyDeriviationAlgorithm

      public void setKeyDeriviationAlgorithm(HashingAlgorithm x)
      Parameters:
      x - Key-derivation (aka s2k digest) algorithm to use (used to convert the symmetric passphrase into an encryption key). Defaults to HashingAlgorithm.SHA512.
      See Also:
    • withDeriviationAlgorithm

      public Encryptor withDeriviationAlgorithm(HashingAlgorithm x)
      See Also:
    • getKeyDeriviationWorkFactor

      public int getKeyDeriviationWorkFactor()
      Returns:
      Key-derivation work factor (aka s2k count) to use, from 0 to 255 (where 1 = 1088 iterations, and 255 = 65,011,712 iterations). Defaults to 255.
      See Also:
    • setKeyDeriviationWorkFactor

      public void setKeyDeriviationWorkFactor(int x)
      Parameters:
      x - Key-derivation work factor (aka s2k count) to use, from 0 to 255 (where 1 = 1088 iterations, and 255 = 65,011,712 iterations). Defaults to 255.
      See Also:
    • withKeyDeriviationWorkFactor

      public Encryptor withKeyDeriviationWorkFactor(int x)
      See Also:
    • getMaxFileBufferSize

      public int getMaxFileBufferSize()
    • setMaxFileBufferSize

      public void setMaxFileBufferSize(int maxFileBufferSize)
      Parameters:
      maxFileBufferSize - Encryptor will choose the most appropriate read/write buffer size for each file. Defaults to 1MB.
      See Also:
    • withMaxFileBufferSize

      public Encryptor withMaxFileBufferSize(int maxFileBufferSize)
      See Also:
    • getRing

      public Ring getRing()
      Returns:
      Keys to use for encryption and signing.
    • setRing

      public void setRing(Ring x)
      Parameters:
      x - Keys to use for encryption and signing.
    • withRing

      public Encryptor withRing(Ring x)
      See Also:
    • isLoggingEnabled

      public boolean isLoggingEnabled()
      Returns:
      true if logging a brief summary of the execution every time encryption is executed (e.g. file name/path, size, compression type, etc.). Note: errors/warnings logging are not affected by this setting
    • setLoggingEnabled

      public void setLoggingEnabled(boolean enabled)
      Parameters:
      enabled - true if should log a brief summary of the execution every time encryption is executed (e.g. file name/path, size, compression type, etc.). Note: errors/warnings logging are not affected by this setting
    • withLoggingEnabled

      public Encryptor withLoggingEnabled(boolean enabled)
      See Also:
    • clearSecrets

      public void clearSecrets()
      Zeroes-out the cached passphrase for all keys, and releases the extracted private key material for garbage collection.
    • encrypt

      public FileMetadata encrypt(File plaintext, File ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Signs, compresses, and encrypts the specified file to the output location specified by the second file. If a file already exists in the output file's location, it will be deleted. If an exception occurs during this processing, the output file will be deleted.

      Use the setSigningAlgorithm(org.c02e.jpgpj.HashingAlgorithm), setCompressionAlgorithm(org.c02e.jpgpj.CompressionAlgorithm), and setEncryptionAlgorithm(org.c02e.jpgpj.EncryptionAlgorithm) before running this method to turn off or adjust signing, compression, or encryption.

      Parameters:
      plaintext - File to encrypt.
      ciphertext - Location of output file.
      Returns:
      The FileMetadata of the encrypted plaintext
      Throws:
      IOException - if an IO error occurs reading from or writing to the underlying input or output streams.
      org.bouncycastle.openpgp.PGPException - if no encryption keys and no passphrase for symmetric encryption were supplied (and the message is not unencrypted), or if no signing keys were supplied (and the message is not unsigned).
      PassphraseException - if an incorrect passphrase was supplied for one of the signing keys.
    • encrypt

      public FileMetadata encrypt(Path plaintext, Path ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Signs, compresses, and encrypts the specified file to the output location specified by the second file. If a file already exists in the output file's location, it will be deleted. If an exception occurs during this processing, the output file will be deleted.

      Use the setSigningAlgorithm(org.c02e.jpgpj.HashingAlgorithm), setCompressionAlgorithm(org.c02e.jpgpj.CompressionAlgorithm), and setEncryptionAlgorithm(org.c02e.jpgpj.EncryptionAlgorithm) before running this method to turn off or adjust signing, compression, or encryption.

      Parameters:
      plaintext - Path of file to encrypt.
      ciphertext - Path location of output ciphertext file.
      Returns:
      The FileMetadata of the encrypted plaintext
      Throws:
      IOException - if an IO error occurs reading from or writing to the underlying input or output streams.
      org.bouncycastle.openpgp.PGPException - if no encryption keys and no passphrase for symmetric encryption were supplied (and the message is not unencrypted), or if no signing keys were supplied (and the message is not unsigned).
      PassphraseException - if an incorrect passphrase was supplied for one of the signing keys.
    • wrapSourceInputStream

      public InputStream wrapSourceInputStream(InputStream sourceStream, long inputSize) throws IOException
      Parameters:
      sourceStream - Original source (plaintext) InputStream
      inputSize - Expected input (plaintext) size
      Returns:
      A wrapper buffered stream optimized for the input size according to the current encryptor settings
      Throws:
      IOException - If failed to generate the wrapper
    • wrapTargetOutputStream

      public OutputStream wrapTargetOutputStream(OutputStream targetStream, long inputSize) throws IOException
      Parameters:
      targetStream - Original target (ciphertext) OutputStream
      inputSize - Expected input (plaintext) size
      Returns:
      A wrapper buffered stream optimized for the input size according to the current encryptor settings.
      Throws:
      IOException - If failed to generate the wrapper
      See Also:
    • encryptBytes

      public FileMetadata encryptBytes(byte[] data, String name, File ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Parameters:
      data - Data buffer to be used as plaintext input
      name - The "file" name to report as being encrypted - can be null
      ciphertext - Target ciphertext File
      Returns:
      The FileMetadata of the encrypted plaintext
      Throws:
      IOException - if an IO error occurs reading from or writing to the underlying input or output streams.
      org.bouncycastle.openpgp.PGPException - if no encryption keys and no passphrase for symmetric encryption were supplied (and the message is not unencrypted), or if no signing keys were supplied (and the message is not unsigned).
      PassphraseException - if an incorrect passphrase was supplied for one of the signing keys.
    • encryptBytes

      public FileMetadata encryptBytes(byte[] data, String name, Path ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Parameters:
      data - Data buffer to be used as plaintext input
      name - The "file" name to report as being encrypted - can be null
      ciphertext - Target ciphertext Path
      Returns:
      The FileMetadata of the encrypted plaintext
      Throws:
      IOException - if an IO error occurs reading from or writing to the underlying input or output streams.
      org.bouncycastle.openpgp.PGPException - if no encryption keys and no passphrase for symmetric encryption were supplied (and the message is not unencrypted), or if no signing keys were supplied (and the message is not unsigned).
      PassphraseException - if an incorrect passphrase was supplied for one of the signing keys.
    • encryptBytes

      public FileMetadata encryptBytes(byte[] data, String name, OutputStream ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Parameters:
      data - Data buffer to be used as plaintext input
      name - The "file" name to report as being encrypted - can be null
      ciphertext - Target ciphertext OutputStream
      Returns:
      The FileMetadata of the encrypted plaintext
      Throws:
      IOException - if an IO error occurs reading from or writing to the underlying input or output streams.
      org.bouncycastle.openpgp.PGPException - if no encryption keys and no passphrase for symmetric encryption were supplied (and the message is not unencrypted), or if no signing keys were supplied (and the message is not unsigned).
      PassphraseException - if an incorrect passphrase was supplied for one of the signing keys.
    • encrypt

      public FileMetadata encrypt(InputStream plaintext, OutputStream ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Signs, compresses, and encrypts the specified content as a PGP message into the specified output stream (with no optional metadata). Does not close or flush the streams.

      Use the setSigningAlgorithm(org.c02e.jpgpj.HashingAlgorithm), setCompressionAlgorithm(org.c02e.jpgpj.CompressionAlgorithm), and setEncryptionAlgorithm(org.c02e.jpgpj.EncryptionAlgorithm) before running this method to turn off or adjust signing, compression, or encryption.

      Parameters:
      plaintext - InputStream content to encrypt.
      ciphertext - OutputStream for PGP message, in binary or ASCII Armor format.
      Returns:
      A FileMetadata placeholder that contains at the very least the number of bytes processed from the plaintext stream
      Throws:
      IOException - if an IO error occurs reading from or writing to the underlying input or output streams.
      org.bouncycastle.openpgp.PGPException - if no encryption keys and no passphrase for symmetric encryption were supplied (and the message is not unencrypted), or if no signing keys were supplied (and the message is not unsigned).
      PassphraseException - if an incorrect passphrase was supplied for one of the signing keys.
    • encrypt

      public FileMetadata encrypt(InputStream plaintext, OutputStream ciphertext, FileMetadata meta) throws IOException, org.bouncycastle.openpgp.PGPException
      Signs, compresses, and encrypts the specified content as a PGP message into the specified output stream with the specified content metadata. Does not close or flush the streams.

      Use the setSigningAlgorithm(org.c02e.jpgpj.HashingAlgorithm), setCompressionAlgorithm(org.c02e.jpgpj.CompressionAlgorithm), and setEncryptionAlgorithm(org.c02e.jpgpj.EncryptionAlgorithm) before running this method to turn off or adjust signing, compression, or encryption.

      Parameters:
      plaintext - Content to encrypt.
      ciphertext - PGP message, in binary or ASCII Armor format.
      meta - Metadata of original file that contains at the very least the number of bytes processed from the plaintext stream
      Throws:
      IOException - if an IO error occurs reading from or writing to the underlying input or output streams.
      org.bouncycastle.openpgp.PGPException - if no encryption keys and no passphrase for symmetric encryption were supplied (and the message is not unencrypted), or if no signing keys were supplied (and the message is not unsigned).
      PassphraseException - if an incorrect passphrase was supplied for one of the signing keys.
    • prepareCiphertextOutputStream

      public OutputStream prepareCiphertextOutputStream(FileMetadata plainMeta, File ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Builds a wrapper OutputStream where everything written to the it is encrypted+compressed+signed according to the encryptor's configuration, and then written to the specified target file. Closing the wrapper stream finalizes the encryption and signature, and finishes writing all the wrapper stream's content to the original stream as well as closing the file stream.
      Parameters:
      plainMeta - The FileMetadata describing the plaintext file - if null an empty ad-hoc instance will be created
      ciphertext - The target File for the encrypted data
      Returns:
      The wrapper stream
      Throws:
      IOException - If failed to wrap the stream
      org.bouncycastle.openpgp.PGPException - If failed to apply a PGP wrapper
    • prepareCiphertextOutputStream

      public OutputStream prepareCiphertextOutputStream(FileMetadata plainMeta, Path ciphertext) throws IOException, org.bouncycastle.openpgp.PGPException
      Builds a wrapper OutputStream where everything written to the it is encrypted+compressed+signed according to the encryptor's configuration, and then written to the specified target file. Closing the wrapper stream finalizes the encryption and signature, and finishes writing all the wrapper stream's content to the original stream as well as closing the file stream.
      Parameters:
      plainMeta - The FileMetadata describing the plaintext file - if null an empty ad-hoc instance will be created
      ciphertext - The target Path for the encrypted data
      Returns:
      The wrapper stream
      Throws:
      IOException - If failed to wrap the stream
      org.bouncycastle.openpgp.PGPException - If failed to apply a PGP wrapper
    • prepareCiphertextOutputStream

      public OutputStream prepareCiphertextOutputStream(OutputStream ciphertext, FileMetadata meta, boolean closeOriginal) throws IOException, org.bouncycastle.openpgp.PGPException
      Builds a new wrapper OutputStream to wrap the original specified OutputStream, where everything written to the it is automatically encrypted+compressed+signed according to the encryptor's configuration, and then written to the original stream. Closing the wrapper stream finalizes the encryption and signature, and finishes writing all the wrapper stream's content to the original stream. The original stream will be closed if closeOriginal parameter is true - otherwise, it is the caller's responsibility to close it after having closed the wrapper.
      Parameters:
      ciphertext - The original OutputStream into which the encryption results are to be written. Note: the stream will not be closed when the returned wrapper is closed
      meta - The original plaintext file's FileMetadata if available - if null an ad-hoc empty instance is used.
      closeOriginal - Whether to also close the original wrapped stream when the wrapper is closed.
      Returns:
      A wrapper stream - Note: actual encryption and signature is finalized when it is closed.
      Throws:
      IOException - If failed to wrap the stream
      org.bouncycastle.openpgp.PGPException - If failed to apply a PGP wrapper
    • pipeline

      protected OutputStream pipeline(OutputStream out, List<OutputStream> stack)
      Pushes output stream onto stack if not null, and returns top of stack.
    • armor

      protected OutputStream armor(OutputStream out, FileMetadata meta)
      Wraps with stream that outputs ASCII-armored text - including configuring its armor headers.
      Parameters:
      out - The OutputStream to wrap
      meta - The input plaintext FileMetadata - might be empty (but not null).
      Returns:
      The wrapped output stream - null if no wrapping.
      See Also:
    • encrypt

      protected OutputStream encrypt(OutputStream out, FileMetadata meta) throws IOException, org.bouncycastle.openpgp.PGPException
      Wraps with stream that outputs encrypted data packet.
      Throws:
      IOException
      org.bouncycastle.openpgp.PGPException
    • compress

      protected OutputStream compress(OutputStream out, FileMetadata meta) throws IOException, org.bouncycastle.openpgp.PGPException
      Wraps with stream that outputs compressed data packet.
      Throws:
      IOException
      org.bouncycastle.openpgp.PGPException
    • packet

      protected OutputStream packet(OutputStream out, FileMetadata meta) throws IOException, org.bouncycastle.openpgp.PGPException
      Wraps with stream that ouputs literal data packet.
      Throws:
      IOException
      org.bouncycastle.openpgp.PGPException
    • sign

      protected Encryptor.SigningOutputStream sign(OutputStream out, FileMetadata meta) throws IOException, org.bouncycastle.openpgp.PGPException
      Wraps with stream that outputs signature packets as header and footer to envelope.
      Throws:
      IOException
      org.bouncycastle.openpgp.PGPException
    • copy

      protected long copy(InputStream i, OutputStream o, Encryptor.SigningOutputStream s, FileMetadata meta) throws IOException, org.bouncycastle.openpgp.PGPException
      Copies the content from the specified input stream to the specified output stream.
      Parameters:
      i - The plaintext InputStream
      o - The prepared target ciphertext
      invalid @link
      {@link OutputStream)
      s - The Encryptor.SigningOutputStream used to calculate the signature - null if no signature provided
      meta - The provided FileMetadata
      Returns:
      Total number of processed bytes from input stream
      Throws:
      IOException
      org.bouncycastle.openpgp.PGPException
    • buildEncryptor

      protected org.bouncycastle.openpgp.PGPEncryptedDataGenerator buildEncryptor()
      Builds a PGPEncryptedDataGenerator for the configured encryption algorithm.
    • buildPublicKeyEncryptor

      protected org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator buildPublicKeyEncryptor(Key key, FileMetadata meta)
      Builds a PublicKeyKeyEncryptionMethodGenerator for the specified key.
    • buildSymmetricKeyEncryptor

      protected org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator buildSymmetricKeyEncryptor(FileMetadata meta) throws org.bouncycastle.openpgp.PGPException
      Builds a PublicKeyKeyEncryptionMethodGenerator for the specified key to encrypt the file.
      Throws:
      org.bouncycastle.openpgp.PGPException
    • isUsableForSigning

      protected boolean isUsableForSigning(Subkey subkey)
    • buildSigner

      protected org.bouncycastle.openpgp.PGPSignatureGenerator buildSigner(Key key, FileMetadata meta) throws org.bouncycastle.openpgp.PGPException
      Builds a PGPSignatureGenerator for the specified key and content.
      Throws:
      org.bouncycastle.openpgp.PGPException
    • buildSignerBuilder

      protected org.bouncycastle.openpgp.operator.PGPContentSignerBuilder buildSignerBuilder(int keyAlgorithm, int hashAlgorithm)
      Builds a PGPContentSignerBuilder for the specified algorithms.
    • getEncryptionBuffer

      public byte[] getEncryptionBuffer(FileMetadata meta)
      Internal buffer for encrypted-data packets, sized based on plaintext length.
    • getEncryptionBuffer

      public byte[] getEncryptionBuffer(long inputSize)
      Internal buffer for encrypted-data packets, sized based on plaintext length.
    • getCompressionBuffer

      public byte[] getCompressionBuffer(FileMetadata meta)
      Internal buffer for compressed-data packets, sized based on plaintext length.
    • getCompressionBuffer

      public byte[] getCompressionBuffer(long inputSize)
      Internal buffer for compressed-data packets, sized based on plaintext length.
    • getLiteralBuffer

      public byte[] getLiteralBuffer(FileMetadata meta)
      Internal buffer for literal-data packets, sized based on plaintext length.
    • getLiteralBuffer

      public byte[] getLiteralBuffer(long inputSize)
      Internal buffer for literal-data packets, sized based on plaintext length.
    • getCopyBuffer

      public byte[] getCopyBuffer(FileMetadata meta)
      Internal buffer for copying plaintext into the encryption pipeline, sized based on plaintext length.
    • getCopyBuffer

      public byte[] getCopyBuffer(long inputSize)
      Internal buffer for copying plaintext into the encryption pipeline, sized based on plaintext length.
    • bestPacketSize

      public int bestPacketSize(FileMetadata meta)
      Calculates optimal PGP packet size, based on plaintext length.
    • bestPacketSize

      public int bestPacketSize(long inputSize)
      Calculates optimal PGP packet size, based on plaintext length.
    • estimateOutFileBufferSize

      public int estimateOutFileBufferSize(long inFileSize)
      Parameters:
      inFileSize - Input (plaintext) file size
      Returns:
      The recommended buffering for the target (ciphertext) output stream
      See Also:
    • clone

      public Encryptor clone()
      Overrides:
      clone in class Object