Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Base64;
- public class User implements Serializable {
- String userName;
- transient String password;
- public User(String userName, String password) {
- this.userName = userName;
- this.password = password;
- }
- private void writeObject(ObjectOutputStream oos) throws Exception {
- oos.defaultWriteObject();
- String encryptPassword = encrypt(password);
- oos.writeObject(encryptPassword);
- }
- private void readObject(ObjectInputStream ois) throws Exception {
- ois.defaultReadObject();
- password = decrypt((String) ois.readObject()) + " <- Decrypted password";
- }
- private String encrypt(String password) {
- return Base64.getEncoder().encodeToString(password.getBytes());
- }
- private String decrypt(String encodedString) {
- return new String(Base64.getDecoder().decode(encodedString));
- }
- @Override
- public String toString() {
- return String.format("Name: %s, Pass: %s", userName, password);
- }
- }
- class UserMain {
- public static void main(String[] args) throws IOException, ClassNotFoundException {
- User newUser = new User("Bob", "1qaS3d+67");
- System.out.println("Before serialization " + newUser); // Before serialization Name: Bob, Pass: 1qaS3d+67
- serializeUser(newUser, "new_user_file");
- User oldUser = deserializeUser("new_user_file");
- System.out.println("After serialization " + oldUser); // After serialization Name: Bob, Pass: 1qaS3d+67 <- Decrypted password
- }
- public static User deserializeUser(String filename) throws IOException {
- User deserializedUser = null;
- try (FileInputStream fileIn = new FileInputStream(filename);
- ObjectInputStream ois = new ObjectInputStream(fileIn)) {
- deserializedUser = (User) ois.readObject();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- return deserializedUser;
- }
- public static void serializeUser(User user, String filename) throws IOException {
- try (FileOutputStream fileOut = new FileOutputStream(filename);
- ObjectOutputStream oos = new ObjectOutputStream(fileOut)) {
- oos.writeObject(user);
- }
- }
- }
Add Comment
Please, Sign In to add comment