Class Encryptor
- java.lang.Object
-
- org.c02e.jpgpj.Encryptor
-
- All Implemented Interfaces:
java.lang.Cloneable
public class Encryptor extends java.lang.Object implements java.lang.Cloneable
Encrypts and signs PGP messages using the encryption and signingKey
s supplied on this object'sRing
.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), usesetSymmetricPassphrase(java.lang.String)
to supply the passphrase.To encrypt without signing,
setSigningAlgorithm(org.c02e.jpgpj.HashingAlgorithm)
toHashingAlgorithm.Unsigned
. To sign without encrypting,setEncryptionAlgorithm(org.c02e.jpgpj.EncryptionAlgorithm)
toEncryptionAlgorithm.Unencrypted
. To turn off compression,setCompressionAlgorithm(org.c02e.jpgpj.CompressionAlgorithm)
toCompressionAlgorithm.Uncompressed
.
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):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") );
gpg --sign --encrypt --local-user alice --recipient alice --recipient bob \ --output path/to/ciphertext.txt.gpg path/to/plaintext.txt
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected static class
Encryptor.EncryptorWrapperStream
protected class
Encryptor.SigningOutputStream
-
Field Summary
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
addArmoredHeaders(java.util.Map<java.lang.String,java.lang.String> headers)
Adds the specified headers - replaces existing ones and adds the new ones.protected java.io.OutputStream
armor(java.io.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
buildEncryptor()
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
buildSymmetricKeyEncryptor(FileMetadata meta)
Builds a PublicKeyKeyEncryptionMethodGenerator for the specified key to encrypt the file.void
clearSecrets()
Zeroes-out the cached passphrase for all keys, and releases the extracted private key material for garbage collection.Encryptor
clone()
protected java.io.OutputStream
compress(java.io.OutputStream out, FileMetadata meta)
Wraps with stream that outputs compressed data packet.protected long
copy(java.io.InputStream i, java.io.OutputStream o, Encryptor.SigningOutputStream s, FileMetadata meta)
Copies the content from the specified input stream to the specified output stream.FileMetadata
encrypt(java.io.File plaintext, java.io.File ciphertext)
Signs, compresses, and encrypts the specified file to the output location specified by the second file.FileMetadata
encrypt(java.io.InputStream plaintext, java.io.OutputStream ciphertext)
Signs, compresses, and encrypts the specified content as a PGP message into the specified output stream (with no optional metadata).FileMetadata
encrypt(java.io.InputStream plaintext, java.io.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 java.io.OutputStream
encrypt(java.io.OutputStream out, FileMetadata meta)
Wraps with stream that outputs encrypted data packet.FileMetadata
encrypt(java.nio.file.Path plaintext, java.nio.file.Path ciphertext)
Signs, compresses, and encrypts the specified file to the output location specified by the second file.FileMetadata
encryptBytes(byte[] data, java.lang.String name, java.io.File ciphertext)
FileMetadata
encryptBytes(byte[] data, java.lang.String name, java.io.OutputStream ciphertext)
FileMetadata
encryptBytes(byte[] data, java.lang.String name, java.nio.file.Path ciphertext)
int
estimateOutFileBufferSize(long inFileSize)
java.lang.String
getArmoredHeader(java.lang.String name)
Retrieves the value for the specified armored header.java.util.Map<java.lang.String,java.lang.String>
getArmoredHeaders()
EncryptedAsciiArmorHeadersCallback
getArmorHeadersCallback()
CompressionAlgorithm
getCompressionAlgorithm()
byte[]
getCompressionBuffer(long inputSize)
Internal buffer for compressed-data packets, sized based on plaintext length.byte[]
getCompressionBuffer(FileMetadata meta)
Internal buffer for compressed-data packets, sized based on plaintext length.int
getCompressionLevel()
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.EncryptionAlgorithm
getEncryptionAlgorithm()
byte[]
getEncryptionBuffer(long inputSize)
Internal buffer for encrypted-data packets, sized based on plaintext length.byte[]
getEncryptionBuffer(FileMetadata meta)
Internal buffer for encrypted-data packets, sized based on plaintext length.HashingAlgorithm
getKeyDeriviationAlgorithm()
int
getKeyDeriviationWorkFactor()
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
getMaxFileBufferSize()
Ring
getRing()
HashingAlgorithm
getSigningAlgorithm()
java.lang.String
getSymmetricPassphrase()
char[]
getSymmetricPassphraseChars()
boolean
isAsciiArmored()
boolean
isLoggingEnabled()
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).protected boolean
isUsableForSigning(Subkey subkey)
protected java.io.OutputStream
packet(java.io.OutputStream out, FileMetadata meta)
Wraps with stream that ouputs literal data packet.protected java.io.OutputStream
pipeline(java.io.OutputStream out, java.util.List<java.io.OutputStream> stack)
Pushes output stream onto stack if not null, and returns top of stack.java.io.OutputStream
prepareCiphertextOutputStream(java.io.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.java.io.OutputStream
prepareCiphertextOutputStream(FileMetadata plainMeta, java.io.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.java.io.OutputStream
prepareCiphertextOutputStream(FileMetadata plainMeta, java.nio.file.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.java.lang.String
removeArmoredHeader(java.lang.String name)
Removes the specified armored header Note: affects the output only ifarmored
setting is used.void
setArmoredHeaders(java.util.Map<java.lang.String,java.lang.String> headers)
Replaces the current armored headers with the provided ones.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.void
setAsciiArmored(boolean x)
void
setCompressionAlgorithm(CompressionAlgorithm x)
void
setCompressionLevel(int x)
void
setEncryptionAlgorithm(EncryptionAlgorithm x)
void
setKeyDeriviationAlgorithm(HashingAlgorithm x)
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
setRing(Ring x)
void
setSigningAlgorithm(HashingAlgorithm x)
void
setSymmetricPassphrase(java.lang.String x)
void
setSymmetricPassphraseChars(char[] x)
protected Encryptor.SigningOutputStream
sign(java.io.OutputStream out, FileMetadata meta)
Wraps with stream that outputs signature packets as header and footer to envelope.java.lang.String
updateArmoredHeader(java.lang.String name, java.lang.String value)
Sets the specified header value - replaces it if already set.Encryptor
withArmoredHeader(java.lang.String name, java.lang.String value)
Encryptor
withArmoredHeaders(java.util.Map<java.lang.String,java.lang.String> headers)
Encryptor
withArmorHeadersCallback(EncryptedAsciiArmorHeadersCallback x)
Encryptor
withAsciiArmored(boolean x)
Encryptor
withCompressionAlgorithm(CompressionAlgorithm x)
Encryptor
withCompressionLevel(int x)
Encryptor
withDeriviationAlgorithm(HashingAlgorithm x)
Encryptor
withEncryptionAlgorithm(EncryptionAlgorithm x)
Encryptor
withKeyDeriviationWorkFactor(int x)
Encryptor
withLoggingEnabled(boolean enabled)
Encryptor
withMaxFileBufferSize(int maxFileBufferSize)
Encryptor
withRemoveDefaultArmoredVersionHeader(boolean x)
Encryptor
withRing(Ring x)
Encryptor
withSigningAlgorithm(HashingAlgorithm x)
Encryptor
withSymmetricPassphrase(java.lang.String x)
Encryptor
withSymmetricPassphraseChars(char[] x)
java.io.InputStream
wrapSourceInputStream(java.io.InputStream sourceStream, long inputSize)
java.io.OutputStream
wrapTargetOutputStream(java.io.OutputStream targetStream, long inputSize)
-
-
-
Field Detail
-
MAX_ENCRYPT_COPY_BUFFER_SIZE
public static final int MAX_ENCRYPT_COPY_BUFFER_SIZE
- See Also:
- Constant Field Values
-
DEFAULT_ASCII_ARMORED
public static final boolean DEFAULT_ASCII_ARMORED
- See Also:
- Constant Field Values
-
DEFAULT_REMOVE_DEFAULT_ARMORED_VERSION_HEADER
public static final boolean DEFAULT_REMOVE_DEFAULT_ARMORED_VERSION_HEADER
- See Also:
- Constant Field Values
-
DEFAULT_COMPRESSION_LEVEL
public static final int DEFAULT_COMPRESSION_LEVEL
- See Also:
- Constant Field Values
-
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:
- Constant Field Values
-
DEFAULT_MAX_FILE_BUFFER_SIZE
public static final int DEFAULT_MAX_FILE_BUFFER_SIZE
- See Also:
- Constant Field Values
-
DEFAULT_LOGGING_ENABLED
public static final boolean DEFAULT_LOGGING_ENABLED
- See Also:
- Constant Field Values
-
asciiArmored
protected boolean asciiArmored
-
removeDefaultArmoredVersionHeader
protected boolean removeDefaultArmoredVersionHeader
-
armoredHeaders
protected java.util.Map<java.lang.String,java.lang.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 java.lang.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
-
-
Method Detail
-
isAsciiArmored
public boolean isAsciiArmored()
- Returns:
true
to encode final output with ASCII Armor. Defaults to false.- See Also:
DEFAULT_ASCII_ARMORED
-
setAsciiArmored
public void setAsciiArmored(boolean x)
- Parameters:
x
-true
to encode final output with ASCII Armor. Defaults to false.- See Also:
DEFAULT_ASCII_ARMORED
-
withAsciiArmored
public Encryptor withAsciiArmored(boolean x)
- See Also:
setAsciiArmored(boolean)
-
getArmorHeadersCallback
public EncryptedAsciiArmorHeadersCallback getArmorHeadersCallback()
- Returns:
- The last set
EncryptedAsciiArmorHeadersCallback
- See Also:
setArmorHeadersCallback(EncryptedAsciiArmorHeadersCallback)
-
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 ifarmored
setting is used.- Parameters:
x
- The callback to invoke -null
if none- See Also:
isAsciiArmored()
,isRemoveDefaultArmoredVersionHeader()
,setArmoredHeaders
,addArmoredHeaders
,updateArmoredHeader
-
withArmorHeadersCallback
public Encryptor withArmorHeadersCallback(EncryptedAsciiArmorHeadersCallback x)
-
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:
DEFAULT_REMOVE_DEFAULT_ARMORED_VERSION_HEADER
-
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:
DEFAULT_REMOVE_DEFAULT_ARMORED_VERSION_HEADER
-
withRemoveDefaultArmoredVersionHeader
public Encryptor withRemoveDefaultArmoredVersionHeader(boolean x)
-
getArmoredHeader
public java.lang.String getArmoredHeader(java.lang.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:
java.lang.NullPointerException
- If no header name provided
-
getArmoredHeaders
public java.util.Map<java.lang.String,java.lang.String> getArmoredHeaders()
- Returns:
- An unmodifiable
Map
of the current armored headers - Note: header name access is case sensitive
-
setArmoredHeaders
public void setArmoredHeaders(java.util.Map<java.lang.String,java.lang.String> headers)
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
public Encryptor withArmoredHeaders(java.util.Map<java.lang.String,java.lang.String> headers)
- See Also:
setArmoredHeaders(Map)
-
addArmoredHeaders
public void addArmoredHeaders(java.util.Map<java.lang.String,java.lang.String> headers)
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
public java.lang.String updateArmoredHeader(java.lang.String name, java.lang.String value)
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:
java.lang.NullPointerException
- If no header name provided- See Also:
setRemoveDefaultArmoredVersionHeader(boolean)
-
withArmoredHeader
public Encryptor withArmoredHeader(java.lang.String name, java.lang.String value)
- See Also:
updateArmoredHeader(String, String)
-
removeArmoredHeader
public java.lang.String removeArmoredHeader(java.lang.String name)
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:
java.lang.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:
DEFAULT_COMPRESSION_LEVEL
-
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:
DEFAULT_COMPRESSION_LEVEL
-
withCompressionLevel
public Encryptor withCompressionLevel(int x)
- See Also:
setCompressionLevel(int)
-
getCompressionAlgorithm
public CompressionAlgorithm getCompressionAlgorithm()
- Returns:
- Compression algorithm to use.
Defaults to
CompressionAlgorithm.ZLIB
. - See Also:
DEFAULT_COMPRESSION_ALGORITHM
-
setCompressionAlgorithm
public void setCompressionAlgorithm(CompressionAlgorithm x)
- Parameters:
x
- Compression algorithm to use. Defaults toCompressionAlgorithm.ZLIB
.- See Also:
DEFAULT_COMPRESSION_ALGORITHM
-
withCompressionAlgorithm
public Encryptor withCompressionAlgorithm(CompressionAlgorithm x)
-
getEncryptionAlgorithm
public EncryptionAlgorithm getEncryptionAlgorithm()
- Returns:
- Encryption algorithm to use.
Defaults to
EncryptionAlgorithm.AES128
. - See Also:
DEFAULT_ENCRYPTION_ALGORITHM
-
setEncryptionAlgorithm
public void setEncryptionAlgorithm(EncryptionAlgorithm x)
- Parameters:
x
- Encryption algorithm to use. Defaults toEncryptionAlgorithm.AES128
.- See Also:
DEFAULT_ENCRYPTION_ALGORITHM
-
withEncryptionAlgorithm
public Encryptor withEncryptionAlgorithm(EncryptionAlgorithm x)
-
getSigningAlgorithm
public HashingAlgorithm getSigningAlgorithm()
- Returns:
- Signing algorithm to use.
Defaults to
HashingAlgorithm.SHA256
. - See Also:
DEFAULT_SIGNING_ALGORITHM
-
setSigningAlgorithm
public void setSigningAlgorithm(HashingAlgorithm x)
- Parameters:
x
- Signing algorithm to use. Defaults toHashingAlgorithm.SHA256
.- See Also:
DEFAULT_SIGNING_ALGORITHM
-
withSigningAlgorithm
public Encryptor withSigningAlgorithm(HashingAlgorithm x)
- See Also:
setSigningAlgorithm(HashingAlgorithm)
-
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
public Encryptor withSymmetricPassphraseChars(char[] x)
- See Also:
setSymmetricPassphraseChars(char[])
-
getSymmetricPassphrase
public java.lang.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:
getSymmetricPassphraseChars()
-
setSymmetricPassphrase
public void setSymmetricPassphrase(java.lang.String x)
- 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:
setSymmetricPassphraseChars(char[])
-
withSymmetricPassphrase
public Encryptor withSymmetricPassphrase(java.lang.String x)
- See Also:
setSymmetricPassphrase(String)
-
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:
DEFAULT_KEY_DERIVATION_ALGORITHM
-
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 toHashingAlgorithm.SHA512
.- See Also:
DEFAULT_KEY_DERIVATION_ALGORITHM
-
withDeriviationAlgorithm
public Encryptor withDeriviationAlgorithm(HashingAlgorithm x)
-
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:
DEFAULT_KEY_DERIVATION_ALGORITHM_WORK_FACTOR
-
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:
DEFAULT_KEY_DERIVATION_ALGORITHM_WORK_FACTOR
-
withKeyDeriviationWorkFactor
public Encryptor withKeyDeriviationWorkFactor(int x)
- See Also:
setKeyDeriviationWorkFactor(int)
-
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:
DEFAULT_MAX_FILE_BUFFER_SIZE
-
withMaxFileBufferSize
public Encryptor withMaxFileBufferSize(int maxFileBufferSize)
- See Also:
setMaxFileBufferSize(int)
-
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:
setRing(Ring)
-
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:
setLoggingEnabled(boolean)
-
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(java.io.File plaintext, java.io.File ciphertext) throws java.io.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:
java.io.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(java.nio.file.Path plaintext, java.nio.file.Path ciphertext) throws java.io.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:
java.io.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 java.io.InputStream wrapSourceInputStream(java.io.InputStream sourceStream, long inputSize) throws java.io.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:
java.io.IOException
- If failed to generate the wrapper
-
wrapTargetOutputStream
public java.io.OutputStream wrapTargetOutputStream(java.io.OutputStream targetStream, long inputSize) throws java.io.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:
java.io.IOException
- If failed to generate the wrapper- See Also:
estimateOutFileBufferSize(long)
-
encryptBytes
public FileMetadata encryptBytes(byte[] data, java.lang.String name, java.io.File ciphertext) throws java.io.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:
java.io.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, java.lang.String name, java.nio.file.Path ciphertext) throws java.io.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:
java.io.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, java.lang.String name, java.io.OutputStream ciphertext) throws java.io.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:
java.io.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(java.io.InputStream plaintext, java.io.OutputStream ciphertext) throws java.io.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:
java.io.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(java.io.InputStream plaintext, java.io.OutputStream ciphertext, FileMetadata meta) throws java.io.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:
java.io.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 java.io.OutputStream prepareCiphertextOutputStream(FileMetadata plainMeta, java.io.File ciphertext) throws java.io.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:
java.io.IOException
- If failed to wrap the streamorg.bouncycastle.openpgp.PGPException
- If failed to apply a PGP wrapper
-
prepareCiphertextOutputStream
public java.io.OutputStream prepareCiphertextOutputStream(FileMetadata plainMeta, java.nio.file.Path ciphertext) throws java.io.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:
java.io.IOException
- If failed to wrap the streamorg.bouncycastle.openpgp.PGPException
- If failed to apply a PGP wrapper
-
prepareCiphertextOutputStream
public java.io.OutputStream prepareCiphertextOutputStream(java.io.OutputStream ciphertext, FileMetadata meta, boolean closeOriginal) throws java.io.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:
java.io.IOException
- If failed to wrap the streamorg.bouncycastle.openpgp.PGPException
- If failed to apply a PGP wrapper
-
pipeline
protected java.io.OutputStream pipeline(java.io.OutputStream out, java.util.List<java.io.OutputStream> stack)
Pushes output stream onto stack if not null, and returns top of stack.
-
armor
protected java.io.OutputStream armor(java.io.OutputStream out, FileMetadata meta)
Wraps with stream that outputs ASCII-armored text - including configuring its armor headers.- Parameters:
meta
- The input plaintextFileMetadata
- might be empty (but notnull
).out
- TheOutputStream
to wrap- Returns:
- The wrapped output stream -
null
if no wrapping. - See Also:
isAsciiArmored()
,isRemoveDefaultArmoredVersionHeader()
,setArmoredHeaders
,addArmoredHeaders
,updateArmoredHeader
,setArmorHeadersCallback(EncryptedAsciiArmorHeadersCallback)
-
encrypt
protected java.io.OutputStream encrypt(java.io.OutputStream out, FileMetadata meta) throws java.io.IOException, org.bouncycastle.openpgp.PGPException
Wraps with stream that outputs encrypted data packet.- Throws:
java.io.IOException
org.bouncycastle.openpgp.PGPException
-
compress
protected java.io.OutputStream compress(java.io.OutputStream out, FileMetadata meta) throws java.io.IOException, org.bouncycastle.openpgp.PGPException
Wraps with stream that outputs compressed data packet.- Throws:
java.io.IOException
org.bouncycastle.openpgp.PGPException
-
packet
protected java.io.OutputStream packet(java.io.OutputStream out, FileMetadata meta) throws java.io.IOException, org.bouncycastle.openpgp.PGPException
Wraps with stream that ouputs literal data packet.- Throws:
java.io.IOException
org.bouncycastle.openpgp.PGPException
-
sign
protected Encryptor.SigningOutputStream sign(java.io.OutputStream out, FileMetadata meta) throws java.io.IOException, org.bouncycastle.openpgp.PGPException
Wraps with stream that outputs signature packets as header and footer to envelope.- Throws:
java.io.IOException
org.bouncycastle.openpgp.PGPException
-
copy
protected long copy(java.io.InputStream i, java.io.OutputStream o, Encryptor.SigningOutputStream s, FileMetadata meta) throws java.io.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 ciphertext {@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:
java.io.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:
getMaxFileBufferSize()
-
clone
public Encryptor clone()
- Overrides:
clone
in classjava.lang.Object
-
-