If you want to secure a Java object you need to use SealedObject class.
Following is a sample code.
Using AES-128 bit and writing into a file as a sealed object.
try {
//Generate a key
KeyGenerator gen = KeyGenerator.getInstance("AES");
gen.init(128);
Key sKey = gen.generateKey();
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE,sKey);
// do the sealing
Car car=new Car("My car ",2014);
SealedObject so = new SealedObject(car,c);
FileOutputStream out = new FileOutputStream("Objects.obj");
ObjectOutputStream oOut = new ObjectOutputStream(out);
//Save the key
oOut.writeObject(sKey);
//Save the sealed object
oOut.writeObject(so);
oOut.close();
System.out.println("SealedObject was written to Object file");
} catch (Exception e) {
System.out.println(e);
}
}
Decryption goes as follows. It reads the sealed object and decrypt using the same key.
try {
FileInputStream in = new FileInputStream("Objects.obj");
ObjectInputStream oIn = new ObjectInputStream(in);
//Read the key
Key sKey= (Key) oIn.readObject();
//Read the sealed object
SealedObject so= (SealedObject) oIn.readObject();
//unsealded the object
Car car = (Car) so.getObject(sKey);
car.getNo();
car.getYear();
} catch (Exception e) {
System.out.println(e);
}
Securing the symmetric key is very important here but it is off topic.
AES(256) is the modern standard and its been used in US federal and other organisations. AES has 128,192 and 256 bit encryption. DES is considered as "Old" and it has many vulnerabilities. Successor of DES is 3DES. 3DES mitigates many vulnerabilities found in DES. But it is considered as slow when it comes to software implementations, because it's applying the DES in 3 times.
So always use AES when you are in doubt.