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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值