· 8 years ago · Dec 30, 2017, 01:00 PM
1import javax.crypto.*;
2import javax.crypto.spec.IvParameterSpec;
3import java.io.*;
4import java.security.InvalidAlgorithmParameterException;
5import java.security.InvalidKeyException;
6import java.security.NoSuchAlgorithmException;
7import java.security.SecureRandom;
8
9public class Main {
10
11 public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
12
13 // encrypt an java object and write to file
14
15 // create a java object
16 Employee em1 = new Employee("steve", "123");
17
18 // generate symmetric key
19 KeyGenerator generator = KeyGenerator.getInstance( "AES" );
20 SecretKey key = generator.generateKey();
21
22 // generate IV
23 SecureRandom random = new SecureRandom();
24 byte [] iv = new byte [16];
25 random.nextBytes( iv );
26
27 // create cipher
28 Cipher cipher = Cipher.getInstance( key.getAlgorithm() + "/CBC/PKCS5Padding" );
29 cipher.init( Cipher.ENCRYPT_MODE, key, new IvParameterSpec( iv ) );
30
31 // create sealed object
32 SealedObject sealedEm1 = new SealedObject( em1, cipher);
33
34 // Create stream
35 FileOutputStream fos = new FileOutputStream("out.aes");
36 BufferedOutputStream bos = new BufferedOutputStream(fos);
37 CipherOutputStream cos = new CipherOutputStream(bos, cipher);
38 ObjectOutputStream oos = new ObjectOutputStream(cos);
39 oos.writeObject( sealedEm1 );
40 oos.close();
41
42
43 // read an encrypted java object from a file and decrypt it
44
45
46 // turn the mode of cipher to decryption
47 cipher.init( Cipher.DECRYPT_MODE, key, new IvParameterSpec( iv ) ); // reuse the key and iv generated before
48
49 // create stream
50 CipherInputStream cipherInputStream = new CipherInputStream( new BufferedInputStream( new FileInputStream( "out.aes" ) ), cipher );
51 ObjectInputStream inputStream = new ObjectInputStream( cipherInputStream );
52 SealedObject sealedObject = (SealedObject) inputStream.readObject();
53 Employee em2 = (Employee) sealedObject.getObject(cipher);
54 System.out.println(em2.name);
55
56
57 }
58}
59
60class Employee implements Serializable {
61 public String name = "";
62 public String ssn = "";
63
64 public Employee(String name, String ssn) {
65 this.name = name;
66 this.ssn = ssn;
67 }
68
69}