Solved

PDF Encryption With Certificate

Posted on 2011-02-10
20
1,746 Views
Last Modified: 2012-06-27
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

0
Comment
Question by:mrkkishore
  • 10
  • 7
  • 3
20 Comments
 
LVL 92

Expert Comment

by:objects
ID: 34866680
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34866701
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
0
 

Author Comment

by:mrkkishore
ID: 34866865
I went to these sites, I downloaded JCE.jar file and replaced with existing JCE jar file.Still I am getting the same error.
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 34866925

Have you seen this somewhat related post, maybe it could give you some clue, even though
I guess it was utimately resolved by replacing jar's as the previous cases mentioned:

http://www.experts-exchange.com/Programming/Languages/Java/Q_26359622.html
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34866965
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.
0
 

Author Comment

by:mrkkishore
ID: 34867764
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"
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34867787
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?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34867801
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.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34867822
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  

0
 

Author Comment

by:mrkkishore
ID: 34867941
I have it as a class file.

C:\etm\java\jdk1.5.0_18

My OS is WindowsXP




0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 47

Expert Comment

by:for_yan
ID: 34867953
How do you start your excution - as the command line from cmd window ?
What is the command?
0
 

Author Comment

by:mrkkishore
ID: 34867960
I am running this in Eclipse3.4.1
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34867977
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?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34867987
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
0
 

Author Comment

by:mrkkishore
ID: 34867995
Thank you guys, It is working..I just re-build,clean the project and it started working...
0
 
LVL 92

Expert Comment

by:objects
ID: 34867996
> 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
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34868003
Great!
0
 

Author Comment

by:mrkkishore
ID: 34868005
my class files are in wss\build\classes..I think I have given you the wrong build path ..
0
 
LVL 92

Expert Comment

by:objects
ID: 34868041
you shouldn't need to specify it, source folders get included automatically
0
 

Author Closing Comment

by:mrkkishore
ID: 34890920
Not a direct answer.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 68
stackato and cloud 4 74
even odd program using while loop 3 29
Way to decrease size of apk file 9 45
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In 2017, ransomware will become so virulent and widespread that if you aren’t a victim yourself, you will know someone who is.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now