serialization - Using DES to encrypt and decrypt a file in Java -


i'm trying serialize object (in case simple string), encrypt it, , write file. encryption seems work, decryption fails. i've tried searching around, can't seem figure out i'm doing wrong..

// create new key encrypt , decrypt file byte[] key = "password".getbytes();  // cipher object in encrypt mode  cipher cipher = null; try {     deskeyspec dks = new deskeyspec(key);     secretkeyfactory skf = secretkeyfactory.getinstance("des");     secretkey deskey = skf.generatesecret(dks);     cipher = cipher.getinstance("des");     cipher.init(cipher.encrypt_mode, deskey); } catch (invalidkeyexception | nosuchalgorithmexception | invalidkeyspecexception | nosuchpaddingexception ex) {     system.err.println("[critical] incryption chiper error"); }  // encrypt file try {     new objectoutputstream(new cipheroutputstream(new fileoutputstream("test"), cipher)).writeobject("test text"); } catch (ioexception e) {     system.err.println("[critical] error encrypting data: " + e.getmessage());     e.printstacktrace(); }  // cipher object in decrypt mode try {     deskeyspec dks = new deskeyspec(key);     secretkeyfactory skf = secretkeyfactory.getinstance("des");     secretkey deskey = skf.generatesecret(dks);     cipher = cipher.getinstance("des");     cipher.init(cipher.decrypt_mode, deskey); } catch (invalidkeyexception | nosuchalgorithmexception | invalidkeyspecexception | nosuchpaddingexception ex) {     system.err.println("[critical] incryption chiper error"); }  // decrypt file try {     // line throws exception     system.out.println((string) new objectinputstream(new cipherinputstream(new fileinputstream("test"), cipher)).readobject());  } catch (ioexception | classnotfoundexception e) {     system.err.println("[critical] error decrypting data: " + e.getmessage());     e.printstacktrace(); } 

running above code results in following exception:

[critical] error decrypting data: null java.io.eofexception @ java.io.objectinputstream$peekinputstream.readfully(objectinputstream.java:2304) @ java.io.objectinputstream$blockdatainputstream.readutfbody(objectinputstream.java:3042) @ java.io.objectinputstream$blockdatainputstream.readutf(objectinputstream.java:2843) @ java.io.objectinputstream.readstring(objectinputstream.java:1617) @ java.io.objectinputstream.readobject0(objectinputstream.java:1338) @ java.io.objectinputstream.readobject(objectinputstream.java:369) @ server.datapersistence.main(datapersistence.java:203) 

does have ideas?

thanks!

my guess nothing has been written file when attempt open , re-read data program. try calling flush(); , close(); on output stream before attempting read file in again.


Comments