2012-07-08 82 views
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) 

任何想法?

回答

3

我希望我可以创建具有的CipherData一个新的字符串作为PARM

cipherData号是任意的二进制数据。它是而不是编码文本,这是各种字符串构造函数所期望的。 (顺便说一句,你应该几乎从不电话String.getBytes()new String(byte[])不指定编码。始终指定适当的编码,这将视情况而定)。

无论是传输数据二进制数据而不是通过文本,或者使用Base64来安全地将二进制数据编码为文本,然后在解密之前将其从Base64解码为二进制文件。有一个易于使用的public domain Base64 encoder

+0

像http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html? – user1177292 2012-07-08 18:52:26

+0

@ user1177292:是的,这可以正常工作 - 或者在我的答案中查看另一个链接,该链接只是可以包含在项目中的单个源文件。 – 2012-07-08 18:55:31