RSA C# Encrypt Java Decrypt

Posted by user353030 on Stack Overflow See other posts from Stack Overflow or by user353030
Published on 2010-05-28T15:16:08Z Indexed on 2010/05/28 15:22 UTC
Read the original article Hit count: 558

Filed under:
|
|
|
|

Hi guys,

In my program (server side - Java) I've created keystore file, with command:

keytool -genkey -alias myalias -keyalg RSA -validity 10000 -keystore my.keystore

and exported related X509 certificate with:

keytool -export -alias myalias -file cert.cer -keystore my.keystore

After I saved cert.cer on client side (C#) and I write this code:

X509Certificate2 x509 = new X509Certificate2();
byte[] rawData = ReadFile("mycert.cer");
x509.Import(rawData);

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key;
byte[] plainbytes = System.Text.Encoding.ASCII.GetBytes("My Secret");
byte[] cipherbytes = rsa.Encrypt(plainbytes, true);
String cipherHex = convertToHex(cipherContent);
byte[] byteArray = encoding.GetBytes(cipherHex);

....

I write this Java code on server side:

keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream("C:\\my.keystore"), "mypass".toCharArray());
Key key = keyStore.getKey("myalias", "mypass".toCharArray());
if (key instanceof PrivateKey) {
    Certificate cert = keyStore.getCertificate("myalias");
    PublicKey pubKey = cert.getPublicKey();
    privKey = (PrivateKey)key;
}
byte[] toDecodeBytes = new BigInteger(encodeMessageHex, 16).toByteArray();
Cipher decCipher = Cipher.getInstance("RSA");
decCipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] decodeMessageBytes = decCipher.doFinal(toDecodeBytes);
String decodeMessageString = new String(decodeMessageBytes);

I receive this error:

javax.crypto.BadPaddingException: Data must start with zero

Can you help me, please? Thanks thanks,

© Stack Overflow or respective owner

Related posts about c#

Related posts about java