一.对于Facebook Conceal的介绍我就不多说了,网上很多,这里我主要说一下用法。
1.在 moudle 的 build.gradle 里添加
compile 'com.facebook.conceal:conceal:2.0.1@aar'
2.在项目的Application里或首个Activity里初始化Conceal,推荐在Application里初始化具体代码如下:
SoLoader.init(this, false);//第一个参数为context上下文环境
3.Conceal的加密解密是对字节数组byte[]以及数据流inputstream,outputstream等等进行处理,只是简单的对文本内容加密,解密的话,操作字节数组即可。
//先获取一个Crypto 加密对象
KeyChain keyChain = new SharedPrefsBackedKeyChain(this, CryptoConfig.KEY_256);
Crypto crypto = AndroidConceal.get().createDefaultCrypto(keyChain);
String s = "我爱中国";//需加密的字符串 byte[] plainText = s.getBytes();//转换为字节数组 Log.e("tag","加密前=="+plainText); byte[] cipherText = crypto.encrypt(plainText, Entity.create("mytext"));//对字节数组加密 Log.e("tag","加密后=="+cipherText);
//在需要解密的地方
byte[] cipher = getIntent().getByteArrayExtra("cipherText");//新页面接收传递过来的加密后数组
byte[] plainText = crypto.decrypt(cipher, Entity.create("mytext"));//解密,得到原来的字节数组
String s = new String(cipher);//将字节数组转回字符串
注意:加密解密中Entity.create("mytext")这个参数必须一致
二.文件加密
File file = new File(Environment.getExternalStorageDirectory(),"MyTest");// if(!file.exists()){ file.mkdir();//创建MyTest文件夹 } Log.e("tag","file="+file.exists()); File txtfile = new File(file,"aaaaa.txt");//自己往该文件夹拷贝一个文件 try { FileInputStream fis = new FileInputStream(txtfile); File outfile = new File(file,"bbbbb.txt");//加密后的文件,加密成功后打开是乱码 OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(outfile)); OutputStream outputStream = crypto.getCipherOutputStream( fileStream, Entity.create("entity_id")); int i=0; byte[] buffer = new byte[1024]; while ((i = fis.read(buffer)) > 0) { outputStream.write(buffer, 0, i); outputStream.flush(); } fis.close(); outputStream.close(); fileStream.close(); } catch (Exception e) { e.printStackTrace(); }
三.文件解密
File file = new File(Environment.getExternalStorageDirectory(),"MyTest"); File infile = new File(file,"bbbbb.txt");//之前加密过的文件 File outfile = new File(file,"ccccc.txt");//解密之后的文件 try { FileOutputStream out = new FileOutputStream(outfile); BufferedOutputStream bos = new BufferedOutputStream(out); FileInputStream fileStream = new FileInputStream(infile); //加密解密过程中Entity.create("entity_id")方法的参数必须一致 InputStream inputStream = crypto.getCipherInputStream(fileStream,Entity.create("entity_id")); int read; byte[] buffer = new byte[1024]; while ((read = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, read); bos.flush(); } out.close(); inputStream.close(); fileStream.close(); } catch (IOException e) { e.printStackTrace(); } catch (KeyChainException e) { e.printStackTrace(); } catch (CryptoInitializationException e) { e.printStackTrace(); }