Class Encryptor
- All Implemented Interfaces:
Cloneable
Key
s 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
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static class
protected class
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected EncryptedAsciiArmorHeadersCallback
protected boolean
protected CompressionAlgorithm
protected int
static final boolean
static final CompressionAlgorithm
static final int
static final EncryptionAlgorithm
static final HashingAlgorithm
static final int
static final boolean
static final int
static final boolean
static final HashingAlgorithm
protected EncryptionAlgorithm
protected HashingAlgorithm
protected int
protected final org.slf4j.Logger
protected boolean
static final int
protected int
protected boolean
protected Ring
protected HashingAlgorithm
protected String
Deprecated.Null unless explicitly set by user.protected char[]
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
addArmoredHeaders
(Map<String, String> headers) Adds the specified headers - replaces existing ones and adds the new ones.protected OutputStream
armor
(OutputStream out, FileMetadata meta) Wraps with stream that outputs ASCII-armored text - including configuring its armor headers.int
bestPacketSize
(long inputSize) Calculates optimal PGP packet size, based on plaintext length.int
bestPacketSize
(FileMetadata meta) Calculates optimal PGP packet size, based on plaintext length.protected org.bouncycastle.openpgp.PGPEncryptedDataGenerator
Builds a PGPEncryptedDataGenerator for the configured encryption algorithm.protected org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator
buildPublicKeyEncryptor
(Key key, FileMetadata meta) Builds a PublicKeyKeyEncryptionMethodGenerator for the specified key.protected org.bouncycastle.openpgp.PGPSignatureGenerator
buildSigner
(Key key, FileMetadata meta) Builds a PGPSignatureGenerator for the specified key and content.protected org.bouncycastle.openpgp.operator.PGPContentSignerBuilder
buildSignerBuilder
(int keyAlgorithm, int hashAlgorithm) Builds a PGPContentSignerBuilder for the specified algorithms.protected org.bouncycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator
Builds a PublicKeyKeyEncryptionMethodGenerator for the specified key to encrypt the file.void
Zeroes-out the cached passphrase for all keys, and releases the extracted private key material for garbage collection.clone()
protected OutputStream
compress
(OutputStream out, FileMetadata meta) Wraps with stream that outputs compressed data packet.protected long
copy
(InputStream i, OutputStream o, Encryptor.SigningOutputStream s, FileMetadata meta) Copies the content from the specified input stream to the specified output stream.Signs, compresses, and encrypts the specified file to the output location specified by the second file.encrypt
(InputStream plaintext, OutputStream ciphertext) Signs, compresses, and encrypts the specified content as a PGP message into the specified output stream (with no optional metadata).encrypt
(InputStream plaintext, OutputStream ciphertext, FileMetadata meta) Signs, compresses, and encrypts the specified content as a PGP message into the specified output stream with the specified content metadata.protected OutputStream
encrypt
(OutputStream out, FileMetadata meta) Wraps with stream that outputs encrypted data packet.Signs, compresses, and encrypts the specified file to the output location specified by the second file.encryptBytes
(byte[] data, String name, File ciphertext) encryptBytes
(byte[] data, String name, OutputStream ciphertext) encryptBytes
(byte[] data, String name, Path ciphertext) int
estimateOutFileBufferSize
(long inFileSize) getArmoredHeader
(String name) Retrieves the value for the specified armored header.byte[]
getCompressionBuffer
(long inputSize) Internal buffer for compressed-data packets, sized based on plaintext length.byte[]
Internal buffer for compressed-data packets, sized based on plaintext length.int
byte[]
getCopyBuffer
(long inputSize) Internal buffer for copying plaintext into the encryption pipeline, sized based on plaintext length.byte[]
getCopyBuffer
(FileMetadata meta) Internal buffer for copying plaintext into the encryption pipeline, sized based on plaintext length.byte[]
getEncryptionBuffer
(long inputSize) Internal buffer for encrypted-data packets, sized based on plaintext length.byte[]
Internal buffer for encrypted-data packets, sized based on plaintext length.int
byte[]
getLiteralBuffer
(long inputSize) Internal buffer for literal-data packets, sized based on plaintext length.byte[]
getLiteralBuffer
(FileMetadata meta) Internal buffer for literal-data packets, sized based on plaintext length.int
getRing()
char[]
boolean
boolean
boolean
By default theArmoredOutputStream
adds a "Version" header - this setting allows users to remove this header (and perhaps replace it and/or add others - see headers manipulation methods).protected boolean
isUsableForSigning
(Subkey subkey) protected OutputStream
packet
(OutputStream out, FileMetadata meta) Wraps with stream that ouputs literal data packet.protected OutputStream
pipeline
(OutputStream out, List<OutputStream> stack) Pushes output stream onto stack if not null, and returns top of stack.prepareCiphertextOutputStream
(OutputStream ciphertext, FileMetadata meta, boolean closeOriginal) Builds a new wrapperOutputStream
to wrap the original specifiedOutputStream
, where everything written to the it is automatically encrypted+compressed+signed according to the encryptor's configuration, and then written to the original stream.prepareCiphertextOutputStream
(FileMetadata plainMeta, File ciphertext) Builds a wrapperOutputStream
where everything written to the it is encrypted+compressed+signed according to the encryptor's configuration, and then written to the specified target file.prepareCiphertextOutputStream
(FileMetadata plainMeta, Path ciphertext) Builds a wrapperOutputStream
where everything written to the it is encrypted+compressed+signed according to the encryptor's configuration, and then written to the specified target file.removeArmoredHeader
(String name) Removes the specified armored header Note: affects the output only ifarmored
setting is used.void
setArmoredHeaders
(Map<String, String> headers) Replaces the current armored headers with the provided ones.void
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.void
setAsciiArmored
(boolean x) void
void
setCompressionLevel
(int x) void
void
void
setKeyDeriviationWorkFactor
(int x) void
setLoggingEnabled
(boolean enabled) void
setMaxFileBufferSize
(int maxFileBufferSize) void
setRemoveDefaultArmoredVersionHeader
(boolean x) By default theArmoredOutputStream
adds a "Version" header - this setting allows users to remove this header (and perhaps replace it and/or add others - see headers manipulation methods).void
void
void
void
setSymmetricPassphraseChars
(char[] x) protected Encryptor.SigningOutputStream
sign
(OutputStream out, FileMetadata meta) Wraps with stream that outputs signature packets as header and footer to envelope.updateArmoredHeader
(String name, String value) Sets the specified header value - replaces it if already set.withArmoredHeader
(String name, String value) withArmoredHeaders
(Map<String, String> headers) withAsciiArmored
(boolean x) withCompressionLevel
(int x) withKeyDeriviationWorkFactor
(int x) withLoggingEnabled
(boolean enabled) withMaxFileBufferSize
(int maxFileBufferSize) withRemoveDefaultArmoredVersionHeader
(boolean x) withSymmetricPassphraseChars
(char[] x) wrapSourceInputStream
(InputStream sourceStream, long inputSize) wrapTargetOutputStream
(OutputStream targetStream, long inputSize)
-
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
-
DEFAULT_ENCRYPTION_ALGORITHM
-
DEFAULT_SIGNING_ALGORITHM
-
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
-
armorHeadersCallback
-
compressionLevel
protected int compressionLevel -
compressionAlgorithm
-
encryptionAlgorithm
-
signingAlgorithm
-
symmetricPassphraseChars
protected char[] symmetricPassphraseChars -
symmetricPassphrase
Deprecated.Null unless explicitly set by user. -
keyDerivationAlgorithm
-
keyDerivationWorkFactor
protected int keyDerivationWorkFactor -
maxFileBufferSize
protected int maxFileBufferSize -
loggingEnabled
protected boolean loggingEnabled -
ring
-
log
protected final org.slf4j.Logger log
-
-
Constructor Details
-
Encryptor
public Encryptor()Constructs an encryptor with an empty key ring. -
Encryptor
Constructs an encryptor with the specified key ring. -
Encryptor
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
- See Also:
-
getArmorHeadersCallback
- Returns:
- The last set
EncryptedAsciiArmorHeadersCallback
- See Also:
-
setArmorHeadersCallback
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 ifarmored
setting is used.- Parameters:
x
- The callback to invoke -null
if none- See Also:
-
withArmorHeadersCallback
- See Also:
-
isRemoveDefaultArmoredVersionHeader
public boolean isRemoveDefaultArmoredVersionHeader()By default theArmoredOutputStream
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 theArmoredOutputStream
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 ifarmored
setting is used.- Parameters:
x
-true
if "Version" should be removed - default=false
. Note: relevant only ifarmored
setting was also set.- See Also:
-
withRemoveDefaultArmoredVersionHeader
- See Also:
-
getArmoredHeader
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
- Returns:
- An unmodifiable
Map
of the current armored headers - Note: header name access is case sensitive
-
setArmoredHeaders
Replaces the current armored headers with the provided ones. Note: affects the output only ifarmored
setting is used.- Parameters:
headers
- The new headers to set - may benull
/empty. Note:- Header names are case sensitive
-
In order to clear all headers need to also use
setRemoveDefaultArmoredVersionHeader(boolean)
.
-
withArmoredHeaders
- See Also:
-
addArmoredHeaders
Adds the specified headers - replaces existing ones and adds the new ones. Note: affects the output only ifarmored
setting is used.- Parameters:
headers
- The headers to add - may benull
/empty. Note: header names are case sensitive.
-
updateArmoredHeader
Sets the specified header value - replaces it if already set. Note: affects the output only ifarmored
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 - ifnull
then equivalent toheader removal
- Returns:
- The replaced value -
null
if no previous value set - Throws:
NullPointerException
- If no header name provided- See Also:
-
withArmoredHeader
- See Also:
-
removeArmoredHeader
Removes the specified armored header Note: affects the output only ifarmored
setting is used.- Parameters:
name
- Case sensitive name of header to remove - Note: in order to remove the version header must usesetRemoveDefaultArmoredVersionHeader(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
- See Also:
-
getCompressionAlgorithm
- Returns:
- Compression algorithm to use.
Defaults to
CompressionAlgorithm.ZLIB
. - See Also:
-
setCompressionAlgorithm
- Parameters:
x
- Compression algorithm to use. Defaults toCompressionAlgorithm.ZLIB
.- See Also:
-
withCompressionAlgorithm
- See Also:
-
getEncryptionAlgorithm
- Returns:
- Encryption algorithm to use.
Defaults to
EncryptionAlgorithm.AES128
. - See Also:
-
setEncryptionAlgorithm
- Parameters:
x
- Encryption algorithm to use. Defaults toEncryptionAlgorithm.AES128
.- See Also:
-
withEncryptionAlgorithm
- See Also:
-
getSigningAlgorithm
- Returns:
- Signing algorithm to use.
Defaults to
HashingAlgorithm.SHA256
. - See Also:
-
setSigningAlgorithm
- Parameters:
x
- Signing algorithm to use. Defaults toHashingAlgorithm.SHA256
.- See Also:
-
withSigningAlgorithm
- 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 (orsetSymmetricPassphraseChars(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 untilclearSecrets()
is called (orsetSymmetricPassphraseChars(char[])
is called again with a different passphrase, and then the char[] will be zeroed.
-
withSymmetricPassphraseChars
- See Also:
-
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
- Parameters:
x
- Passphrase to use to encrypt with a symmetric key; or empty string. PrefersetSymmetricPassphraseChars(char[])
to avoid creating extra copies of the passphrase in memory that cannot be cleaned up.- See Also:
-
withSymmetricPassphrase
- See Also:
-
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
- Parameters:
x
- Key-derivation (aka s2k digest) algorithm to use (used to convert the symmetric passphrase into an encryption key). Defaults toHashingAlgorithm.SHA512
.- See Also:
-
withDeriviationAlgorithm
- 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
- 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
- See Also:
-
getRing
- Returns:
- Keys to use for encryption and signing.
-
setRing
- Parameters:
x
- Keys to use for encryption and signing.
-
withRing
- 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
- 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)
, andsetEncryptionAlgorithm(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)
, andsetEncryptionAlgorithm(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 inputname
- The "file" name to report as being encrypted - can benull
ciphertext
- Target ciphertextFile
- 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 inputname
- The "file" name to report as being encrypted - can benull
ciphertext
- Target ciphertextPath
- 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 inputname
- The "file" name to report as being encrypted - can benull
ciphertext
- Target ciphertextOutputStream
- 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)
, andsetEncryptionAlgorithm(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)
, andsetEncryptionAlgorithm(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 wrapperOutputStream
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
- TheFileMetadata
describing the plaintext file - ifnull
an empty ad-hoc instance will be createdciphertext
- The targetFile
for the encrypted data- Returns:
- The wrapper stream
- Throws:
IOException
- If failed to wrap the streamorg.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 wrapperOutputStream
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
- TheFileMetadata
describing the plaintext file - ifnull
an empty ad-hoc instance will be createdciphertext
- The targetPath
for the encrypted data- Returns:
- The wrapper stream
- Throws:
IOException
- If failed to wrap the streamorg.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 wrapperOutputStream
to wrap the original specifiedOutputStream
, 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 ifcloseOriginal
parameter istrue
- otherwise, it is the caller's responsibility to close it after having closed the wrapper.- Parameters:
ciphertext
- The originalOutputStream
into which the encryption results are to be written. Note: the stream will not be closed when the returned wrapper is closedmeta
- The original plaintext file'sFileMetadata
if available - ifnull
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 streamorg.bouncycastle.openpgp.PGPException
- If failed to apply a PGP wrapper
-
pipeline
Pushes output stream onto stack if not null, and returns top of stack. -
armor
Wraps with stream that outputs ASCII-armored text - including configuring its armor headers.- Parameters:
out
- TheOutputStream
to wrapmeta
- The input plaintextFileMetadata
- might be empty (but notnull
).- 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 plaintextInputStream
o
- The prepared target ciphertextinvalid @link
{@link OutputStream)
s
- TheEncryptor.SigningOutputStream
used to calculate the signature -null
if no signature providedmeta
- The providedFileMetadata
- 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
-
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
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
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
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
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
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
-