java - Writing an encrypted PDF file using Cipher RSA -


in code below, grab existing pdf file, encrypt , output encrypted file. problem outputted file not work properly. creates file of 0 bytes. tried same code simple text file "sample.txt" , worked fine. outputted file created encryption.

can tell me may doing wrong? work differently pdf files?

public void encryptfile() throws nosuchalgorithmexception, nosuchpaddingexception, invalidkeyexception, certificateexception, keystoreexception, ioexception {      fileinputstream fis = new fileinputstream("c:\\sample.pdf");     fileoutputstream fos = new fileoutputstream("c:\\sample_encrypted");      cipher c = cipher.getinstance("rsa/ecb/oaepwithsha-1andmgf1padding");     c.init(cipher.encrypt_mode, getsappubliccertificate().getpublickey());     cipheroutputstream cos = new cipheroutputstream(fos, c);      byte[] buf = new byte[2048];     int read;     while ((read = fis.read(buf)) != -1) {         cos.write(buf, 0, read);     }      fis.close();     cos.flush();     cos.close(); } 

edit should mention tried same thing above without cipher/cipheroutputstream , new cloned file generated properly. code below. tend believe issue cipher or cipheroutputstream. again, mentioned before, worked fine simple text file.

    byte[] buffer = new byte[2048];     int read;     while ((read = fis.read(buffer)) != -1) {         fos.write(buffer, 0, read);     } 

edit2 content of method getcertficate()

public certificate getsappubliccertificate() throws ioexception, certificateexception, keystoreexception, nosuchalgorithmexception {     char[] password = "mypass".tochararray();     string alias = "myalias";      fileinputstream fin = new fileinputstream(keystoresapcertificate);     keystore keystore = keystore.getinstance("jks");      keystore.load(fin, password);     certificate cert = keystore.getcertificate(alias);      return cert; } 

you need use hybrid encryption. cannot encrypt large files using rsa. wonder though how handle errors or when program doesn't finish; issues these should caught java runtime system.

the file handling not different between text files , pdf files, it's size different.


hybrid encryption comes down to:

  1. generate random symmetric key (e.g. aes-128);
  2. encrypt file, e.g. using aes-cbc 0 iv;
  3. encrypt symmetric key rsa-oaep or rsa-pkcs#1;
  4. send or store ciphertext , encrypted symmetric key;

decryption goes this:

  1. retrieve ciphertext , rsa encrypted symmetric key;
  2. decrypt symmetric key using private key;
  3. decrypt ciphertext.

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -