1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import java.io.*;
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);
oos.writeObject(object);
oos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
oos.close();
}
if (fos != null) {
fos.close();
}
}
}
public static void main(String[] args) throws Exception {
//
// Generating a temporary key and stire it in a file.
//
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
writeToFile("secretkey.txt", 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).
//
Personne p=new Personne("Mohamed","Mohamed",40);
// SealedObject sealedObject = new SealedObject(p, cipher);
Object sealedObject = new SealedObject(p, cipher);//.getObject(cipher);
Personne o=(Personne) sealedObject;
System.out.println("Text = " + o.getnom());
//
// Write the object out as a binary file.
//
writeToFile("sealed.txt", sealedObject);
}
} |
Partager