Skip to content

Instantly share code, notes, and snippets.

@zukopvd
Created January 29, 2018 09:05
Show Gist options
  • Save zukopvd/a591c1f0c7ec7403c91074e195b4a920 to your computer and use it in GitHub Desktop.
Save zukopvd/a591c1f0c7ec7403c91074e195b4a920 to your computer and use it in GitHub Desktop.
Android Decryptor (Helper class)
class Decryptor(private val storage: SharedPreferences) {
private val ANDROID_KEY_STORE = "AndroidKeyStore"
private val TRANSFORMATION = "AES/GCM/NoPadding"
private var keyStore: KeyStore? = null
init {
initKeyStore()
}
@Throws(Exception::class)
private fun initKeyStore() {
keyStore = KeyStore.getInstance(ANDROID_KEY_STORE)
keyStore!!.load(null)
}
@Throws(Exception::class)
fun decryptDataWithAES(alias: String): String {
var alias = alias
alias = alias + "_AES"
val base64InitVector = storage.getString(alias + "_initVector", null)
val base64Encryption = storage.getString(alias + "_encryption", null)
if (TextUtils.isEmpty(base64InitVector) || TextUtils.isEmpty(base64Encryption))
throw NullPointerException("Not found initialization vector or encryption data for specified alias")
val encryptionIv = Base64.decode(base64InitVector, Base64.NO_WRAP)
val encryptedData = Base64.decode(base64Encryption, Base64.NO_WRAP)
Log.d("AndroidKeyStore", "encrypted data: " + Arrays.toString(encryptedData) + " encrypted iv: "
+ Arrays.toString(encryptionIv))
val cipher = Cipher.getInstance(TRANSFORMATION)
val spec = GCMParameterSpec(128, encryptionIv)
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec)
return String(cipher.doFinal(encryptedData), StandardCharsets.UTF_8)
}
fun decryptDataWithRSA(alias: String): String {
var alias = alias
alias = alias + "_RSA"
val base64PublicKey = storage.getString(alias + "_publicKey", null)
val base64Encryption = storage.getString(alias + "_encryption", null)
val keyBytes = Base64.decode(base64PublicKey, Base64.NO_WRAP)
val encryption = Base64.decode(base64Encryption, Base64.NO_WRAP)
val spec = X509EncodedKeySpec(keyBytes)
var decodedBytes = ByteArray(0)
try {
val keyFactory = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_RSA)
val key = keyFactory.generatePublic(spec)
val cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_RSA)
cipher.init(Cipher.DECRYPT_MODE, key)
decodedBytes = cipher.doFinal(encryption)
} catch (e: Exception) {
e.printStackTrace()
}
return String(decodedBytes, StandardCharsets.UTF_8)
}
@Throws(Exception::class)
private fun getSecretKey(alias: String): SecretKey {
return (keyStore!!.getEntry(alias, null) as KeyStore.SecretKeyEntry).getSecretKey()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment