sqlite3加密

在加密和解密的时候我们都依赖于一个key, 这个key的生成会决定着加密效果。key可以保存在内存中或者以二进制的形式写入到文件,每次当程序启动时,从文件读取到内存中。key的生成,我们可以自定义一些规则,比如当前用户的密码+特定字符串,当前deviceId+特定字符串等等。这个就自定义了。

public static byte[] encrypt(byte[] key, byte[]data) {
        SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher;
        byte[] encryptedData = null;
        try {
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
            encryptedData = cipher.doFinal(data);
        } catch (Exception e) {
            Log.i(TAG, "encrypt exception" + e.getMessage());
        }
        return encryptedData;
    }

    public static byte[] decrypt(byte[] key, byte[]data) {
        SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher;
        byte [] decryptedData = null;
        try {
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
            decryptedData = cipher.doFinal(data);
        } catch (Exception e) {
            Log.i(TAG, "decrypt exception" + e.getMessage());
        }
        return decryptedData;
    }

    public static byte[] generateKey(byte[] randomNumberSeed) {
        SecretKey sKey = null;
        KeyGenerator keyGen;
        try {
            keyGen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(randomNumberSeed);
            sKey = keyGen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            Log.i(TAG, "generateKey exception" + e.getMessage());
        }
        return sKey.getEncoded();
    }

    //调用的demo
    public static void testAES() {
        String randomNumberSeed = "aaaa";
        String data = "Hello World";
        byte [] key = generateKey(randomNumberSeed.getBytes());
        byte [] encryptData = encrypt(key, data.getBytes());
        String str = Base64.encodeToString(encryptData, Base64.DEFAULT);
        Log.i(TAG, "encrypt data:" + str);
        byte [] decodeData = Base64.decode(str, Base64.DEFAULT);
        Log.i(TAG, "encrypt data:" + new String(decrypt(key, decodeData)));
    }
引用:https://github.com/fred-ye/summary/issues/47

参考:

安卓Sqlite加密---第三方开源-sqlCipher

http://www.bafenbaosoft.com/post/11.html

http://icodingnotes.com/2015/03/09/Android%E7%AC%94%E8%AE%B0%E4%B9%8B%E5%AE%89%E5%85%A8%E7%AF%87%EF%BC%88%E9%9B%B6%EF%BC%89%E2%80%94%E2%80%94%E4%BD%BF%E7%94%A8SQLCipher%E5%8A%A0%E5%AF%86SQLite%E6%95%B0%E6%8D%AE%E5%BA%93/

SQLite全面学习(一)
http://www.codeceo.com/article/sqlite-learning-01.html
android-lite-orm
https://github.com/litesuits/android-lite-orm

你可能感兴趣的:(sqlite3加密)