SecureStorage.java 915 B

12345678910111213141516171819202122232425262728
  1. package storage;
  2. import model.Chat;
  3. import java.io.*;
  4. import java.nio.file.*;
  5. import java.security.*;
  6. import javax.crypto.*;
  7. import javax.crypto.spec.SecretKeySpec;
  8. import java.util.*;
  9. public class SecureStorage {
  10. public static void saveChats(List<Chat> chats, String password) throws Exception {
  11. ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
  12. ObjectOutputStream objOut = new ObjectOutputStream(byteStream);
  13. objOut.writeObject(chats);
  14. objOut.close();
  15. byte[] data = byteStream.toByteArray();
  16. byte[] key = Arrays.copyOf(password.getBytes(), 16); // AES 128-bit
  17. SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
  18. Cipher cipher = Cipher.getInstance("AES");
  19. cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  20. byte[] encrypted = cipher.doFinal(data);
  21. Files.write(Paths.get("chats.dat"), encrypted);
  22. }
  23. }