Java中的填充异常(RSA Decryption) [英] bad padding exception in java (RSA Decryption)

查看:169
本文介绍了Java中的填充异常(RSA Decryption)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在解密java.RSA中的RSA Base64编码字符串时,我面临一些问题。加密字符串由c#.Net创建。

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

实际上,我使用java创建了一个公钥和私钥。然后我把公钥交给了.Net团队。他们通过使用公钥加密了一个字符串,使用 RSACryptoServiceProvider 类。

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代码: p>

.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解密代码:

   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*..)

然后,我尝试使用

 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)

导致PKCS#1 v1.5填充。所以你必须在java方面使用相同的。尝试使用

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");

我认为Windows API默认使用ECB,但您可能想尝试其他模式,如CBC或CFB。

I think the windows API uses ECB by default, but you might want to try other modes like CBC or CFB too.

这篇关于Java中的填充异常(RSA Decryption)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆