Encrypted save and decrypted load of an ArrayList of serializable objects

前端 未结 3 1533
情书的邮戳
情书的邮戳 2021-02-04 17:37

I save and load in sd card a file that contains an ArrayList of serializable object with these two methods

save method

public static void sa         


        
3条回答
  •  遥遥无期
    2021-02-04 18:02

    Try (adding the appropriate checks and try blocks that I have omitted to make the code more readable) something like this to save

    public static void AESObjectEncoder(Serializable object, String password, String path) {
            try {
                Cipher cipher = null;
                cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                cipher.init(Cipher.ENCRYPT_MODE, fromStringToAESkey(password));
                SealedObject sealedObject = null;
                sealedObject = new SealedObject(object, cipher);
                CipherOutputStream cipherOutputStream = null;
                cipherOutputStream = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(path)), cipher);
                ObjectOutputStream outputStream = null;
                outputStream = new ObjectOutputStream(cipherOutputStream);
                outputStream.writeObject(sealedObject);
                outputStream.close();    
        }
    

    and this to load

     public static Serializable AESObjectDedcoder(String password, String path) {
            Cipher cipher = null;
            Serializable userList = null;
            cipher = Cipher.getInstance("AES/CBC/PKCS7Pdding");
    
            //Code to write your object to file
            cipher.init(Cipher.DECRYPT_MODE, fromStringToAESkey(password));         
            CipherInputStream cipherInputStream = null;
            cipherInputStream = new CipherInputStream(new BufferedInputStream(new FileInputStream(path)), cipher);
    
            ObjectInputStream inputStream = null;
            inputStream = new ObjectInputStream(cipherInputStream);
            SealedObject sealedObject = null;
            sealedObject = (SealedObject) inputStream.readObject();
            userList = (Serializable) sealedObject.getObject(ciper);  
            return userList;
        }
    

    to create a SecretKey from a String you can use this

    public static SecretKey fromStringToAESkey(String s) {
            //256bit key need 32 byte
            byte[] rawKey = new byte[32];
            // if you don't specify the encoding you might get weird results
            byte[] keyBytes = new byte[0];
            try {
                keyBytes = s.getBytes("ASCII");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.arraycopy(keyBytes, 0, rawKey, 0, keyBytes.length);
            SecretKey key = new SecretKeySpec(rawKey, "AES");
            return key;
        }
    

    NOTE:

    this code encrypts and decrypts twice to show the way of use of both sealed object and Cipher streams

提交回复
热议问题