Cryptage des objects avec java
Code:
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);
}
} |
Code:
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
| import java.io.*;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
public class ObjectDecrypt {
//
// Method for reading object stored in a file.
//
private static Object readFromFile(String filename) throws Exception {
FileInputStream fis = null;
ObjectInputStream ois = null;
Object object = null;
try {
fis = new FileInputStream(new File(filename));
ois = new ObjectInputStream(fis);
object = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
}
if (fis != null) {
fis.close();
}
}
return object;
}
public static void main(String[] args) throws Exception {
//
// Read the previously stored SecretKey.
//
SecretKey key = (SecretKey) readFromFile("secretkey.txt");
//
// Read the SealedObject
//
SealedObject sealedObject = (SealedObject) readFromFile("sealed.txt");
//
// Preparing Cipher object from decryption.
//
String algorithmName = sealedObject.getAlgorithm();
Cipher cipher = Cipher.getInstance(algorithmName);
cipher.init(Cipher.DECRYPT_MODE, key);
Object text = (Object) sealedObject.getObject(cipher);
System.out.println("Text = " + text);
}
} |