0
我使用以下代码来加密一些数据,并且我想将解密代码移动到服务器,因此需要将cipherData(这是一个byte []数组)发送给我服务器过REST通过包含加密数据的REST发送字节数组
BigInteger modulus = new BigInteger("blah");
BigInteger exponent = new BigInteger("blah");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory encryptfact = KeyFactory.getInstance("RSA");
PublicKey pubKey = encryptfact.generatePublic(keySpec);
String dataToEncrypt = "Hello World";
/**
* Encrypt data
*/
Cipher encrypt = Cipher.getInstance("RSA");
encrypt.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = encrypt.doFinal(dataToEncrypt.getBytes());
System.out.println("cipherData: " + new String(cipherData));
/**
* Decrypt data
*/
BigInteger privatemodulus = new BigInteger("blah");
BigInteger privateexponent = new BigInteger("blah");
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privatemodulus, privateexponent);
PrivateKey privateKey = encryptfact.generatePrivate(privateKeySpec);
Cipher decrypt = Cipher.getInstance("RSA");
decrypt.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decData = decrypt.doFinal(cipherData);
System.out.println(new String(decData));
这工作正常。
我希望我可以创建具有的CipherData一个新的字符串作为PARM
当我尝试这与上面的例子中,我得到以下错误
byte[] decData = decrypt.doFinal(new String(cipherData).getBytes());
javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:308)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:255)
at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at com.test.EncryptTest.main(EncryptTest.java:52)
任何想法?
像http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html? – user1177292 2012-07-08 18:52:26
@ user1177292:是的,这可以正常工作 - 或者在我的答案中查看另一个链接,该链接只是可以包含在项目中的单个源文件。 – 2012-07-08 18:55:31