我正在尝试使用RSA和我的私钥(大小为4096)解密字符串。我遇到了错误:
控制台显示错误:0D0680A8:asn1编码例程:ASN1_CHECK_TLEN:错误的标签 这是我的代码:
public String decrypt(String texte ) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String stringKey = "MIIJJwIBAAKCAgEAuLAzezndEnAt8oT7czUcuZhJfDgrIhOyYOlnfoH8p5vbA8PW OoUoe0Gt85EJT6cRrKv+uB+IfZEMDIML3WXy8k7MJOGuDZVMLf03K6lmP6W1BJXL PrU1d0f88SSWK477LTmIm+PxKBMx7ubJHR71D/abUScyvyhv3hxhYQkRy8NE8kP+ eHfEZQbVfT4h2nvy8q535DqvvU67LE6ZZvlY6tbt5uXllEK633fdcMthO6wHoMui ivGwVTGFhAs74TdeKLhBQXQAUb7ZDCgzEWdaO6TxNEW/WZ4pNl1uOJRhRnK2pGrw RtHD+nexnlMxH9EuAmJnAgdPWG2ShX24Ur1wizL2de55ZVimHCWNMB1L8NsHBe81 A0GXvxWZIePieAtIRPNWQPu1PwokOhaN9PEeL/mQdquFBP1AfZut5uF2qhpKxoCt eD5D3+wIMa4XIzhvYZy0aL7PAIrMVM4yHOegKvqTp1WBeelTiNL/2fHDbZ7FqXNV 5ZsDbDtnut1oZmfv0itoHRlvz2YdXiA6a95xAg2/fLsMpU7XtYZEAFc238sd/mXc +gAVGduZMzR5tY4zEbHWsOu3mqZaYYnhEpYEwz1+XPA+8duGusKJ9HCF4vTPEFFy ooLPjZ609wx/xod1jrto1cgfVF55WfodTHtDHKFZTQsZght1O0e18rss9OsCAwEA AQKCAgAZQifYS4KbmfH+wAcvq2zhSR2LupbTk0QLEwDPgXGPbrZWXns3B60Qplvm +sf+N8goCGHOxqlBGww9zdJali3Sy8oJpT/LpcaEZ6Qa+ZD9VWlbVi00x02noZXL WQicrnJVrg+r2lHJ/E4Q8UlCDVDQvRZi0+yRzjL2eoUq4zWm227bf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QzeNHkmM0s5zkr2vh0in05pZnqinaLrI EKfoG9rOYkwV8A2NoRvgmv5JbWKeG3kzz17Dg3PfZKpftILTishiCx6WFw==";
byte[] keyBytes = stringKey.getBytes();
String painText=texte;
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance(CIPHER_RSA_WITH_PADDING, PROVIDER);
cipher.init(DECRYPT_MODE,privateKey);
byte[] encryptedMessageBytes = Base64.decode(painText.getBytes().toString(),BASE64_FLAG);
return new String(cipher.doFinal(encryptedMessageBytes,0,encryptedMessageBytes.length));
}
错误在这里抛出:
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
答案 0 :(得分:0)
尝试解码RSA私钥(2048位)时,我遇到了类似的错误,但仅适用于棉花糖或更早的版本。牛轧糖和较新的工作正常。这是因为不同版本的Android上的安全提供程序实现不同。要解决此问题,我使用了SpongyCastle提供程序。
我在build.gradle中添加了以下行:
implementation 'com.madgag.spongycastle:prov:1.58.0.0'
以及我的Application类的onCreate()方法的下一行
Security.insertProviderAt(org.spongycastle.jce.provider.BouncyCastleProvider(), 1)
为完整起见,这是我的RSA解密代码:
fun decryptRsa(
cipherText: String,
key: String
): String {
val keySpec = PKCS8EncodedKeySpec(Base64.decode(key, Base64.DEFAULT))
val factory = KeyFactory.getInstance("RSA")
val privateKey: PrivateKey = factory.generatePrivate(keySpec) as RSAPrivateKey
val cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
cipher.init(Cipher.DECRYPT_MODE, privateKey)
val encryptedBytes: ByteArray = Base64.decode(cipherText, Base64.DEFAULT)
return String(cipher.doFinal(encryptedBytes))
}