java 用于加密/解密pdf文件的Java API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3676004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java API for encrypting / decrypting pdf files
提问by DG.
I need to encrypt and decrypt pdf files. Is there a free or low cost Java API that does that ? Basically I need to hide files from normal users. Any other suggestion on achieving that programatically ?
我需要加密和解密pdf文件。是否有免费或低成本的 Java API 可以做到这一点?基本上我需要对普通用户隐藏文件。关于以编程方式实现这一目标的任何其他建议?
Thanks, Deep
谢谢,深
采纳答案by Frederik
Using iText:
使用iText:
// Assuming you provide the following yourself:
File inputFile;
File outputFile;
String userPassword;
String ownerPassword;
// A bit-field containing file permissions.
int permissions = PDFWriter.ALLOW_PRINTING | PDFWriter.ALLOW_COPY;
PdfReader reader = new PdfReader(inputFile);
PdfEncryptor.encrypt(reader, new FileOutputStream(outputFile),
ENCRYPTION_AES128, userPassword, ownerPassword,
permissions);
Here's the API for PDFEncryptorand PDFWriter(for the permissions).
这是PDFEncryptor和PDFWriter的 API (用于权限)。
回答by Anthony O.
Using PDFBox(based on Decrypt.javacode) :
使用PDFBox(基于Decrypt.java代码):
PDDocument document = null;
try
{
document = PDDocument.load( infile );
if( document.isEncrypted() )
{
DecryptionMaterial decryptionMaterial = null;
decryptionMaterial = new StandardDecryptionMaterial(password);
document.openProtection(decryptionMaterial);
AccessPermission ap = document.getCurrentAccessPermission();
if(ap.isOwnerPermission())
{
document.setAllSecurityToBeRemoved(true);
document.save( outfile );
}
else
{
throw new IOException(
"Error: You are only allowed to decrypt a document with the owner password." );
}
}
else
{
System.err.println( "Error: Document is not encrypted." );
}
}
finally
{
if( document != null )
{
document.close();
}
}