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