我正在使用RSA加密一个秘密,然后将其发送到另一台主机。该代码在PC上完成时效果很好 - > PC流量,但会引发Android的以下例外 - > PC流量。
The javax.crypto.BadPaddingException: Blocktype mismatch: 0
sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:332)
sun.security.rsa.RSAPadding.unpad(RSAPadding.java:272)
com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:354)
com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:380)
javax.crypto.Cipher.doFinal(Cipher.java:2121)
我该怎么做才能解决这个问题?
public byte[] encrypt(byte[] plaintext){
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plaintext);
}
public byte[] decrypt(byte[] ciphertext){
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(ciphertext);
}
答案 0 :(得分:0)
import android.util.Base64
import java.security.KeyFactory
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher
class RSAUtils {
val ALGORITHM = "RSA"
val PUBLIC_KEY = "" // Enter Public key here
val PRIVATE_KEY = "" // Enter Private key here
fun encrypt(text: String): String? {
return encryptRSA(text)?.let { byteArrayToString(it) }
}
fun decrypt(text: String): String {
return decryptRSA(stringToByteArray(text))
}
private fun encryptRSA(text: String): ByteArray? {
var cipherText: ByteArray? = null
try {
// generate publicKey instance
val byteKey = stringToByteArray(PUBLIC_KEY)
val X509publicKey = X509EncodedKeySpec(byteKey)
val kf: KeyFactory = KeyFactory.getInstance(ALGORITHM)
val publicKey = kf.generatePublic(X509publicKey)
// get an RSA cipher object and print the provider
val cipher: Cipher = Cipher.getInstance(ALGORITHM)
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
cipherText = cipher.doFinal(text.toByteArray())
} catch (e: Exception) {
e.printStackTrace()
}
return cipherText
}
private fun decryptRSA(text: ByteArray): String {
var dectyptedText: ByteArray? = null
try {
// generate privateKey instance
val byteKey = stringToByteArray(PRIVATE_KEY)
val keySpec = PKCS8EncodedKeySpec(byteKey)
val kf: KeyFactory = KeyFactory.getInstance(ALGORITHM)
val privateKey = kf.generatePrivate(keySpec)
// get an RSA cipher object and print the provider
val cipher = Cipher.getInstance(ALGORITHM)
// decrypt the text using the private key
cipher.init(Cipher.DECRYPT_MODE, privateKey)
dectyptedText = cipher.doFinal(text)
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
return String(dectyptedText!!)
}
private fun stringToByteArray(text: String): ByteArray {
return Base64.decode(text, Base64.DEFAULT)
}
private fun byteArrayToString(byteArray: ByteArray): String {
return Base64.encodeToString(byteArray, Base64.DEFAULT)
}
}
https://github.com/kushalgupta0565/RSAEncryption - 在安卓中运行良好,你只需要传递你的公钥/私钥