问题描述
尝试解密加密的字符串时遇到此问题。我读了很多书,也从Stack Overflow搜索答案,但是没有任何效果。您可以看到我附加的代码,它并不复杂,但是问题使我感到困惑。我正在使用Kotlin,是的,它用于Android。
private fun generateKeyPair() {
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
keyStore.load(null)
if (keyStore.containsAlias(keyAlias)) return
val keyGenerator =
KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA,ANDROID_KEYSTORE)
val builder = KeyGenParameterSpec.Builder(
keyAlias,KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setKeySize(4096)
.setDigests(KeyProperties.DIGEST_SHA256)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setRandomizedEncryptionRequired(true)
.setUserAuthenticationRequired(false)
keyGenerator.initialize(builder.build(),SecureRandom())
keyGenerator.generateKeyPair()
}
fun encryptApplicationKey(
data: String
) {
val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
cipher.init(Cipher.ENCRYPT_MODE,getPublicKey())
val encryptResult = cipher.doFinal(data.toByteArray())
val encryptResultString = Base64.encodeToString(encryptResult,Base64.DEFAULT)
text_view_info.text = encryptResultString
}
fun decryptApplicationKey(data: String) {
val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
cipher.init(Cipher.DECRYPT_MODE,getPrivateKey()) //it throw Caused by: android.security.KeyStoreException: Incompatible padding mode
val encryptedData = Base64.decode(data,Base64.DEFAULT)
val decryptResult = cipher.doFinal(encryptedData)
val decryptResultString = String(decryptResult)
text_view_info.text = decryptResultString
}
fun getPublicKey(): PublicKey {
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
keyStore.load(null)
val publicKey = keyStore.getCertificate(keyAlias).publicKey
val unrestrictedPublicKey: PublicKey =
KeyFactory.getInstance(publicKey.algorithm).generatePublic(
X509EncodedKeySpec(publicKey.encoded)
)
return unrestrictedPublicKey
}
fun getPrivateKey(): PrivateKey {
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
keyStore.load(null)
return keyStore.getKey(keyAlias,null) as PrivateKey
}
当我调试getPrivateKey()
函数时,它返回AndroidKeyStoreRSAPrivateKey
对象。我不知道问题是否与PKCS1Padding的使用有关,但是当我使用OAEP填充时,运行它不会崩溃。
设备会影响结果吗?我已经评论了崩溃发生的位置。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)