Skip to content

Instantly share code, notes, and snippets.

@stevemu
Last active August 13, 2021 03:15
Show Gist options
  • Save stevemu/5f1cdaabe58648f760a9f750f8d5155f to your computer and use it in GitHub Desktop.
Save stevemu/5f1cdaabe58648f760a9f750f8d5155f to your computer and use it in GitHub Desktop.
How to encrypt an object and write it to file in Java and decrypt it
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
// encrypt an java object and write to file
// create a java object
Employee em1 = new Employee("steve", "123");
// generate symmetric key
KeyGenerator generator = KeyGenerator.getInstance( "AES" );
SecretKey key = generator.generateKey();
// generate IV
SecureRandom random = new SecureRandom();
byte [] iv = new byte [16];
random.nextBytes( iv );
// create cipher
Cipher cipher = Cipher.getInstance( key.getAlgorithm() + "/CBC/PKCS5Padding" );
cipher.init( Cipher.ENCRYPT_MODE, key, new IvParameterSpec( iv ) );
// create sealed object
SealedObject sealedEm1 = new SealedObject( em1, cipher);
// Create stream
FileOutputStream fos = new FileOutputStream("out.aes");
BufferedOutputStream bos = new BufferedOutputStream(fos);
CipherOutputStream cos = new CipherOutputStream(bos, cipher);
ObjectOutputStream oos = new ObjectOutputStream(cos);
oos.writeObject( sealedEm1 );
oos.close();
// read an encrypted java object from a file and decrypt it
// turn the mode of cipher to decryption
cipher.init( Cipher.DECRYPT_MODE, key, new IvParameterSpec( iv ) ); // reuse the key and iv generated before
// create stream
CipherInputStream cipherInputStream = new CipherInputStream( new BufferedInputStream( new FileInputStream( "out.aes" ) ), cipher );
ObjectInputStream inputStream = new ObjectInputStream( cipherInputStream );
SealedObject sealedObject = (SealedObject) inputStream.readObject();
Employee em2 = (Employee) sealedObject.getObject(cipher);
System.out.println(em2.name);
}
}
class Employee implements Serializable {
public String name = "";
public String ssn = "";
public Employee(String name, String ssn) {
this.name = name;
this.ssn = ssn;
}
}
@pcdddd
Copy link

pcdddd commented Aug 13, 2021

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment