· 7 years ago · Feb 12, 2018, 06:28 AM
1class Decryptor(private val storage: SharedPreferences) {
2 private val ANDROID_KEY_STORE = "AndroidKeyStore"
3 private val TRANSFORMATION = "AES/GCM/NoPadding"
4
5 private var keyStore: KeyStore? = null
6
7 init {
8 initKeyStore()
9 }
10
11 @Throws(Exception::class)
12 private fun initKeyStore() {
13 keyStore = KeyStore.getInstance(ANDROID_KEY_STORE)
14 keyStore!!.load(null)
15 }
16
17 @Throws(Exception::class)
18 fun decryptDataWithAES(alias: String): String {
19 var alias = alias
20 alias = alias + "_AES"
21
22 val base64InitVector = storage.getString(alias + "_initVector", null)
23 val base64Encryption = storage.getString(alias + "_encryption", null)
24
25 if (TextUtils.isEmpty(base64InitVector) || TextUtils.isEmpty(base64Encryption))
26 throw NullPointerException("Not found initialization vector or encryption data for specified alias")
27
28 val encryptionIv = Base64.decode(base64InitVector, Base64.NO_WRAP)
29 val encryptedData = Base64.decode(base64Encryption, Base64.NO_WRAP)
30
31 Log.d("AndroidKeyStore", "encrypted data: " + Arrays.toString(encryptedData) + " encrypted iv: "
32 + Arrays.toString(encryptionIv))
33 val cipher = Cipher.getInstance(TRANSFORMATION)
34 val spec = GCMParameterSpec(128, encryptionIv)
35 cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec)
36
37 return String(cipher.doFinal(encryptedData), StandardCharsets.UTF_8)
38 }
39
40 fun decryptDataWithRSA(alias: String): String {
41 var alias = alias
42 alias = alias + "_RSA"
43 val base64PublicKey = storage.getString(alias + "_publicKey", null)
44 val base64Encryption = storage.getString(alias + "_encryption", null)
45
46 val keyBytes = Base64.decode(base64PublicKey, Base64.NO_WRAP)
47 val encryption = Base64.decode(base64Encryption, Base64.NO_WRAP)
48 val spec = X509EncodedKeySpec(keyBytes)
49
50 var decodedBytes = ByteArray(0)
51 try {
52 val keyFactory = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_RSA)
53 val key = keyFactory.generatePublic(spec)
54 val cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_RSA)
55 cipher.init(Cipher.DECRYPT_MODE, key)
56 decodedBytes = cipher.doFinal(encryption)
57 } catch (e: Exception) {
58 e.printStackTrace()
59 }
60
61 return String(decodedBytes, StandardCharsets.UTF_8)
62 }
63
64 @Throws(Exception::class)
65 private fun getSecretKey(alias: String): SecretKey {
66 return (keyStore!!.getEntry(alias, null) as KeyStore.SecretKeyEntry).getSecretKey()
67 }
68}