2013-04-08 75 views
0

我加密一個字符串,並將其存儲在客戶端的cookie ..但是當我從js發送確切的加密字符串到java代碼它給了我上述的例外。鑑於最後一塊沒有正確填充AES

我使用的加密和解密的代碼是:

public static final String UNICODE_FORMAT = "UTF8"; 

public static String encrypt(String Data, SecretKeySpec skeySpec,IvParameterSpec ivspec) throws Exception { 
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec); 
     byte[] plainBytes = Data.getBytes(UNICODE_FORMAT); 
     byte[] encrypted = cipher.doFinal(plainBytes); 
     String encryption = bytesToString(encrypted); 
     return encryption; 
} 

public static String decrypt(String encryptedData,SecretKeySpec skeySpec,IvParameterSpec ivspec) throws Exception { 
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec); 
    byte[] decryptval = hexToBytes(encryptedData); 
    byte[] decrypted = cipher.doFinal(decryptval); 
    return new String(decrypted); 
} 

public static String bytesToString(byte[] bytes) { 
    HexBinaryAdapter adapter = new HexBinaryAdapter(); 
    String s = adapter.marshal(bytes); 
    return s; 
} 

public static byte[] hexToBytes(String hexString) { 
    HexBinaryAdapter adapter = new HexBinaryAdapter(); 
    byte[] bytes = adapter.unmarshal(hexString); 
    return bytes; 
} 

你能告訴我的問題可能是什麼?我已經嘗試了在stackoverflow.com提及的解決方案,還有一些其他的解決方案,但沒有工作..我得到這個錯誤,因爲我發送加密的字符串到JS,它正在改變字符串的填充?

+0

當你在服務器端運行加密/解密時它工作嗎? – evgenyl 2013-04-08 06:18:12

+0

是的,它確實工作,然後...問題是,只有當我從javascript – 2013-04-08 06:21:50

+1

'新字符串(解密,UNICODE_FORMAT)'返回它,但不能是錯誤。 – 2013-04-08 06:22:45

回答

0

正如@ JoopEggen所述 - 從字節[]創建sting可以打破它。

你可以序列化,而不是從它創建字符串?

相關問題