思路:本地用异或加密好图片---放入Android的assets文件夹下---在程序里用异或解密。
都知道解压APK文件能拿到程序的图片资源,为了保护图片资源不被盗用,可采用简单异或的方法对图片进行加密,这样即使解压APK文件,图片也无法打开。
第一步,通过创建一个JAVA工程来对本地图片异或加密。
[java] view plain copy
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- /**
- * 用异或方法加密和解密图片
- * @author Administrator
- *
- */
- public class EncryptDemo {
- public static final int XOR_CONST = 0X99; // 异或密钥
- /**
- * @param args
- */
- public static void main(String[] args) {
- File load = new File("D:\\Windows\\Desktop\\eee.jpg"); //原图
- File result = new File("D:\\Windows\\Desktop\\eee.dat"); //加密后得到的文件
- File reload = new File("D:\\Windows\\Desktop\\eee2.jpg"); //解密后得到的原图
- try {
- encryptImg(load, result); // 加密原图
- encryptImg(result, reload); // 对加密后的文件再加密得到原图
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 文件流异或加密
- * @param src
- * @param dest
- * @throws Exception
- */
- public static void encryptImg(File load, File result) throws Exception {
- FileInputStream fis = new FileInputStream(load);
- FileOutputStream fos = new FileOutputStream(result);
- int read;
- while ((read = fis.read()) > -1) {
- fos.write(read ^ XOR_CONST); //进行异或运算并写入结果
- }
- fos.flush();
- fos.close();
- fis.close();
- }
- }
第二步,把生成的加密文件.dat放到android工程的assets文件夹下。
第三步,在android程序创建一个ImageView,用来显示解密图片资源。
[java] view plain copy
- package com.example.encryptdemo2;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
- import com.example.encryptdemo2.R;
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.widget.ImageView;
- /**
- * android中用异或解密图片资源
- * @author Administrator
- *
- */
- public class MainActivity extends Activity {
- private ImageView img;
- private Bitmap bitmap;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- img = (ImageView) findViewById(R.id.img);
- bitmap = readBitmap(this, "eee.dat"); //获取解密后的图片
- if(bitmap != null) {
- img.setImageBitmap(bitmap);
- } else {
- System.out.println("图片为空");
- }
- }
- /**
- * 异或解密图片方法
- * @param context
- * @param fileName
- * @return
- */
- public static Bitmap readBitmap(Context context, String fileName) {
- Bitmap bitmap = null;
- List<Byte> list = new ArrayList<Byte>();
- try {
- InputStream is = context.getAssets().open(fileName);
- int read;
- while ((read = is.read()) > -1) {
- read = read ^ 0X99; // 密钥
- list.add((byte) read);
- }
- byte[] arr = new byte[list.size()];
- for (int i = 0; i < arr.length; i++) {
- arr[i] = (Byte) list.get(i); //list转成byte[]
- }
- //通过byte数组获取二进制图片流
- bitmap = BitmapFactory.decodeByteArray(arr, 0, arr.length);
- System.out.println(bitmap);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return bitmap;
- }
- }