简体   繁体   English

Java中的错误填充异常(RSA解密)

[英]bad padding exception in java (RSA Decryption)

I am facing some issues when decrypt a RSA Base64 encoded string in java.RSA encrypted string is made by c#.Net. 解密java中的RSA Base64编码字符串时遇到一些问题。RSA加密字符串由c#.Net生成。

Actually, I created a public and private key by using java. 实际上,我使用java创建了一个公共和私有密钥。 Then I exchanged the public key to .Net Team. 然后,我将公共密钥交换给.Net团队。 They encrypted a string by using the public key with the use of RSACryptoServiceProvider class. 他们通过使用公共密钥和RSACryptoServiceProvider类对字符串进行加密。

.Net code: .Net代码:

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize);
rsa.FromXmlString(publicKey);
.......
.......
byte[] encryptedBytes = rsa.Encrypt(tempBytes, false);
Array.Reverse(encryptedBytes);
stringBuilder.Append(Convert.ToBase64String(encryptedBytes));

Java decrypt Code: Java解密代码:

   public static void doDecrypt( BigInteger  modules, BigInteger  d , String encrypted )
    {
            try {
                    byte[] decodedBytes = Base64.decodeBase64( encrypted );
                    KeyFactory factory = KeyFactory.getInstance("RSA");
                    Cipher cipher = Cipher.getInstance("RSA");

                    RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modules, d);
                    PrivateKey privKey = factory.generatePrivate(privSpec);

                    cipher.init(Cipher.DECRYPT_MODE, privKey);
                    byte[] decrypted = cipher.doFinal(decodedBytes) ;
                    System.out.println("decrypted: " + new String(decrypted));
            }
            catch (Exception e) {
                    e.printStackTrace();
            }

    }

While decrypting the string, It says the following error. 解密字符串时,显示以下错误。

javax.crypto.BadPaddingException: Data must start with zero
   at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:308)
   at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:255)
   at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
   at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
   at javax.crypto.Cipher.doFinal(DashoA13*..)

then , I tried with 然后,我尝试了

 Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");

But, It gives junk characters, Which I could not relate to my desired plain text. 但是,它提供了垃圾字符,我无法将其与所需的纯文本相关联。 I think , Somewhere I am missing to do something.Please guide me on this. 我想,我想在某处做某事。请对此进行指导。

rsa.Encrypt(tempBytes, false)

leads to PKCS#1 v1.5 padding. 导致PKCS#1 v1.5填充。 So you must use the same on the java side. 因此,您必须在Java端使用相同的名称。 Try to use 尝试使用

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

I think the windows API uses ECB by default, but you might want to try other modes like CBC or CFB too. 我认为Windows API默认使用ECB,但您可能也想尝试其他模式,例如CBC或CFB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM