半年前写下的草稿了,首次发表,很多不足,以后要慢慢改进
目标:加密内容-->写到文件中,解密文件-->读取文件内容
加密解密方式:AES-128(尝试过使用AES-256,发现在Androidstudio中实现不了,有大神可以实现的希望多多指教)
解析xml文件:这里我使用了第三方Xstream库(这个比较方便使用,数据不多时可以使用AS本身的方法)来序列化写入,反序列化写出
例子:byte[ ] _iv 长度为16,具体字节可自定义,byte[ ] _key 长度为32,具体字节自定义。(如:byte[ ] _iv={0x11,0x32,(byte) 0xFC,..........})。
这里是传入字符串进行加密,返回字节以便序列化写入文件;
传入字符串进行解密,返回字符串再反序列化写出;可根据具体需要来修改。
private static final byte[] _iv = {。。。。。}; private static final byte[] _key = {。。。。。}; //解密 public static String Decrypt(String sSrc){ SecretKeySpec skeySpec = new SecretKeySpec(_key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(_iv); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(HexUtils.hexStringToByte(sSrc)); return new String(original); } //加密 public static byte[] EncryptToByte(String sSrc) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(_key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(_iv); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); return cipher.doFinal(sSrc.getBytes()); }
/**反序列化 * @param inputStream 输入流 * @param cls 需要反序列化的类 * @param charSetName 编码格式字符串 * @return * @throws IOException */ public static <T> T Deserialize(InputStream inputStream, Class<T> cls,String charSetName) throws IOException { Log.d("devinfo", "PMCCheckUtil-->Deserialize01" ); XStream xstream = new XStream(new DomDriver(charSetName)); // xstream.autodetectAnnotations(true); xstream.processAnnotations(cls); @SuppressWarnings("unchecked") T retobj = (T) (xstream.fromXML(inputStream)); return retobj; }
/**序列化 * @param /ms 输出流 * @param obj 需要序列化的类 * @param charSetName 编码格式字符串 * @throws IOException */ public static void Serialize(OutputStream outputStream, Object obj,String charSetName) throws IOException { XStream xstream = new XStream(new DomDriver(charSetName)); xstream.processAnnotations(obj.getClass()); xstream.toXML(obj, outputStream); }