bad padding exception in java (RSA Decryption)

2019-03-22 07:40发布

问题:

I am facing some issues when decrypt a RSA Base64 encoded string in java.RSA encrypted string is made by c#.Net.

Actually, I created a public and private key by using java. Then I exchanged the public key to .Net Team. They encrypted a string by using the public key with the use of RSACryptoServiceProvider class.

.Net code:

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:

   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.

回答1:

rsa.Encrypt(tempBytes, false)

leads to PKCS#1 v1.5 padding. So you must use the same on the java side. 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.