Java Security SealedObject save to file
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.security.PublicKey; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SealedObject; import javax.crypto.SecretKey; import javax.security.cert.X509Certificate; ///*from ww w. j a va 2 s. c o m*/ public class Main { public static void main(String args[]) throws Exception { String alg = "DES", target = "Hello World!"; PublicKey pub = X509Certificate.getInstance(new FileInputStream("test.cer")).getPublicKey(); Cipher cipher = Cipher.getInstance(pub.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pub); KeyGenerator kg = KeyGenerator.getInstance(alg); SecretKey sk = kg.generateKey(); SealedObject so = new SealedObject(sk.getEncoded(), cipher); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("key")); oos.writeObject(so); cipher = Cipher.getInstance(alg); cipher.init(Cipher.ENCRYPT_MODE, sk); so = new SealedObject(target, cipher); oos = new ObjectOutputStream(new FileOutputStream("data")); oos.writeObject(so); oos.close(); } }