1

我正在 Android 中实现 RSA 加密和解密。我可以很好地执行加密(公钥)。但是在解密(私钥)中我得到了一个例外..

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;
}

导入一个私钥。当我打电话时会给他们上面的图片。预先感谢。

4

1 回答 1

0

This code is obviously incorrect

KeyFactory kf1 = KeyFactory.getInstance("RSA");
PublicKey pkPublic1 = kf1.generatePublic(publicKeySpec1);

Cipher pkCipher1 = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
pkCipher1.init(Cipher.DECRYPT_MODE, pkPublic1)

You need to use private key for decryption

于 2013-08-21T18:24:01.417 回答