您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

可序列化对象的ArrayList的加密保存和解密加载

可序列化对象的ArrayList的加密保存和解密加载

请尝试(添加适当的检查并尝试省略的块以使代码更具可读性)这样的保存

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();    
    }

这要加载

 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;
    }

SecretKey字符串创建一个,您可以使用此

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;
    }

注意:@H_419_22@

代码两次加密和解密,以显示密封对象和密码流的使用方式@H_419_22@

其他 2022/1/1 18:27:22 有552人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶