android - Encrypt/Decrypt pdf file with Java -


i want encrypt/decrypt pdf file on android (but it's java common issue)

i have code generate key :

 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;  } 

my code write encrypted file :

 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)) >= 0)  {       outstream.write(cipher.dofinal(data),0, bytesread);  }  outstream.flush();  outstream.close();    instream.close(); 

and code decrypt (and save it, new decrypted file) :

  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(); 

i read lot on stackoverflow, , try follow instructions, not working , got error :

 javax.crypto.badpaddingexception: pad block corrupted @ com.android.org.bouncycastle.jcajce.provider.symmetric.util.baseblockcipher.enginedofinal(baseblockci 

what doing wrong ? there specificity related pdf file ?

you shouldn't calling cipher.dofinal inside loop. instead call cipher.update(data, ...) , call cipher.dofinal() after loop completes. otherwise you're processing last block.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -