一、前言
下面通过pdfbox的org.apache.pdfbox.pdmodel.PDDocument的pdf文件实现了分别对内容基于org.apache.pdfbox.tools.Encrypt加密、org.apache.pdfbox.tools.Decrypt进行pdf解密后存入PDF文件的代码示例。
二、代码示例
1.Encrypt加密代码示例
package org.apache.pdfbox.tools;@b@@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.security.cert.CertificateException;@b@import java.security.cert.CertificateFactory;@b@import java.security.cert.X509Certificate;@b@@b@import org.apache.pdfbox.pdmodel.PDDocument;@b@import org.apache.pdfbox.pdmodel.encryption.AccessPermission;@b@import org.apache.pdfbox.pdmodel.encryption.PublicKeyProtectionPolicy;@b@import org.apache.pdfbox.pdmodel.encryption.PublicKeyRecipient;@b@import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;@b@@b@/**@b@ * This will read a document from the filesystem, encrypt it and and then write@b@ * the results to the filesystem.@b@ *@b@ * @author Ben Litchfield@b@ */@b@public final class Encrypt@b@{@b@ private Encrypt()@b@ {@b@ }@b@@b@ /**@b@ * This is the entry point for the application.@b@ *@b@ * @param args The command-line arguments.@b@ *@b@ * @throws IOException If there is an error decrypting the document.@b@ * @throws CertificateException If there is an error with a certificate.@b@ */@b@ public static void main( String[] args ) throws IOException, CertificateException@b@ {@b@ // suppress the Dock icon on OS X@b@ System.setProperty("apple.awt.UIElement", "true");@b@@b@ Encrypt encrypt = new Encrypt();@b@ encrypt.encrypt( args );@b@ }@b@@b@ private void encrypt( String[] args ) throws IOException, CertificateException@b@ {@b@ if( args.length < 1 )@b@ {@b@ usage();@b@ }@b@ else@b@ {@b@ AccessPermission ap = new AccessPermission();@b@@b@ String infile = null;@b@ String outfile = null;@b@ String certFile = null;@b@ String userPassword = "";@b@ String ownerPassword = "";@b@@b@ int keyLength = 40;@b@@b@ PDDocument document = null;@b@@b@ try@b@ {@b@ for( int i=0; i<args.length; i++ )@b@ {@b@ String key = args[i];@b@ if( key.equals( "-O" ) )@b@ {@b@ ownerPassword = args[++i];@b@ }@b@ else if( key.equals( "-U" ) )@b@ {@b@ userPassword = args[++i];@b@ }@b@ else if( key.equals( "-canAssemble" ) )@b@ {@b@ ap.setCanAssembleDocument(args[++i].equalsIgnoreCase( "true" ));@b@ }@b@ else if( key.equals( "-canExtractContent" ) )@b@ {@b@ ap.setCanExtractContent( args[++i].equalsIgnoreCase( "true" ) );@b@ }@b@ else if( key.equals( "-canExtractForAccessibility" ) )@b@ {@b@ ap.setCanExtractForAccessibility( args[++i].equalsIgnoreCase( "true" ) );@b@ }@b@ else if( key.equals( "-canFillInForm" ) )@b@ {@b@ ap.setCanFillInForm( args[++i].equalsIgnoreCase( "true" ) );@b@ }@b@ else if( key.equals( "-canModify" ) )@b@ {@b@ ap.setCanModify( args[++i].equalsIgnoreCase( "true" ) );@b@ }@b@ else if( key.equals( "-canModifyAnnotations" ) )@b@ {@b@ ap.setCanModifyAnnotations( args[++i].equalsIgnoreCase( "true" ) );@b@ }@b@ else if( key.equals( "-canPrint" ) )@b@ {@b@ ap.setCanPrint( args[++i].equalsIgnoreCase( "true" ) );@b@ }@b@ else if( key.equals( "-canPrintDegraded" ) )@b@ {@b@ ap.setCanPrintDegraded( args[++i].equalsIgnoreCase( "true" ) );@b@ }@b@ else if( key.equals( "-certFile" ) )@b@ {@b@ certFile = args[++i];@b@ }@b@ else if( key.equals( "-keyLength" ) )@b@ {@b@ try@b@ {@b@ keyLength = Integer.parseInt( args[++i] );@b@ }@b@ catch( NumberFormatException e )@b@ {@b@ throw new NumberFormatException(@b@ "Error: -keyLength is not an integer '" + args[i] + "'" );@b@ }@b@ }@b@ else if( infile == null )@b@ {@b@ infile = key;@b@ }@b@ else if( outfile == null )@b@ {@b@ outfile = key;@b@ }@b@ else@b@ {@b@ usage();@b@ }@b@ }@b@ if( infile == null )@b@ {@b@ usage();@b@ }@b@ if( outfile == null )@b@ {@b@ outfile = infile;@b@ }@b@ document = PDDocument.load( new File(infile) );@b@@b@ if( !document.isEncrypted() )@b@ {@b@ if( certFile != null )@b@ {@b@ PublicKeyProtectionPolicy ppp = new PublicKeyProtectionPolicy();@b@ PublicKeyRecipient recip = new PublicKeyRecipient();@b@ recip.setPermission(ap);@b@@b@@b@ CertificateFactory cf = CertificateFactory.getInstance("X.509");@b@ @b@ InputStream inStream = null;@b@ try@b@ {@b@ inStream = new FileInputStream(certFile);@b@ X509Certificate certificate = (X509Certificate)cf.generateCertificate(inStream);@b@ recip.setX509(certificate);@b@ }@b@ finally@b@ {@b@ if (inStream != null)@b@ {@b@ inStream.close();@b@ }@b@ } @b@@b@ ppp.addRecipient(recip);@b@@b@ ppp.setEncryptionKeyLength(keyLength);@b@@b@ document.protect(ppp);@b@ }@b@ else@b@ {@b@ StandardProtectionPolicy spp =@b@ new StandardProtectionPolicy(ownerPassword, userPassword, ap);@b@ spp.setEncryptionKeyLength(keyLength);@b@ document.protect(spp);@b@ }@b@ document.save( outfile );@b@ }@b@ else@b@ {@b@ System.err.println( "Error: Document is already encrypted." );@b@ }@b@ }@b@ finally@b@ {@b@ if( document != null )@b@ {@b@ document.close();@b@ }@b@ }@b@ }@b@ }@b@@b@ /**@b@ * This will print a usage message.@b@ */@b@ private static void usage()@b@ {@b@ String message = "Usage: java -jar pdfbox-app-x.y.z.jar Encrypt [options] <inputfile> [outputfile]\n"@b@ + "\nOptions:\n"@b@ + " -O <password> : Set the owner password (ignored if cert is set)\n"@b@ + " -U <password> : Set the user password (ignored if cert is set)\n"@b@ + " -certFile <path to cert> : Path to X.509 certificate\n"@b@ + " -canAssemble <true|false> : Set the assemble permission\n"@b@ + " -canExtractContent <true|false> : Set the extraction permission\n"@b@ + " -canExtractForAccessibility <true|false> : Set the extraction permission\n"@b@ + " -canFillInForm <true|false> : Set the fill in form permission\n"@b@ + " -canModify <true|false> : Set the modify permission\n"@b@ + " -canModifyAnnotations <true|false> : Set the modify annots permission\n"@b@ + " -canPrint <true|false> : Set the print permission\n"@b@ + " -canPrintDegraded <true|false> : Set the print degraded permission\n"@b@ + " -keyLength <length> : The length of the key in bits "@b@ + "(valid values: 40, 128 or 256, default is 40)\n"@b@ + "\nNote: By default all permissions are set to true!";@b@ @b@ System.err.println(message);@b@ System.exit(1);@b@ }@b@@b@}
2.Decrypt解密代码示例
package org.apache.pdfbox.tools;@b@@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@@b@import org.apache.pdfbox.io.IOUtils;@b@import org.apache.pdfbox.pdmodel.PDDocument;@b@import org.apache.pdfbox.pdmodel.encryption.AccessPermission;@b@@b@/**@b@ * This will read a document from the filesystem, decrypt it and and then write@b@ * the result to the filesystem.@b@ *@b@ * @author Ben Litchfield@b@ */@b@public final class Decrypt@b@{@b@ private static final String ALIAS = "-alias";@b@ private static final String PASSWORD = "-password";@b@ private static final String KEYSTORE = "-keyStore";@b@ @b@ private String password;@b@ private String infile;@b@ private String outfile;@b@ private String alias;@b@ private String keyStore;@b@@b@@b@ private Decrypt()@b@ {@b@ }@b@ /**@b@ * This is the entry point for the application.@b@ *@b@ * @param args The command-line arguments.@b@ *@b@ * @throws IOException If there is an error decrypting the document.@b@ */@b@ public static void main(String[] args) throws IOException@b@ {@b@ // suppress the Dock icon on OS X@b@ System.setProperty("apple.awt.UIElement", "true");@b@@b@ Decrypt decrypt = new Decrypt();@b@ decrypt.parseCommandLineArgs(args);@b@ decrypt.decrypt();@b@ }@b@ @b@ private void parseCommandLineArgs(String[] args)@b@ {@b@ if( args.length < 1 || args.length > 8 )@b@ {@b@ usage();@b@ }@b@ else@b@ {@b@ for( int i=0; i<args.length; i++ )@b@ {@b@ if( args[i].equals( ALIAS ) )@b@ {@b@ i++;@b@ if( i >= args.length )@b@ {@b@ usage();@b@ }@b@ alias = args[i];@b@ }@b@ else if( args[i].equals( KEYSTORE ) )@b@ {@b@ i++;@b@ if( i >= args.length )@b@ {@b@ usage();@b@ }@b@ keyStore = args[i];@b@ }@b@ else if( args[i].equals( PASSWORD ) )@b@ {@b@ i++;@b@ if( i >= args.length )@b@ {@b@ usage();@b@ }@b@ password = args[i];@b@ }@b@ else if( infile == null )@b@ {@b@ infile = args[i];@b@ }@b@ else if( outfile == null )@b@ {@b@ outfile = args[i];@b@ }@b@ else@b@ {@b@ usage();@b@ }@b@ }@b@ if( infile == null )@b@ {@b@ usage();@b@ }@b@ if( outfile == null )@b@ {@b@ outfile = infile;@b@ }@b@ if( password == null )@b@ {@b@ password = "";@b@ }@b@ }@b@ }@b@@b@ private void decrypt() throws IOException@b@ {@b@ PDDocument document = null;@b@ InputStream keyStoreStream = null;@b@ try@b@ {@b@ if( keyStore != null )@b@ {@b@ keyStoreStream = new FileInputStream(keyStore);@b@ }@b@ document = PDDocument.load(new File(infile), password, keyStoreStream, alias);@b@ @b@ if (document.isEncrypted())@b@ {@b@ AccessPermission ap = document.getCurrentAccessPermission();@b@ if(ap.isOwnerPermission())@b@ {@b@ document.setAllSecurityToBeRemoved(true);@b@ document.save( outfile );@b@ }@b@ else@b@ {@b@ throw new IOException(@b@ "Error: You are only allowed to decrypt a document with the owner password." );@b@ }@b@ }@b@ else@b@ {@b@ System.err.println( "Error: Document is not encrypted." );@b@ }@b@ }@b@ finally@b@ {@b@ if( document != null )@b@ {@b@ document.close();@b@ }@b@ IOUtils.closeQuietly(keyStoreStream);@b@ }@b@ }@b@@b@ /**@b@ * This will print a usage message.@b@ */@b@ private static void usage()@b@ {@b@ @b@ String message = "Usage: java -jar pdfbox-app-x.y.z.jar Decrypt [options] <inputfile> [outputfile]\n"@b@ + "\nOptions:\n"@b@ + " -alias : The alias of the key in the certificate file (mandatory if several keys are available\n"@b@ + " -password : The password to open the certificate and extract the private key from it.\n"@b@ + " -keyStore : The KeyStore that holds the certificate.";@b@ @b@ System.err.println(message);@b@ System.exit(1);@b@ }@b@@b@}