Android KeyStore with 3DES

444 Views Asked by At

Im trying save datas to android keystore with 3DES. But 3des algorithm is depracted. So i decided to write my own. But im getting "Attempt to get length of null array" null pointer exception.When i create that keystore with aes everythings fine. Am i skipping some parts? How can ı create android keystore with 3DES?

This is my encyrpt class :

class Encrypt {
private val TRANSFORMATION = "AES/GCM/NoPadding"
private val TRANSFORMATION = "DESede"
private val ANDROID_KEY_STORE = "AndroidKeyStore"

private var encryption: ByteArray? = null
private var iv: ByteArray? = null

private var keyStore: KeyStore? = null

init {
    initKeyStore()
}

private fun initKeyStore() {
    keyStore = KeyStore.getInstance(ANDROID_KEY_STORE)
    keyStore!!.load(null)
}

fun encryptText(alias: String, textToEncrypt: String): ByteArray? {
    val cipher = Cipher.getInstance(TRANSFORMATION)
    cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(alias))
    iv = cipher.iv
    return cipher.doFinal(textToEncrypt.toByteArray(charset("UTF-8"))).also { encryption = it }
}

private fun getSecretKey(alias: String): SecretKey {


    return generateOwnKey(alias).secretKey
}

fun getEncryption(): ByteArray? {
    return encryption
}

fun getIv(): ByteArray? {
    return iv
}

fun generateOwnKey(alias: String?): KeyStore.SecretKeyEntry {
    val myKey = SecretKeySpec(alias?.toByteArray(), "DESede")
    Log.i("type", myKey.algorithm)
    val secretKeyEntry = KeyStore.SecretKeyEntry(myKey)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        keyStore?.setEntry(
            alias,
            KeyStore.SecretKeyEntry(myKey),
            KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .build()
        )
    }
     return secretKeyEntry

} }

and Decrypt class :

    private val TRANSFORMATION = "DESede"
private val ANDROID_KEY_STORE = "AndroidKeyStore"

private var keyStore: KeyStore? = null

init {
    initKeyStore()
}

private fun initKeyStore() {
    keyStore = KeyStore.getInstance(ANDROID_KEY_STORE)
    keyStore!!.load(null)
}

fun decryptData(alias: String, encryptedData: ByteArray?, encryptionIv: ByteArray?): String? {
    val cipher = Cipher.getInstance(TRANSFORMATION)

    val ivspec = IvParameterSpec(encryptionIv)
    cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), ivspec)
    return String(cipher.doFinal(encryptedData), Charsets.UTF_8)
}

private fun getSecretKey(alias: String): SecretKey? {
    return (keyStore!!.getEntry(alias, null) as KeyStore.SecretKeyEntry).secretKey
}
0

There are 0 best solutions below