Al3XXX

Custom serialization

Nov 28th, 2021 (edited)
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.30 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Base64;
  3.  
  4. public class User implements Serializable {
  5.     String userName;
  6.     transient String password;
  7.  
  8.     public User(String userName, String password) {
  9.         this.userName = userName;
  10.         this.password = password;
  11.     }
  12.  
  13.     private void writeObject(ObjectOutputStream oos) throws Exception {
  14.         oos.defaultWriteObject();
  15.         String encryptPassword = encrypt(password);
  16.         oos.writeObject(encryptPassword);
  17.     }
  18.  
  19.     private void readObject(ObjectInputStream ois) throws Exception {
  20.         ois.defaultReadObject();
  21.         password = decrypt((String) ois.readObject()) + " <- Decrypted password";
  22.     }
  23.  
  24.     private String encrypt(String password) {
  25.         return Base64.getEncoder().encodeToString(password.getBytes());
  26.     }
  27.  
  28.     private String decrypt(String encodedString) {
  29.         return new String(Base64.getDecoder().decode(encodedString));
  30.     }
  31.  
  32.     @Override
  33.     public String toString() {
  34.         return String.format("Name: %s, Pass: %s", userName, password);
  35.     }
  36. }
  37.  
  38. class UserMain {
  39.     public static void main(String[] args) throws IOException, ClassNotFoundException {
  40.         User newUser = new User("Bob", "1qaS3d+67");
  41.         System.out.println("Before serialization " + newUser); // Before serialization Name: Bob, Pass: 1qaS3d+67
  42.         serializeUser(newUser, "new_user_file");
  43.  
  44.         User oldUser = deserializeUser("new_user_file");
  45.         System.out.println("After serialization " + oldUser); // After serialization Name: Bob, Pass: 1qaS3d+67 <- Decrypted password
  46.     }
  47.  
  48.     public static User deserializeUser(String filename) throws IOException {
  49.         User deserializedUser = null;
  50.         try (FileInputStream fileIn = new FileInputStream(filename);
  51.             ObjectInputStream ois = new ObjectInputStream(fileIn)) {
  52.  
  53.             deserializedUser = (User) ois.readObject();
  54.         } catch (ClassNotFoundException e) {
  55.             e.printStackTrace();
  56.         }
  57.         return deserializedUser;
  58.     }
  59.  
  60.     public static void serializeUser(User user, String filename) throws IOException {
  61.         try (FileOutputStream fileOut = new FileOutputStream(filename);
  62.              ObjectOutputStream oos = new ObjectOutputStream(fileOut)) {
  63.  
  64.             oos.writeObject(user);
  65.         }
  66.     }
  67. }
Add Comment
Please, Sign In to add comment