Hugh.C
5 years ago
1 changed files with 74 additions and 0 deletions
@ -0,0 +1,74 @@
|
||||
package com.fr.third.com.lowagie.text.pdf; |
||||
|
||||
import com.fr.third.com.lowagie.text.Document; |
||||
import com.fr.third.com.lowagie.text.DocumentException; |
||||
import com.fr.third.com.lowagie.text.Paragraph; |
||||
import com.fr.third.com.lowagie.text.exceptions.BadPasswordException; |
||||
import java.io.ByteArrayOutputStream; |
||||
import java.io.IOException; |
||||
import org.junit.Test; |
||||
|
||||
import static junit.framework.TestCase.assertTrue; |
||||
import static org.junit.Assert.fail; |
||||
|
||||
/** |
||||
* @author Hugh.C |
||||
* @version 1.0 |
||||
* Created by Hugh.C on 2020/4/28 |
||||
*/ |
||||
public class PdfEncryptDecryptTest { |
||||
|
||||
@Test |
||||
public void testPdfEncryption() { |
||||
|
||||
try { |
||||
byte[] bytes = createPdfEncryptionDocumentByteArray("123"); |
||||
assertTrue(bytes.length > 0); |
||||
} catch (Exception e) { |
||||
fail(); |
||||
} |
||||
} |
||||
|
||||
@Test |
||||
public void testPdfDecrypt() { |
||||
|
||||
try { |
||||
//沒報錯,解密成功
|
||||
new PdfReader(createPdfEncryptionDocumentByteArray("123"), "123".getBytes()); |
||||
} catch (Exception e) { |
||||
fail(); |
||||
} |
||||
|
||||
boolean result = false; |
||||
try { |
||||
//報錯,解密失敗
|
||||
new PdfReader(createPdfEncryptionDocumentByteArray("123"), "234".getBytes()); |
||||
} catch (Exception e) { |
||||
assertTrue(e instanceof BadPasswordException); |
||||
result = true; |
||||
} |
||||
assertTrue(result); |
||||
} |
||||
|
||||
/** |
||||
* 創建加密過後的pdf document 數組 |
||||
* |
||||
* @param passWord pdf密碼 |
||||
* @return |
||||
* @throws DocumentException |
||||
* @throws IOException |
||||
*/ |
||||
private byte[] createPdfEncryptionDocumentByteArray(String passWord) throws DocumentException, IOException { |
||||
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); |
||||
Document document = new Document(); |
||||
PdfWriter write = PdfWriter.getInstance(document, byteOutputStream); |
||||
String userPassword = "老王"; |
||||
write.setEncryption(userPassword.getBytes(), passWord.getBytes(), PdfWriter.ALLOW_ASSEMBLY, PdfWriter.ENCRYPTION_AES_128); |
||||
document.open(); |
||||
document.add(new Paragraph("ABCDEFG")); |
||||
document.close(); |
||||
write.close(); |
||||
byteOutputStream.flush(); |
||||
return byteOutputStream.toByteArray(); |
||||
} |
||||
} |
Loading…
Reference in new issue