栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

public static void AESObjectEnprer(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 AESObjectDedprer(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;    }

注意:

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407363.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号