title: Encrypt/Decrypt pdf file with Java
body: <p>I want to encrypt/decrypt a pdf file on Android (but it's a java common issue)</p>
  
  <p>I have this code to generate my key : </p>
  
  <pre><code> public static byte[] getRawKey(byte[] seed) throws Exception {
       KeyGenerator kgen = KeyGenerator.getInstance("AES");
       SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
       sr.setSeed(seed);
       kgen.init(128, sr);
       SecretKey skey = kgen.generateKey();
       byte[] raw = skey.getEncoded();
       return raw;
   }
  </code></pre>
  
  <p>my code to write encrypted file : </p>
  
  <pre><code> inStream = new BufferedInputStream(conn.getInputStream());
   outFile = new File(path + fileName);
   outStream = new BufferedOutputStream(new FileOutputStream(outFile), 4096);
   byte[] data = new byte[4096];
   String seed = "password";
   byte[] rawKey = Utils.getRawKey(seed.getBytes());
   SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
   Cipher cipher = Cipher.getInstance("AES");
   cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
   int bytesRead = 0;
   while((bytesRead = inStream.read(data, 0, data.length)) &gt;= 0)
   {
        outStream.write(cipher.doFinal(data),0, bytesRead);
   }
   outStream.flush();
   outStream.close();  
   inStream.close();
  </code></pre>
  
  <p>And my code to decrypt it (and save it, to a new decrypted file) : </p>
  
  <pre><code>  FileInputStream fis = new FileInputStream(file);
    FileOutputStream fos = new FileOutputStream(tmp_file);
    String seed = "password";
    byte[] rawKey = Utils.getRawKey(seed.getBytes());
    SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    int b;
    byte[] data = new byte[4096];
    while((b = fis.read(data)) != -1) {
         fos.write(cipher.doFinal(data), 0, b);
    }
   fos.flush();
   fos.close();
   fis.close();
  </code></pre>
  
  <p>I read a lot on stackoverflow, and try to follow instructions, but this not working and I got this error : </p>
  
  <pre><code> javax.crypto.BadPaddingException: pad block corrupted at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCi
  </code></pre>
  
  <p>What am I doing wrong ? Is there any specificity related to pdf file ?</p>