In the code below, I grab an existing pdf file, encrypt it and then output the encrypted file. My problem is that the outputted file does not work properly. It creates a file of zero bytes. I tried the same code with a simple text file "sample.txt" and it worked fine. The outputted file was created with encryption.
Can anyone tell me what I may be doing wrong? Does it work differently with 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 I should mention that I tried the same thing above but without any cipher/cipherOutPutStream and the new cloned file was generated properly. The code is below. So I would tend to believe its an issue with Cipher or CipherOutputStream. But then again, as mentioned before, it all worked fine with a 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; }