How do I encrypt an object with DES?

This example demonstrate encrypting an object using DES algorithm. After the object was encrypted we store it in a file which will be decrypted in the next example here How do I decrypt an object with DES?.



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

public class ObjectEncrypt {
    // Store object in a file for future use.
    private static void writeToFile(String filename, Object object) throws Exception {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {
            fos = new FileOutputStream(new File(filename));
            oos = new ObjectOutputStream(fos);
        } catch (Exception e) {
        } finally {
            if (oos != null) {
            if (fos != null) {

    public static void main(String[] args) throws Exception {
        // Generating a temporary key and store it in a file.
        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
        writeToFile("secretkey.dat", key);

        // Preparing Cipher object for encryption.
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // Here we seal (encrypt) a simple string message (a string object).
        SealedObject sealedObject = new SealedObject("THIS IS A SECRET MESSAGE!", cipher);

        // Write the object out as a binary file.
        writeToFile("sealed.dat", sealedObject);


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply