How to encrypt and decrypt an object in and from a file in Java

There are times when we need to write something on a file, but doesn't want it to be readable as a plain text. In this case we can use a...

There are times when we need to write something on a file, but doesn't want it to be readable as a plain text. In this case we can use any type of encryption mechanism, but what if we want to decrypt the encrypted file back and read its contents. For example a configuration file, etc.

Let's show some codes as usual:

public class CipherUtils {

public static final String CIPHER_MODE = "AES/CBC/PKCS5Padding";

private CipherUtils() {

}

public static void encode(Serializable object, String password, String path)
throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance(CIPHER_MODE);
cipher.init(Cipher.ENCRYPT_MODE, fromStringToAESkey(password), new IvParameterSpec(new byte[16]));

// read object from file
SealedObject sealedObject = new SealedObject(object, cipher);
FileOutputStream fos = new FileOutputStream(path);
CipherOutputStream cipherOutputStream = new CipherOutputStream(new BufferedOutputStream(fos), cipher);

ObjectOutputStream outputStream = new ObjectOutputStream(cipherOutputStream);
outputStream.writeObject(sealedObject);
outputStream.close();
fos.close();
}

public static Serializable decode(String password, String path)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException,
ClassNotFoundException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance(CIPHER_MODE);

// write object to file
cipher.init(Cipher.DECRYPT_MODE, fromStringToAESkey(password), new IvParameterSpec(new byte[16]));
CipherInputStream cipherInputStream = new CipherInputStream(new BufferedInputStream(new FileInputStream(path)),
cipher);

ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
SealedObject sealedObject = (SealedObject) inputStream.readObject();
Serializable serializeableObject = (Serializable) sealedObject.getObject(cipher);
inputStream.close();

return serializeableObject;
}

public static SecretKey fromStringToAESkey(String s) throws UnsupportedEncodingException {
// 128bit key need 16 byte
byte[] rawKey = new byte[16];
// if you don't specify the encoding you might get weird results
byte[] keyBytes = s.getBytes("UTF-8");
System.arraycopy(keyBytes, 0, rawKey, 0, keyBytes.length);

return new SecretKeySpec(rawKey, "AES");
}
}

This utility class can encrypt and decrypt any serialize-able object we have.

And here's how we use it:


public class CipherUtilsTest {

private Person person;

@Before
public void init() {
person = new Person();
person.setFirstname("Shirayuki");
person.setLastname("Hime");
person.setAge(18);
}

@Test
public void testEncodeDecode() {
try {
CipherUtils.encode(person, "shirayuki", "c://temp//cipher");
Person decodedPerson = (Person) CipherUtils.decode("shirayuki", "c://temp//cipher");
assertEquals(person.getAge(), decodedPerson.getAge());
assertEquals(person.getFirstname(), decodedPerson.getFirstname());
assertEquals(person.getLastname(), decodedPerson.getLastname());
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
| IOException | ClassNotFoundException | BadPaddingException | InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

COMMENTS

mas template
Name

amazon,1,angular,8,bigdata,2,business,1,course-spring,27,courses,6,database,4,docker,3,java,50,kafka,1,keycloak,4,microservices,5,mysql,1,neworking,1,nosql,2,php,1,pinned,2,react,3,server management,7,shared drive,1,spring,7,synology,1,troubleshooting,2,web,1,wordpress,1,
ltr
item
toztech: How to encrypt and decrypt an object in and from a file in Java
How to encrypt and decrypt an object in and from a file in Java
toztech
https://toztech.blogspot.com/2017/10/how-to-encrypt-and-decrypt-object-in.html
https://toztech.blogspot.com/
https://toztech.blogspot.com/
https://toztech.blogspot.com/2017/10/how-to-encrypt-and-decrypt-object-in.html
true
2554149350007112447
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content