开发者

RSA Encryption/Decryption Issue: Encrypted Text from .Net not decrypting in Java

I am facing issues in decryption in Java. Following is the error encountered:

javax.crypto.BadPaddingException: Blocktype mismatch: -127
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:311)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:255)

The text is encrypted in .Net with the following code:

public string EncryptString( string inputString, int dwKeySize, string xmlString )
        {
            RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize );
            rsaCryptoServiceProvider.FromXmlString( xmlString );
            int keySize = dwKeySize / 8;
            byte[] bytes = Encoding.UTF32.GetBytes( inputString );
            int maxLength = keySize - 42;
            int dataLength = bytes.Length;
            int iterations = dataLength / maxLength;
            StringBuilder stringBuilder = new StringBuilder();
            for( int i = 0; i <= iterations; i++ )
            {
                byte[] tempBytes = new byte[ ( dataLength - maxLength * i > maxLength ) ? maxLength : dataLength - maxLength * i ];
                Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, tempBytes.Length );
                byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes, true );

                Array.Reverse( encryptedBytes );
                stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );               
   开发者_高级运维         }           
            return stringBuilder.ToString();
        }

The code for decrytion is JAVA is:

PrivateKey privKey = readPrivateKey(); // reads the private key 
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privKey);
            byte[] encryptedBytes = Base64.decodeBase64(encryptedText.getBytes("UTF-32"));
        encryptedBytes = reverse(b); // reverse the bytes 
        byte[] decrypted = cipher.doFinal(encryptedBytes);
        return new String(decrypted);

Am I missing something here? How can I make both way encryption/decryption?


Your C# application is using OAEP padding PKSC v2 while java is using PKSC v1.5 Try changing your C# code to:

ptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes, false );


This may help:

http://jafetsanchez.com/post/7562162652/rijndael-on-c-and-java

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜