在我的程序(服务器端 - JAVA)我创建密钥库文件,使用命令:RSA C#加密的Java解密
keytool -genkey -alias myalias -keyalg RSA -validity 10000 -keystore my.keystore
和出口相关的X509证书有:
keytool -export -alias myalias -file cert.cer -keystore my.keystore
后,我在客户端(C#)保存cert.cer和我写这篇文章的代码:
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);
....
我写在服务器端解决此Java代码:
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);
我收到此错误:
javax.crypto.BadPaddingException: Data must start with zero
你能帮助我吗? 谢谢,
您好GregS,感谢您的回答。 我在java中使用了Apache Commons Codec,但我不知道我可以在哪里下载这些用于C#端的地方,我在那里加密我的数据。我尝试在Java端(服务器)上更改这一行: Cipher decCipher = Cipher.getInstance(“RSA”); 与: 密码decCipher = Cipher.getInstance(“RSA/ECB/NoPadding”); 在这种情况下,我没有收到一些例外情况,但字符串解码与原来的完全不同。你可以帮我吗? 谢谢 – CeccoCQ 2010-05-29 08:54:52
你不应该在C#端需要任何东西,假设convertToHex是正确的。在Java方面,正确的填充应该是OAEP填充之一,我不确定哪一个填充。尝试OAEPWITHSHA1ANDMGF1PADDING – 2010-05-29 12:40:26
感谢GregS,我试试这个方法;) 一个问题:如果我改变这一行byte [] cipherbytes = rsa.Encrypt(plainbytes,true)in byte [] cipherbytes = rsa.Encrypt(plainbytes,false)一个PKCS1 v1.5对不对? 我如何在java端管理这个?谢谢 – CeccoCQ 2010-05-29 12:51:32