Encryption in Java and Decryption in C# using X509Certificate certificate [The parameter is incorrect exception]

-1

I am encrypting using the public key of the certificate in Java

{  X509Certificate certificate = CertificateManager.getInstance().fetchOpicsCertificate(keystorePath, password);
                PublicKey publicKey = certificate.getPublicKey();
                Cipher c = Cipher.getInstance("RSA/ECB/NoPadding");
                c.init(Cipher.ENCRYPT_MODE, publicKey);
                byte[] encryptedVal = c.doFinal(getBytes(tokenId));
}

 private String getString(byte[] bytes) throws UnsupportedEncodingException {
        return new String(bytes, StandardCharsets.US_ASCII);
    }

    private byte[] getBytes(String str) throws UnsupportedEncodingException {
        return str.getBytes(StandardCharsets.US_ASCII);
    }

and decrypting using the private key of the same certificate on .NET side

 public string DecryptUsingCertificate(X509Certificate2 certificate2, String textToDecrypt)
        {
            byte[] bytesToDescrypt = Convert.FromBase64String(textToDecrypt);
            RSACryptoServiceProvider rsp = (RSACryptoServiceProvider)certificate2.PrivateKey;
            var decryptedByte=rsp.Decrypt(bytesToDescrypt, false);
            var decryptedData = Encoding.ASCII.GetString(decryptedByte);
            return decryptedData.ToString();
        }

Following error is coming:

System.Security.Cryptography.CryptographicException
  HResult=0x80070057
  Message=The parameter is incorrect.

  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>
java
c#
encryption
cryptography
rsa
asked on Stack Overflow Oct 29, 2020 by user2309997

1 Answer

-2

changed the cipher from "Cipher c = Cipher.getInstance("RSA/ECB/NoPadding");" to Cipher c = Cipher.getInstance("RSA");

It's working fine !!!

answered on Stack Overflow Oct 29, 2020 by user2309997

User contributions licensed under CC BY-SA 3.0