如何在Android中使用SQLcipher数据库保护用于Greendao的密码?

时间:2018-08-13 09:09:14

标签: android android-keystore greendao sqlcipher-android

我想用SQLCipher保护用于Greendao数据库的密码。我正在使用密钥库来生成密钥,并使用该密钥对从服务器获取的密码进行加密。我想使用加密的数据作为数据库的密码。 问题是每次生成不同的加密数据时都会进行加密。 (我知道它正在按预期工作)。有什么办法可以每次生成相似的加密数据吗?我正在使用以下代码进行加密:-

 private fun generateSecureKey() {
    val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
    val keyGenParameterSpec = KeyGenParameterSpec.Builder(BuildConfig.APPLICATION_ID,
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .setRandomizedEncryptionRequired(false)
            .build()
    keyGenerator.init(keyGenParameterSpec)
    keyGenerator.generateKey()
}

private fun getSecureKeyFromKeyStore(): SecretKey {
    val keyStore = KeyStore.getInstance("AndroidKeyStore")
    keyStore.load(null)
    return if (keyStore.containsAlias(BuildConfig.APPLICATION_ID)) {
        val secretKeyEntry = keyStore.getEntry(BuildConfig.APPLICATION_ID, null) as KeyStore.SecretKeyEntry
        secretKeyEntry.secretKey
    } else {
        generateSecureKey()
        val secretKeyEntry = keyStore.getEntry(BuildConfig.APPLICATION_ID, null) as KeyStore.SecretKeyEntry
        secretKeyEntry.secretKey
    }
}

private fun encryptData(secureData: String): String {

    val cipher = Cipher.getInstance("AES/GCM/NoPadding")
    cipher.init(Cipher.ENCRYPT_MODE, getSecureKeyFromKeyStore())
    val bytes = cipher.doFinal(secureData.toByteArray())
    return Base64.encodeToString(bytes, Base64.DEFAULT)
}

0 个答案:

没有答案