The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.crypto  [14 examples] > Encrypting and Decrypting  [6 examples]

e466. Encrypting an Object with DES

This example demonstrates how to encrypt a serializable object.
    try {
        // Generate a temporary key. In practice, you would save this key.
        // See also e464 Encrypting with DES Using a Pass Phrase.
        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
    
        // Prepare the encrypter
        Cipher ecipher = Cipher.getInstance("DES");
        ecipher.init(Cipher.ENCRYPT_MODE, key);
    
        // Seal (encrypt) the object
        SealedObject so = new SealedObject(new MySecretClass(), ecipher);
    
        // Get the algorithm used to seal the object
        String algoName = so.getAlgorithm();  // DES
    
        // Prepare the decrypter
        Cipher dcipher = Cipher.getInstance("DES");
        dcipher.init(Cipher.DECRYPT_MODE, key);
    
        // Unseal (decrypt) the class
        MySecretClass o = (MySecretClass)so.getObject(dcipher);
    } catch (java.io.IOException e) {
    } catch (ClassNotFoundException e) {
    } catch (javax.crypto.IllegalBlockSizeException e) {
    } catch (javax.crypto.BadPaddingException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
    
    public class MySecretClass implements java.io.Serializable {
        String s = "the secret";
    }

 Related Examples
e461. Listing All Available Encryption and Decryption Algorithms
e462. Encrypting a String with DES
e463. Encrypting a File or Stream with DES
e464. Encrypting with DES Using a Pass Phrase
e465. Converting a 56-bit Value to a DES Key

See also: Key Agreement    MAC    Symmetric Keys   


© 2002 Addison-Wesley.