Encrypt a file appending IVSBytes in unique file - Execption: Given final block not properly padded

ε祈祈猫儿з 提交于 2019-12-03 21:51:21

Your problem is on the encrypt/write side; you close os (the FileOutputStream) before you close cos (the CipherOutputStream), so it doesn't write the last encrypted block to the file. Instead you should just cos.close(); which per javadoc (note that handles the os.close() for you):

This method invokes the doFinal method of the encapsulated cipher object, which causes any bytes buffered by the encapsulated cipher to be processed. The result is written out by calling the flush method of this output stream.

This method resets the encapsulated cipher object to its initial state and calls the close method of the underlying output stream.

Or since your plaintext fits in one buffer (and your read side requires that) skip the CipherOutputStream and just os.write (cipher.doFinal(bytes)); os.close();

Also, you construct the FileOutputStream with (file,true) which means if the identified file already exists and is nonempty (and not protected so it throws an exception) your new data is appended at the end, but your read side expects it to be at the beginning.

And: you don't show what the salt is, but if it doesn't contain more entropy than a human can remember it probably isn't serving its purpose. Since we can't expect a human to remember and type in adequate salt, the usual practice is to include it in the file/message/database/whatever.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!