package com.example.aspectjandroidtest;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.util.EncodingUtils;

import com.facebook.crypto.Crypto;
import com.facebook.crypto.Entity;
import com.facebook.crypto.keychain.SharedPrefsBackedKeyChain;
import com.facebook.crypto.util.SystemNativeCryptoLibrary;

public aspect FileAspectJ {

	private boolean isEncryption = true;
	//使用秘钥链和原生库的默认实现,来创建一个新的加密对象
	Crypto crypto = new Crypto(
			new SharedPrefsBackedKeyChain(MainActivity.context),
			new SystemNativeCryptoLibrary());

	//创建应用文件的切点集合
	pointcut openFileOutput(String filename,int mode) : !within(FileAspectJ) && args(filename,mode) && call(* openFileOutput(..));
	after (String filename,int mode) returning : openFileOutput(filename, mode){
		//System.out.println("fx Aspectj openFile is start");
		byte[] buffer;
		try {
			System.out.println("fx Aspectj openFileName"+filename);
			buffer = filename.getBytes("UTF8");
			FileOutputStream fileOutputStream = null;
			try {
				//记录本应用加密过的文件
				fileOutputStream = MainActivity.context.openFileOutput("fileList",
						MainActivity.context.MODE_APPEND);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				fileOutputStream.write(buffer);
				fileOutputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//读取应用文件的切点集合
		pointcut openFileInput(String filename) : !within(FileAspectJ) && args(filename) && call(* openFileInput(..));
		before(String filename) : openFileInput(filename){

			String result = "";
			try {
				FileInputStream fileInputStream = MainActivity.context.openFileInput("fileList");
				int bufferSize = 0;
				try {
					bufferSize = fileInputStream.available();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} // 取得输入流的字节长度
				byte buffer[] = new byte[bufferSize];
				try {
					fileInputStream.read(buffer);
					fileInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				result = EncodingUtils.getString(buffer, "UTF-8");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//判断文件是否加密过
			if(result.indexOf(filename) == -1){
				isEncryption = false;//未加密
				System.out.println("fx 文件未加密");
			}else{
				isEncryption = true;//已加密
				System.out.println("fx 文件已加密");
			}
		}

		//截获到File的new操作
		pointcut filePointcut(String pathname ) :  !within(FileAspectJ) && args(pathname) && call(java.io.File.new(..));
		before(String pathname ) : filePointcut(pathname) {
			System.out.println("fx pathname is " + pathname);
		}

	//写文件切点的集合
	pointcut writePointcut(FileOutputStream fileStream, byte[] buffer) : !within(FileAspectJ) && target(fileStream)&& args(buffer) && call(* write(..));
	void around(FileOutputStream fileStream, byte[] buffer) : writePointcut(fileStream, buffer) {
		System.out.println("fx Aspectj write is start");
		//检查加密功能是否可用
		//如果Android没有正确载入库,则此步骤可能失败
		if (!crypto.isAvailable()) {
			System.out.println("return error");
			return;
		}
		OutputStream fbFileStream = new BufferedOutputStream(fileStream);
		try {
			//创建输出流,当数据写入流的时候进行加密,并将加密后的数据输出到文件
			OutputStream outputStream = crypto.getCipherOutputStream(
					fbFileStream, new Entity("test"));
			outputStream.write(buffer);
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//读文件切点集合
	pointcut readPointcut(FileInputStream fileStream, byte[] buffer) : !within(FileAspectJ) && target(fileStream)&& args(buffer) && call(* read(..));
	int around(FileInputStream fileStream, byte[] buffer) : readPointcut(fileStream, buffer) {
		System.out.println("fx Aspectj read is start");
		int bufferSize = 0;
		if(isEncryption==false){
			return 0;
		}
		try {
			//文件流解密操作
			InputStream inputStream = crypto.getCipherInputStream(fileStream,	new Entity("test"));
			bufferSize = inputStream.available(); // 取得输入流的字节长度
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	        byte[] data = new byte[1024];
			int len;
			 if (inputStream != null) {
		            try {
		                while ((len = inputStream.read(data)) != -1) {
		                    outputStream.write(data, 0, len);
		                }
		                data = outputStream.toByteArray();
		            } catch (IOException e) {
		            }
		        }
			 for(int i = 0;i<data.length;i++) {
				 buffer[i] = data[i];
			 }
			inputStream.close();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bufferSize;
	}

}

AspectJ截获操作的更多相关文章

  1. Spring的入门学习笔记 (AOP概念及操作+AspectJ)

    AOP概念 1.aop:面向切面(方面)编程,扩展功能不通过源代码实现 2.采用横向抽取机制,取代了传统的纵向继承重复代码 AOP原理 假设现有 public class User{ //添加用户方法 ...

  2. WCF 已知类型和泛型解析程序 KnownType

    数据协定继承 已知类型和泛型解析程序 Juval Lowy 下载代码示例 自首次发布以来,Windows Communication Foundation (WCF) 开发人员便必须处理数据协定继承方 ...

  3. KVM 实现机制

    1.1.    KVM简介 KVM是一个基于Linux内核的虚拟机,它属于完全虚拟化范畴,从Linux-2.6.20开始被包含在Linux内核中.KVM基于x86硬件虚拟化技术,它的运行要求Intel ...

  4. DPDK support for vhost-user

    转载:http://blog.csdn.net/quqi99/article/details/47321023 X86体系早期没有在硬件设计上对虚拟化提供支持,因此虚拟化完全通过软件实现.一个典型的做 ...

  5. [Spring-AOP-XML] 利用Spirng中的AOP和XML进行事务管理

    Spring中的AOP进行事务管理有三种方式 A.自定义事务切面 利用AspectJ来编写事务,我们一般把这个切面作用在service层中.其他代码在下面 编写一个Transaction实现类,通过S ...

  6. Windows API 查找窗体,发送Windows消息

    最近项目中需要做Windows消息截获操作,在网上找了一些资料. public class WindowsAPI { /// <summary> /// 回调函数代理 /// </s ...

  7. KVM分析报告

    转载   KVM分析报告   虚拟化技术工作组 2008-12-31 1.    概述 1.1.    KVM简介 KVM是以色列开源组织Qumranet开发的一个开源虚拟机监控器,从Linux-2. ...

  8. 《Spring源码深度解析》一

    Spring整体架构 1.1 Spring整体架构 1.1.1 Core Container: 模块:Core.Beans.Context和Expression Language Core:框架的基础 ...

  9. Spring_day03--课程安排_基于aspectj的注解aop_Spring的jdbcTemplate操作

    Spring_day03 上节内容回顾 今天内容介绍 基于aspectj的注解aop Spring的jdbcTemplate操作 增加 修改 删除 查询 Spring配置c3p0连接池和dao使用jd ...

随机推荐

  1. No.1_1 java语言基础_学习笔记

    import java.util.Scanner; public class HelloWorld { static final double PI=3.14; static int x=125; / ...

  2. 在JS中得到表单中各项的值

    var form = document.getElementById("change");var pageNo = form.pageno.value;

  3. [原]C语言实现的快速排序,采用分治策略,递归实现

    #include<stdio.h> #define LEN 8 int a[LEN] = { 5, 2, 4, 7, 1, 3, 2, 6 }; int Partition(int a[] ...

  4. Leetcode 104 Maximum Depth of Binary Tree python

    题目: Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the ...

  5. Django auth 登陆后页面跳转至/account/profile,修改跳转至其他页面

    这几天在学习django,django功能很强大,自带的auth,基本可以满足用户注册登陆登出,简单的用户注册登陆系统使用django auth足矣.当然也不是拿来就能用的,需要自己写登陆页面的模板, ...

  6. django--的第一个项目hello world

    第一步: 用django-admin命令开始一个项目 cd /tmp/ django-admin startproject firstproject tree /tmp/firstproject 第二 ...

  7. 【总结】OJ练习,进行的一些编程语言方面总结

    1.STL vector只有四个构造函数 ) explicit vector (const allocator_type& alloc = allocator_type()); fill () ...

  8. No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() where x is an instance of Outer)

    之前看内部类的时候没发现这个问题,今天写代码的时候遇到,写个最简单的例子: 下面这一段代码 红色的部分就是编译报错: No enclosing instance of type Outer is ac ...

  9. XMPP通讯开发-1

    有关XMPP的相关知识这里就不讲解了,网上有很多,这里我使用的NetBeans+Openire+smack搭建一个以XMPP协议的通讯工具,对于这部分知识我也不是很了解,也是初识吧,可能有些概念会混淆 ...

  10. C语言结构体的内存对齐问题

    在C语言开发当中会遇到这样的情况: #include <stdio.h> struct test { int a; char b; }; int main(int argc, const ...