我想用 SQLCipher 保护用于 Greendao db 的密码。我正在使用密钥库生成密钥并使用该密钥加密从服务器获取的密码。我想使用加密数据作为数据库的密码。问题是密码每次生成不同的加密数据。(我知道它按预期工作)。有没有办法每次都生成类似的加密数据?我正在使用以下代码进行加密:-
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)
}