java通过X509公钥解密

时间:2017-12-20 04:02:47

标签: java encryption digital-signature

因为我正在尝试将文本加密到PKCS8私钥并通过X509公钥解密。



      public static String decryptByPublicKey(String data, String keyHash) {
            final String KEY_ALGORITHM = "RSA";
            final int MAX_DECRYPT_BLOCK = 128;

            try {

                byte[] keyBytes = Base64.getDecoder().decode(keyHash);

                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
                Key publicKey = keyFactory.generatePublic(publicKeySpec);
                Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
                cipher.init(Cipher.DECRYPT_MODE, publicKey);

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int offSet = 0;
                byte[] cache;
                byte[] buffer =data.getBytes();
                int inputLen = buffer.length;
                int i = 0;

                while (inputLen - offSet > 0) {
                    if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                        cache = cipher.doFinal(buffer, offSet, MAX_DECRYPT_BLOCK);
                    } else {
                        cache = cipher.doFinal(buffer, offSet, inputLen - offSet);
                    }
                    out.write(cache, 0, cache.length);
                    i++;
                    offSet = i * MAX_DECRYPT_BLOCK;
                }

                byte[] decryptedData = out.toByteArray();
                out.close();

                return new String(decryptedData, "UTF-8");

            } catch (Exception e) {
                logger.error("decryptByPublicKey - Exception: ", e);
                e.printStackTrace();
            }

            return null;
        }
    It shows BadPaddingException.
    javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
    at javax.crypto.Cipher.doFinal(Cipher.java:2223)


因为,我试图反转该方法(通过公钥加密并通过私钥解密),这没关系。

有人能告诉我问题是什么吗?

2 个答案:

答案 0 :(得分:0)

从给出的错误 显示BadPaddingException.javax.crypto.BadPaddingException:解密错误

请检查缓冲区的大小(int inputLen = buffer.length)。您需要将数据填充为所需的块大小。

答案 1 :(得分:0)

您最后一次只能拨打doFinal()一次。每隔一次你应该拨打update()

但这样做并没有意义。使用私钥加密不是加密,而是数字签名。