Link to home
Start Free TrialLog in
Avatar of mrkkishore
mrkkishore

asked on

PDF Encryption With Certificate

I am using the Itext second edition example, and getting an error like
Exception in thread "main" ExceptionConverter: java.security.InvalidKeyException: Illegal key size or default parameters
      at javax.crypto.Cipher.a(DashoA12275)
      at javax.crypto.Cipher.a(DashoA12275)
      at javax.crypto.Cipher.a(DashoA12275)
      at javax.crypto.Cipher.init(DashoA12275)
      at javax.crypto.Cipher.init(DashoA12275)
      at com.lowagie.text.pdf.PdfPublicKeySecurityHandler.computeRecipientInfo(Unknown Source)
      at com.lowagie.text.pdf.PdfPublicKeySecurityHandler.createDERForRecipient(Unknown Source)
      at com.lowagie.text.pdf.PdfPublicKeySecurityHandler.getEncodedRecipient(Unknown Source)
      at com.lowagie.text.pdf.PdfEncryption.getEncryptionDictionary(Unknown Source)
      at com.lowagie.text.pdf.PdfWriter.setEncryption(Unknown Source)
      at com.oracle.etm.wss.EncryptWithCertificate.createPdf(EncryptWithCertificate.java:57)
      at com.oracle.etm.wss.EncryptWithCertificate.main(EncryptWithCertificate.java:143)

I have added the key.properties,
Downloaded foobar.cer and CA3TKQ41.keystore from  http://itextpdf.com/examples/

Please help me as it is very urgent.

Thank You





package com.oracle.etm.wss;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Properties;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;

public class EncryptWithCertificate {

    /** The resulting PDF */
    public static String RESULT1 = "c:\\kishore\\certificate_encryption.pdf";
    /** The resulting PDF */
    public static String RESULT2 = "c:\\kishore\\certificate_decrypted.pdf";
    /** The resulting PDF */
    public static String RESULT3 = "c:\\kishore\\certificate_encrypted.pdf";

    /**
     * A properties file that is PRIVATE.
     * You should make your own properties file and adapt this line.
     */
    public static String PATH = "c:\\kishore\\key.properties";
    /** Some properties used when signing. */
    public static Properties properties = new Properties();
    
    /**
     * Creates a PDF that is encrypted using two different public certificates.
     * @param filename the path to the resulting PDF file
     * @throws IOException
     * @throws DocumentException
     * @throws GeneralSecurityException
     */
    public void createPdf(String filename)
        throws IOException, DocumentException, GeneralSecurityException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT1));
        Certificate cert1 = getPublicCertificate("c:\\kishore\\foobar.cer");
        Certificate cert2 = getPublicCertificate(properties.getProperty("PUBLIC"));
        writer.setEncryption(new Certificate[]{cert1,cert2},
            new int[]{PdfWriter.ALLOW_PRINTING, PdfWriter.ALLOW_COPY}, PdfWriter.ENCRYPTION_AES_128);
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph("Hello World!"));
        // step 5
        document.close();
    }
    
    /**
     * Gets a public certificate from a certificate file.
     * @param path the path to the certificate
     * @return a Certificate object
     * @throws IOException
     * @throws CertificateException
     */
    public Certificate getPublicCertificate(String path)
        throws IOException, CertificateException {
        FileInputStream is = new FileInputStream(path);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
        return cert;
    }
    
    /**
     * Gets a private key from a KeyStore.
     * @return a PrivateKey object
     * @throws GeneralSecurityException
     * @throws IOException
     */
    public PrivateKey getPrivateKey() throws GeneralSecurityException, IOException {
        String path = "c:\\kishore\\.keystore";
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(path), "f00b4r".toCharArray());
        PrivateKey pk = (PrivateKey)ks.getKey("foobar", "f1lmf3st".toCharArray());
        return pk;
    }
    
    /**
     * Decrypts a PDF that was encrypted using a certificate
     * @param src  The encrypted PDF
     * @param dest The decrypted PDF
     * @throws IOException
     * @throws DocumentException
     * @throws GeneralSecurityException
     */
    public void decryptPdf(String src, String dest)
        throws IOException, DocumentException, GeneralSecurityException {
        PdfReader reader = new PdfReader(src,
            getPublicCertificate("c:\\kishore\\foobar.cer"), getPrivateKey(), "BC");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        stamper.close();
    }
    
    /**
     * Encrypts a PDF using a public certificate.
     * @param src  The original PDF document
     * @param dest The encrypted PDF document
     * @throws IOException
     * @throws DocumentException
     * @throws CertificateException
     */
    public void encryptPdf(String src, String dest)
        throws IOException, DocumentException, CertificateException {
        PdfReader reader = new PdfReader(src);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        Certificate cert = getPublicCertificate("c:\\kishore\\foobar.cer");
        stamper.setEncryption(new Certificate[]{cert},
            new int[]{PdfWriter.ALLOW_PRINTING}, PdfWriter.ENCRYPTION_AES_128);
        stamper.close();
    }

    /**
     * Main method.
     *
     * @param    args    no arguments needed
     * @throws DocumentException 
     * @throws IOException
     * @throws GeneralSecurityException 
     */
    public static void main(String[] args)
        throws IOException, DocumentException, GeneralSecurityException {
        Security.addProvider(new BouncyCastleProvider());
        properties.load(new FileInputStream(PATH));
        EncryptWithCertificate hello = new EncryptWithCertificate();
        hello.createPdf(RESULT1);
        hello.decryptPdf(RESULT1, RESULT2);
        hello.encryptPdf(RESULT2, RESULT3);
    }
}

Open in new window

Avatar of Mick Barry
Mick Barry
Flag of Australia image

Perhaps this may help - long trail but similar error in the end resolved:

http://www.coderanch.com/t/448228/Security/Exception-thread-main-java-security
Avatar of mrkkishore
mrkkishore

ASKER

I went to these sites, I downloaded JCE.jar file and replaced with existing JCE jar file.Still I am getting the same error.
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
So many separate cases where these replaced jar's seemed to have helped, perhaps you want to check that you placed them correctly, like
in the end of this trail
http://www.coderanch.com/t/448228/Security/Exception-thread-main-java-security 

they say "That's not how you install them - the process is described in the documentation that comes with the download. "
Perhaps, it would be good idea to double check that.
Sorry for late response..I installed two jar files local_policy.jar,US_export_policy.jar and I now I am not getting that error message. But still I am getting NoClassFound exception which I am working onit. I know this is rlated to class path .What one thing i am not getting is , I am able to execute other classes from this package except this program.  

 java.lang.NoClassDefFoundError: com/oracle/etm/wss/EncryptWithCertificate
Exception in thread "main"
It cannot find this very class which you posted the code  - maybe it is in the wrong directory tree, hoe do you excute this program - from which directory, where is this class?
Do you have it in jar? Or you have it as a class file? What is your CLASSPATH, what is your OS - with all detailes we definitely should figure it out.
if you create this tree
com/oracle/etm/wss/

and place EncryptWithCertificate.class into this folder com/oracle/etm/wss/

then from  the one level higher folder you should be able to execute:

java com.oracle.etm.wss.EncryptWithCertificate  

I have it as a class file.

C:\etm\java\jdk1.5.0_18

My OS is WindowsXP




How do you start your excution - as the command line from cmd window ?
What is the command?
I am running this in Eclipse3.4.1
Then you should see this your class in the package in your project
and in theRun Configurations window you should see com.oracle.etm.wss.EncryptWithCertificate   in the Main class window
Do you do it this way?
And on the right side in Package Explorer you should see package com, when you open it you should see oracle, then etm, then wss
and in wss there should be your EncryptWithCertificate.java
Thank you guys, It is working..I just re-build,clean the project and it started working...
> I have it as a class file.
> C:\etm\java\jdk1.5.0_18

Not a good place to put your class files
And not a good package name to use

installing the jars would not cause the error you are getting, check you haven't changed anything else.

To run it simply right click on the file and select Run As>Java application
Great!
my class files are in wss\build\classes..I think I have given you the wrong build path ..
you shouldn't need to specify it, source folders get included automatically
Not a direct answer.