RSA C# Encrypt Java Decrypt
- by user353030
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,