我正在Android中实现RSA加密和解密。我可以很好地执行加密(publickey)。但是在解密(私钥)中我得到了一个例外..
java.security.spec.InvalidKeySpecException:java.lang.RuntimeException:error:0D0680A8:an1 encoding routines:ASNl_CHECK_TLEN:wrong tag
当我调用此函数时
try
{
encrypt_text.setText(decrypt(filecopy1,text_cipher));
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
System.out.println("Exception is>>"+e);
}
public static String decrypt(String filePath1, String encrypted) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException,NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
InputStream stream = new FileInputStream(filePath1);
byte[] encodedKey1 = new byte[stream.available()];
stream.read(encodedKey1);
X509EncodedKeySpec publicKeySpec1 = new X509EncodedKeySpec(encodedKey1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
PublicKey pkPublic1 = kf1.generatePublic(publicKeySpec1);
Cipher pkCipher1 = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
pkCipher1.init(Cipher.DECRYPT_MODE, pkPublic1);
byte[] decoded = Base64Coder.decode(encrypted);
byte[] decryptedInByte = pkCipher1.doFinal(decoded);
return new String(decryptedInByte);
// return encrypted;
}
导入私钥。当我打电话给他们上面的照片。 提前谢谢。
答案 0 :(得分:0)
此代码显然不正确
KeyFactory kf1 = KeyFactory.getInstance("RSA");
PublicKey pkPublic1 = kf1.generatePublic(publicKeySpec1);
Cipher pkCipher1 = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
pkCipher1.init(Cipher.DECRYPT_MODE, pkPublic1)
您需要使用私钥进行解密