Link to home
Start Free TrialLog in
Avatar of aaronyeo22
aaronyeo22Flag for Malaysia

asked on

How to create .properties file to solve this

i have no idea how to create the properties file to run this particular example (Itext second edition example).

please help me. Experts.

thanks
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.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
 
public class EncryptWithCertificate {
 
    /** The resulting PDF */
    public static String RESULT1 = "c:/results/part1/chapter01/certificate_encryption.pdf";
    /** The resulting PDF */
    public static String RESULT2 = "c:/results/part1/chapter01/certificate_decrypted.pdf";
    /** The resulting PDF */
    public static String RESULT3 = "c:/results/part1/chapter01/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:/home/blowagie/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:/resources/encryption/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:/resources/encryption/.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:/resources/encryption/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:/resources/encryption/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 CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

It's only there to set a public key file
Avatar of aaronyeo22

ASKER

i was created a key.properties. It means i just key in the "PUBLIC" this word in key.properties file save it and run the example.


thanks
This should be the properties file
PUBLIC=<path to cert file without angle brackets OR spaces>

Open in new window

PUBLIC=c:/resources/encryption
PUBLIC=c:/resources/encryption/

i was test both and put it in the key.properties file and run the program and return

Exception in thread "main" java.io.FileNotFoundException: C:\resources\encryption (Access is denied)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(Unknown Source)
      at java.io.FileInputStream.<init>(Unknown Source)
      at part1.charpter01.EncryptWithCertificate.getPublicCertificate(EncryptWithCertificate.java:76)
      at part1.charpter01.EncryptWithCertificate.createPdf(EncryptWithCertificate.java:56)
      at part1.charpter01.EncryptWithCertificate.main(EncryptWithCertificate.java:143)
Try putting it in your home directory. You ought to give it an extension actually or it looks like a directory

copy C:\resources\encryption "%USERPROFILE%.cer"
echo "File now in "%USERPROFILE%.cer"

Make sure you escape any spaces in the props file


PUBLIC=/a/b/c/a\ directory\ with\ spaces/d.cer
sorry. expert. i am very stupid. can you teach me more directly.

thanks
Those are commands you need to run at the command prompt
copy C:\resources\encryption "%USERPROFILE%.cer"
echo "File now in "%USERPROFILE%.cer"

Open in new window

copy C:\resources\encryption "%USERPROFILE%.cer"
echo "File now in "%USERPROFILE%.cer"


i was do it in cmd. But when i type echo "%USERPROFILE%.cer" the cmd prompt up this is not a valid security certificate.

after i type it the certificate was located and name it as C:\Documents and Settings\Administrator.cer


Let's start again. What is the name of the file you're going to use with the cert in it and where is it?
key.properties = C:\home\blowagie

.keystore  = C:\resources\encryption
foobar.cer  = C:\resources\encryption

sorry.
So, the certificate file is


C:\resources\encryption\foobar.cer

?

If so, you should have

PUBLIC=C:\resources\encryption\foobar.cer

in the props file
PUBLIC=C:/resources/encryption/foobar.cer

my props file and return this error

Exception in thread "main" ExceptionConverter: java.security.InvalidKeyException: Illegal key size or default parameters
      at javax.crypto.Cipher.a(DashoA13*..)
      at javax.crypto.Cipher.a(DashoA13*..)
      at javax.crypto.Cipher.a(DashoA13*..)
      at javax.crypto.Cipher.init(DashoA13*..)
      at javax.crypto.Cipher.init(DashoA13*..)
      at com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.computeRecipientInfo(PdfPublicKeySecurityHandler.java:266)
      at com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.createDERForRecipient(PdfPublicKeySecurityHandler.java:242)
      at com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.getEncodedRecipient(PdfPublicKeySecurityHandler.java:191)
      at com.itextpdf.text.pdf.PdfEncryption.getEncryptionDictionary(PdfEncryption.java:468)
      at com.itextpdf.text.pdf.PdfWriter.setEncryption(PdfWriter.java:2009)
      at part1.charpter01.EncryptWithCertificate.createPdf(EncryptWithCertificate.java:57)
      at part1.charpter01.EncryptWithCertificate.main(EncryptWithCertificate.java:143)
Looks like either the cert file is corrupt or doesn't contain the correct kind of key for iText
PUBLIC=C:\resources\encryption\foobar.cer

Which one is correct
1)PUBLIC=C:/resources/encryption/foobar.cer
2)PUBLIC=C:\resources\encryption\foobar.cer

this is second one return result

Exception in thread "main" java.io.FileNotFoundException: C:abc oobar.cer (The filename, directory name, or volume label syntax is incorrect)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(Unknown Source)
      at java.io.FileInputStream.<init>(Unknown Source)
      at part1.charpter01.EncryptWithCertificate.getPublicCertificate(EncryptWithCertificate.java:76)
      at part1.charpter01.EncryptWithCertificate.createPdf(EncryptWithCertificate.java:56)
      at part1.charpter01.EncryptWithCertificate.main(EncryptWithCertificate.java:143)
If that's happening then definitely use 1)
you need to escape \ so use:

1)PUBLIC=C:/resources/encryption/foobar.cer

or:

2)PUBLIC=C:\\resources\\encryption\\foobar.cer
Thanks a lot. CEHJ. I used the JCE policy file to settle "Exception in thread "main" ExceptionConverter: java.security.InvalidKeyException: Illegal key size or default parameters"


thanks
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland 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
can you look at my second question.