How do I decrypt an object with DES?

On the previous example How do I encrypt an object with DES? we encrypt an object. In this example we’ll decrypt the stored object.



import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;

public class ObjectDecrypt {
    // Method for reading object stored in a file.
    private static Object readFromFile(String filename) throws Exception {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Object object = null;

        try {
            fis = new FileInputStream(new File(filename));
            ois = new ObjectInputStream(fis);
            object = ois.readObject();
        } catch (Exception e) {
        } finally {
            if (ois != null) {
            if (fis != null) {
        return object;

    public static void main(String[] args) throws Exception {
        // Read the previously stored SecretKey.
        SecretKey key = (SecretKey) readFromFile("secretkey.dat");

        // Read the SealedObject
        SealedObject sealedObject = (SealedObject) readFromFile("sealed.dat");

        // Preparing Cipher object from decryption.
        String algorithmName = sealedObject.getAlgorithm();
        Cipher cipher = Cipher.getInstance(algorithmName);
        cipher.init(Cipher.DECRYPT_MODE, key);

        String text = (String) sealedObject.getObject(cipher);
        System.out.println("Text = " + text);

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply