我在Java(Android)中使用aes-128-cbc將明文加密爲密文。我能夠在PHP中將這個密文解密爲相應的明文,但不能在Java本身中解密。Java(Android)aes-128-cbc解密爲明文不一致性
用於加密的Java代碼是如下,
String iv = "0000000000000000"; //Ignore security concerns
IvParameterSpec ivspec;
ivspec = new IvParameterSpec(iv.getBytes());
String plaintext = "Top Secret Data";
byte[] encrypted = null;
Cipher cipher;
cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, seckey, ivspec);
encrypted = cipher.doFinal(padString(plaintext).getBytes());
ciphertext = Base64.encodeToString(encrypted, Base64.DEFAULT);
Log.i("Encrypted Base64 Data", ciphertext);
相應PHP代碼,其能夠解密此成功地是如下,
public function decrypt($data)
{
$key = $_SESSION['sessionkey'];
$iv = "0000000000000000";
$data = base64_decode($data);
$encobj = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($encobj, $key, $iv);
$decrypted = mdecrypt_generic($encobj, $data);
mcrypt_generic_deinit($encobj);
mcrypt_module_close($encobj);
return utf8_encode(trim($decrypted));
}
用於解密的有問題的Java代碼,其反轉到錯誤的明文如下
String iv = "0000000000000000";
IvParameterSpec ivspec;
ivspec = new IvParameterSpec(iv.getBytes());
byte[] decrypted = null;
Cipher cipher;
cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, seckey, ivspec);
decrypted = cipher.doFinal(Base64.decode(ciphertext, Base64.DEFAULT));
Log.i("Decrypted Data",decrypted.toString());
我會讚賞如果有人能指出Java解密代碼出了什麼問題,就吃了它。
我想有你的加密和在Java您的解密代碼之間的相似性:因此不解密的字節數組(字節[])?在這種情況下,您可能需要字符串轉換,如下所示:String resp = new String(解密) – Dien