Khalil_B
Khalil_B

Reputation: 59

PDF encryption/decryption not working

when i try to encrypt/decrypt a pdf file using bouncycastle this give me an empty pdf (with 184Ko size). the code works perfectly with text file. But no way with PDF file. any one have an idea how to encrypt/decrypt PDF file in Java ?

bellow the code that i use for encryption, i get an exception when i encrypt a PDF file (java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block) in this line cipherText = cipher.doFinal(input) :

     Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] input = acVote;
    byte[] cipherText = null;

    Cipher cipher = null;

    try {
    cipher = Cipher.getInstance("RSA/ECB/OAEPPadding", "BC");

    SecureRandom random = new SecureRandom();

    //do encryption

    cipher.init(Cipher.ENCRYPT_MODE, pubKey, random);

    cipherText = cipher.doFinal(input);
    } catch (Exception ex) {
        log.error("Exeption Message : " + ex);
    }

When i encrypt a .txt file, it works ...

Upvotes: 0

Views: 1525

Answers (2)

plinth
plinth

Reputation: 49179

Here's what you need to decide: do I want an encrypted file or do I want an encrypted PDF? The distinction is important. If you want an encrypted file, that's on you. Possible reasons why you're having problems might include that PDF is frequently part binary, and although that shouldn't make a difference to bouncy castle, it may inform the type of reader you're using for data, for example.

If you're trying to get an encrypted PDF (and I suspect this is what you really want) bouncy castle won't (directly) do that for you.

Instead you need to use iText, a tool based on iText, or another similar library (JoltPdf, for example) which can consume PDF and correctly write encrypted PDF out. Encrypted PDF is a PDF file that is only partially encrypted. The PDF elements of type string and stream will be encrypted using a supplied password, a specified encryption algorithm, and some salt. In addition, depending on the encryption algorithm, the document may get signed, which is its own thing that doesn't follow most typical signing processes.

Under the hood, iText and JoltPdf use bouncy castle to do the hashing, encryption, and signing.

Upvotes: 1

Menskl
Menskl

Reputation: 1

I can just tell you the theory and here it is:

I have encrypted a picture some time ago and I did it by reading the picture into a 2048 huge byt array. After that I split it every 2048 bytes into a single byte file (it was a small picture) and after that I had like 20 files with different names and that was pretty simple but also a good encryption

2nd Method is by using the Caesar Encryption (something like that) which mean that you move every byte 2 places up or down (or more than 2)

Those are my pretty easy but sometimes usefull encryptions :DDDDDDDDDDDDDDD

Upvotes: 0

Related Questions