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.

package org.kodejava.example.security;

import java.io.*;

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) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                ois.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        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

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.