Encrypting an Object with DES - Java Security

Java examples for Security:DES

Description

Encrypting an Object with DES

Demo Code


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

public class Main {

  public static void main(String[] argv) {
    try {/* www .  j av a 2s  .c  om*/
      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 (Exception e) {
    }
  }
}

class MySecretClass implements java.io.Serializable {
  String s = "the secret";
}

Related Tutorials