Android文件简单加解密

前言

在Android应用开发中,有时需要把一些内容以文件的方式保存到sdcard上,这时我们需要考虑数据的安全性,这就涉及到文件的加解密,这里简单介绍一种文件的加解密实现方法。

实现方案

我们在读写文件的时候,一般会用到FileInputStream和FileOutputStream,因此我们加解密的时机可以选在read和write数据时,这样很好的和上层业务隔离开,实现方法如下

  1. 实现加密算法
public class DataConvertUtil {
    private static byte rotateLeft(byte sourceByte, int n) {
        int temp = sourceByte & 0xFF;
        return (byte) ((temp << n) | (temp >> (8 - n)));
    }

    private static byte rotateRight(byte sourceByte, int n) {
        int temp = sourceByte & 0xFF;
        return (byte) ((temp >> n) | (temp << (8 - n)));
    }

    private static byte[] rotateLeft(byte[] sourceBytes, int n) {
        for (int i = 0; i < sourceBytes.length; i++) {
            sourceBytes[i] = rotateLeft(sourceBytes[i], n);
        }
        return sourceBytes;

    }

    private static byte[] rotateRight(byte[] sourceBytes, int n) {
        for (int i = 0; i < sourceBytes.length; i++) {
            sourceBytes[i] = rotateRight(sourceBytes[i], n);
        }
        return sourceBytes;
    }

    public static byte[] encryData(byte[] buffer) {
        return rotateLeft(buffer,3);
    }

    public static byte[] decryData(byte[] buffer) {
        return rotateRight(buffer,3);
    }
}
  1. 继承FileOutputStream
public class EncryOutputStream extends FileOutputStream {

    public EncryOutputStream(String path) throws FileNotFoundException {
        super(path);
    }

    @Override
    public void write(byte[] buffer) throws IOException {
        this.write(buffer, 0, buffer.length);
    }

    @Override
    public void write(byte[] buffer, int byteOffset, int byteCount) throws IOException {
        buffer = DataConvertUtil.encryData(buffer);
        super.write(buffer, byteOffset, byteCount);
    }

    @Override
    public void write(int oneByte) throws IOException {
        byte[] buffer = new byte[1];
        buffer[0] = (byte) oneByte;
        this.write(buffer);
    }
}

3.继承FileInputStream

public class EncryFileInputStream extends FileInputStream {

    public EncryFileInputStream(String path) throws FileNotFoundException {
        super(path);
    }

    @Override
    public int read() throws IOException {
        byte[] buffer = new byte[1];
        this.read(buffer);
        return buffer[0];
    }

    @Override
    public int read(byte[] buffer) throws IOException {
        return this.read(buffer, 0, buffer.length);
    }

    @Override
    public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
        int length = super.read(buffer, byteOffset, byteCount);
        DataConvertUtil.decryData(buffer);
        return length;
    }
}

你可能感兴趣的:(Android文件简单加解密)