java通过X509公钥解密

问题描述 投票:0回答:2

因为我试图将文本加密到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)


因为,我试图扭转方法(通过公钥加密和私钥解密),没关系。

有谁能告诉我这是什么问题?

java encryption digital-signature
2个回答
0
投票

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

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


0
投票

你应该最后一次只调用doFinal()一次。每隔一次你应该打电话给update()

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

© www.soinside.com 2019 - 2024. All rights reserved.