Class PublicKeyEncryptionHandler
- java.lang.Object
-
- org.faceless.pdf2.EncryptionHandler
-
- org.faceless.pdf2.PublicKeyEncryptionHandler
-
- All Implemented Interfaces:
Cloneable
- Direct Known Subclasses:
PublicKeyPromptEncryptionHandler
public class PublicKeyEncryptionHandler extends EncryptionHandler
The PublicKeyEncryptionHandler can be used to encrypt and decrypt documents using public/private key Encryption, so documents can only be opened by someone in posession of the private key. This form of encryption requires key management so is not as widely supported as password encryption, however dedicated PDF viewers (including Acrobat and Foxit) should support it.
To encrypt a document you need the X.509 certificates of the recipients - multiple recipients are allowed. RSA and (since 2.28.5) Elliptic Curve keys are supported.
Typically you'd get this from KeyStore, as in this example:
KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream("keystore.p12"), "password".toCharArray()); X509Certificate cert = (X509Certificate)keystore.getCertificate("john"); PublicKeyEncryptionHandler handler = new PublicKeyEncryptionHandler(PublicKeyEncryptionHandler.METHOD_AES256); handler.addRecipient(cert, StandardEncryptionHandler.PRINT_HIGHRES, StandardEncryptionHandler.CHANGE_ALL, StandardEncryptionHandler.EXTRACT_ALL); pdf.setEncryptionHandler(handler);Other ways to get a certificate include using the
FormSignature.loadPKCS7KeyStore(java.io.InputStream)method to load your X.509 certificates from a PKCS#7 object, or theCertificateFactoryclass to load the certificate from.cerfiles exported by Acrobat:FileInputStream fis = new FileInputStream("certificate.cer"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)cf.generateCertificate(fis);To decrypt a document, you will need a
KeyStorecontaining a private key that matches a public key used to encrypt the document.KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream("keystore.p12"), "storepassword".toCharArray()); EncryptionHandler handler = new PublicKeyEncryptionHandler(keystore, null, "keypassword".toCharArray()); PDF pdf = new PDF(new PDFReader(new File("encrypted.pdf"), handler));- Since:
- 2.2.5
- See Also:
PDFReader(InputStream,EncryptionHandler),StandardEncryptionHandler
-
-
Field Summary
Fields Modifier and Type Field Description static intMETHOD_AES128A constant that can be passed to theconstructorto encrypt using the 128-bit AES ciphers defined in PDF 1.6 and supported in Acrobat 7 First added to the API in 2.8.2static intMETHOD_AES256A constant that can be passed to theconstructorto encrypt using the 256-bit AES ciphers defined in PDF 2.0 (ISO 32000-2)static intMETHOD_AES256_GCMA constant that can be passed to theconstructorto encrypt using the 256-bit AES ciphers in Galois Counter Mode, defined in ISO 32003.static intMETHOD_RC4_3DES128A constant that can be passed to theconstructorto encrypt using the 128-bit RC4/3DES ciphers defined in PDF 1.5 and supported in Acrobat 6 First added to the API in 2.2.5static intMETHOD_RC4_3DES128_OLDA constant that can be passed to theconstructorto encrypt using the 128-bit RC4/3DES ciphers and the original method defined in PDF 1.4 and supported in Acrobat 5.
-
Constructor Summary
Constructors Constructor Description PublicKeyEncryptionHandler()Create a new PublicKeyEncryptionHandler for decrypting a document encrypted with theAdobe.PubSecpublic key encryption handler.PublicKeyEncryptionHandler(int method)Create a new PublicKeyEncryptionHandler for encrypting a document.PublicKeyEncryptionHandler(KeyStore keystore, String alias, char[] password)Create a new PublicKeyEncryptionHandler for decrypting a document encrypted with theAdobe.PubSecpublic key encryption handler.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddRecipient(X509Certificate recipient, int print, int extraction, int change)Add a recipient to the list of people that can open the documentprotected booleanchooseRecipient(X500Principal[] issuers, BigInteger[] serials)This method is called byprepareToDecrypt()to give an implementation the chance to select an appropriate entry from the KeyStore if it hasn't already been done.voidfinishedDecrypt()This method is called after the PDF has been read.voidfinishedEncrypt()This method is called after the PDF has been written.intgetChange()Return the value of the "Change" flags.InputStreamgetDecryptionStream(InputStream in, int num, int gen)Return aFilterInputStreamthat will decrypt anything read from it.StringgetDescription()Return a textual description of the encryption usedintgetEncryptedStreamLength(int len)Return the length that a stream of the specified length would be after encryption.OutputStreamgetEncryptionStream(OutputStream out, int num, int gen)Return aFilterOutputStreamthat will encrypt anything written to it.intgetExtract()Return the value of the "Extract" flags.StringgetFilterName()Return the name of the "Filter" field in the Encryption dictionary.intgetPrint()Return the value of the "Print" flags.StringgetSubFilterName()Return the name of the "Subfilter" field in the Encryption dictionary.booleanhasRight(String right)Returns true if the EncryptionHandler wil grant the specified right to the PDF library.booleanisMetadataEncrypted()This method returns true if XMP MetaData should be stored encrypted, or false otherwise.booleanisRequired()This method should returntrueif the document needs to be encrypted.voidprepareToDecrypt()This method is called just before the PDF is read in.voidprepareToEncrypt()This method is called when the PDF is about to be written out.voidsetDecryptionKey(KeyStore keystore, String alias, char[] password)Set the private key to use to decrypt the documentvoidsetDecryptionKey(KeyStore keystore, String alias, KeyStore.ProtectionParameter protection)Set the private key to use to decrypt the documentvoidsetEncryptedMetadata(boolean encrypt)Set whether XMP Metadata is to be encrypted or not.-
Methods inherited from class org.faceless.pdf2.EncryptionHandler
clone, containsKey, getArrayValueSize, getBooleanValue, getDecryptedStreamLength, getDictionaryValueKeys, getFileId, getIntegerValue, getNameValue, getNumericValue, getStringValue, getTextStringValue, isChanged, isEmbeddedFileEncrypted, isStreamEncrypted, isStringEncrypted, markChanged, putArrayValue, putBooleanValue, putDictionaryValue, putNameValue, putNumericValue, putStringValue, putTextStringValue, setFileId
-
-
-
-
Field Detail
-
METHOD_RC4_3DES128_OLD
public static final int METHOD_RC4_3DES128_OLD
A constant that can be passed to theconstructorto encrypt using the 128-bit RC4/3DES ciphers and the original method defined in PDF 1.4 and supported in Acrobat 5.- Since:
- 2.2.5, with the constant added in 2.28.5
- See Also:
- Constant Field Values
-
METHOD_RC4_3DES128
public static final int METHOD_RC4_3DES128
A constant that can be passed to theconstructorto encrypt using the 128-bit RC4/3DES ciphers defined in PDF 1.5 and supported in Acrobat 6 First added to the API in 2.2.5- Since:
- 2.2.5, with the constant added in 2.28.5
- See Also:
- Constant Field Values
-
METHOD_AES128
public static final int METHOD_AES128
A constant that can be passed to theconstructorto encrypt using the 128-bit AES ciphers defined in PDF 1.6 and supported in Acrobat 7 First added to the API in 2.8.2- Since:
- 2.8.2, with the constant added in 2.28.5
- See Also:
- Constant Field Values
-
METHOD_AES256
public static final int METHOD_AES256
A constant that can be passed to theconstructorto encrypt using the 256-bit AES ciphers defined in PDF 2.0 (ISO 32000-2)- Since:
- 2.28.5
- See Also:
- Constant Field Values
-
METHOD_AES256_GCM
public static final int METHOD_AES256_GCM
A constant that can be passed to theconstructorto encrypt using the 256-bit AES ciphers in Galois Counter Mode, defined in ISO 32003.- Since:
- 2.28.5
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
PublicKeyEncryptionHandler
public PublicKeyEncryptionHandler()
Create a new PublicKeyEncryptionHandler for decrypting a document encrypted with theAdobe.PubSecpublic key encryption handler. This constructor must be followed by a call tosetDecryptionKey().- Since:
- 2.8.2
-
PublicKeyEncryptionHandler
public PublicKeyEncryptionHandler(KeyStore keystore, String alias, char[] password) throws GeneralSecurityException
Create a new PublicKeyEncryptionHandler for decrypting a document encrypted with theAdobe.PubSecpublic key encryption handler.- Parameters:
keystore- the KeyStore containing the private key to decrypt the document withalias- the alias of the key to use, ornullto use the first key that fitspassword- the password to decrypt the private key, ornullif no password is required- Throws:
GeneralSecurityException- Since:
- 2.2.5
-
PublicKeyEncryptionHandler
public PublicKeyEncryptionHandler(int method)
Create a new PublicKeyEncryptionHandler for encrypting a document. Recipients can be added using theaddRecipient()method. The parameter should be one of theMETHODconstants defined in this class (prior to release 2.28.5 the supplied value was an "acrobat version number", but it has been redefined using these constants)- Parameters:
method- one ofMETHOD_RC4_3DES128_OLD,METHOD_RC4_3DES128,METHOD_AES128,METHOD_AES256orMETHOD_AES256_GCM- Since:
- 2.2.5
-
-
Method Detail
-
setEncryptedMetadata
public void setEncryptedMetadata(boolean encrypt)
Set whether XMP Metadata is to be encrypted or not. Unencrypted Metadata is supported by Acrobat 6.0 and later.- Parameters:
encrypt- whether to encrypt the XMP Metadata when saving the file.- Since:
- 2.8.2
-
setDecryptionKey
public void setDecryptionKey(KeyStore keystore, String alias, char[] password) throws GeneralSecurityException
Set the private key to use to decrypt the document- Parameters:
keystore- the KeyStore containing the private key to decrypt the document withalias- the alias of the key to use, ornullto use the first key that fitspassword- the password to decrypt the private key, ornullif no password is required- Throws:
GeneralSecurityException- Since:
- 2.8.2
-
setDecryptionKey
public void setDecryptionKey(KeyStore keystore, String alias, KeyStore.ProtectionParameter protection) throws GeneralSecurityException
Set the private key to use to decrypt the document- Parameters:
keystore- the KeyStore containing the private key to decrypt the document withalias- the alias of the key to use, ornullto use the first key that fitsprotection- theKeyStore.ProtectionParameterused to decrypt the password- Throws:
GeneralSecurityException- Since:
- 2.28.5
-
addRecipient
public void addRecipient(X509Certificate recipient, int print, int extraction, int change)
Add a recipient to the list of people that can open the document- Parameters:
recipient- the X.509 certificate of the recipientprint- one ofStandardEncryptionHandler.PRINT_NONEStandardEncryptionHandler.PRINT_LOWRESStandardEncryptionHandler.PRINT_HIGHRESextraction- one ofStandardEncryptionHandler.EXTRACT_NONEStandardEncryptionHandler.EXTRACT_ACCESSIBILITYStandardEncryptionHandler.EXTRACT_ALLchange- one ofStandardEncryptionHandler.CHANGE_NONEStandardEncryptionHandler.CHANGE_LAYOUTStandardEncryptionHandler.CHANGE_FORMSStandardEncryptionHandler.CHANGE_ANNOTATIONSStandardEncryptionHandler.CHANGE_ALL- Since:
- 2.2.5
-
getChange
public int getChange()
Return the value of the "Change" flags. Only valid after decrypting a document.
-
getExtract
public int getExtract()
Return the value of the "Extract" flags. Only valid after decrypting a document.- Returns:
- one of
StandardEncryptionHandler.EXTRACT_NONEStandardEncryptionHandler.EXTRACT_ACCESSIBILITYStandardEncryptionHandler.EXTRACT_ALL - Since:
- 2.6.5
-
getPrint
public int getPrint()
Return the value of the "Print" flags. Only valid after decrypting a document.- Returns:
- one of
StandardEncryptionHandler.PRINT_NONEStandardEncryptionHandler.PRINT_LOWRESStandardEncryptionHandler.PRINT_HIGHRES - Since:
- 2.6.5
-
hasRight
public boolean hasRight(String right)
Description copied from class:EncryptionHandlerReturns true if the EncryptionHandler wil grant the specified right to the PDF library. The default implementation of this method returns true, but subclasses will override this method based on the rights applied to the document. This method should always returnsuper.hasRight()if it doesn't recognise the value of "right"- Overrides:
hasRightin classEncryptionHandler- Parameters:
right- an interned() String defining the usage right the PDF library is querying.
-
getFilterName
public String getFilterName()
Description copied from class:EncryptionHandlerReturn the name of the "Filter" field in the Encryption dictionary. This is used to determine whether an appropriate filter has been supplied by the decryption process. For example, theStandardEncryptionHandlerclass returns "Standard" from this method.- Specified by:
getFilterNamein classEncryptionHandler
-
getSubFilterName
public String getSubFilterName()
Description copied from class:EncryptionHandlerReturn the name of the "Subfilter" field in the Encryption dictionary. This is used to determine whether an appropriate filter has been supplied by the decryption process. As "Subfilter" is an optional field, this method may returnnull.- Specified by:
getSubFilterNamein classEncryptionHandler
-
getDescription
public String getDescription()
Return a textual description of the encryption used- Since:
- 2.8.2
-
isRequired
public boolean isRequired()
Description copied from class:EncryptionHandlerThis method should returntrueif the document needs to be encrypted. For example, theStandardEncryptionHandlerreturnsfalsehere if and only if no passwords are set and the document is set to allow full access.- Specified by:
isRequiredin classEncryptionHandler
-
isMetadataEncrypted
public boolean isMetadataEncrypted()
Description copied from class:EncryptionHandlerThis method returns true if XMP MetaData should be stored encrypted, or false otherwise. The default implementation returns true, subclasses should override as necessary.- Overrides:
isMetadataEncryptedin classEncryptionHandler
-
getEncryptedStreamLength
public int getEncryptedStreamLength(int len)
Description copied from class:EncryptionHandlerReturn the length that a stream of the specified length would be after encryption. Generally this will be the same same as the input length (and that's what this method returns, unless overridden), but for some Encryption algorithms like AES, the size may be rounded up to the nearest block size.- Overrides:
getEncryptedStreamLengthin classEncryptionHandler
-
getEncryptionStream
public OutputStream getEncryptionStream(OutputStream out, int num, int gen)
Description copied from class:EncryptionHandlerReturn aFilterOutputStreamthat will encrypt anything written to it. The encryption parameters are set inEncryptionHandler.prepareToEncrypt(), which is called once at the start of the render.- Specified by:
getEncryptionStreamin classEncryptionHandler- Parameters:
out- the OuptutStream that should be written tonum- the object number of the top-level objectgen- the generation number of the top-level object
-
getDecryptionStream
public InputStream getDecryptionStream(InputStream in, int num, int gen)
Description copied from class:EncryptionHandlerReturn aFilterInputStreamthat will decrypt anything read from it. The decryption parameters are set inEncryptionHandler.prepareToDecrypt(), which is called once at the start of the PDF read.- Specified by:
getDecryptionStreamin classEncryptionHandler- Parameters:
in- the InputStream that should be read fromnum- the object number of the top-level objectgen- the generation number of the top-level object
-
prepareToDecrypt
public void prepareToDecrypt() throws IOExceptionDescription copied from class:EncryptionHandlerThis method is called just before the PDF is read in. It is expected that this method will read various parameters from theEncryptdictionary by way of the variousget...methods, and use them and the value ofEncryptionHandler.getFileId()to set its internal state so that it's ready to start decryption. It may throw anIOExceptionif these parameters are invalid, in which case the document cannot be read.- Specified by:
prepareToDecryptin classEncryptionHandler- Throws:
IOException
-
chooseRecipient
protected boolean chooseRecipient(X500Principal[] issuers, BigInteger[] serials)
This method is called byprepareToDecrypt()to give an implementation the chance to select an appropriate entry from the KeyStore if it hasn't already been done. The supplied arrays are equal length and indicate the Issuer and SerialNumber of all the recipients that can decrypt this document. By default this method does nothing.- Parameters:
issuers- an array listing all the X.509 Certificate Issuersserials- an array listing all the X.509 Certificate Serial Numbers.- Returns:
- true if the decryption should continue, false otherwise
- Since:
- 2.8.3
-
prepareToEncrypt
public void prepareToEncrypt() throws IOExceptionDescription copied from class:EncryptionHandlerThis method is called when the PDF is about to be written out. It is expected that this method will write various parameters which have been set by the user to theEncryptdictionary (including the "Filter" field) by way of the variousput...methods, and will use these and the value ofEncryptionHandler.getFileId()to set its internal state so that it's ready to start encryption. It may throw anIOExceptionif these parameters are in any way invalid, in which case the document cannot be written.- Specified by:
prepareToEncryptin classEncryptionHandler- Throws:
IOException
-
finishedEncrypt
public void finishedEncrypt()
Description copied from class:EncryptionHandlerThis method is called after the PDF has been written. It may be used to clean up any internal state that needs to be cleaned.- Specified by:
finishedEncryptin classEncryptionHandler
-
finishedDecrypt
public void finishedDecrypt()
Description copied from class:EncryptionHandlerThis method is called after the PDF has been read. It may be used to clean up any internal state that needs to be cleaned.- Specified by:
finishedDecryptin classEncryptionHandler
-
-