2012-07-08 78 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