java AES加密然后使用相同的密钥和IV在PHP中解密

时间:2016-07-11 00:57:07

标签: java php android encryption aes

我遵循本指南AES encryption on Java side - decryption on PHP side and selecting a single key,但接受的答案并没有真正起作用。我甚至在java中硬编码了KEY和IV值,这样我确信我在PHP中具有相同的值。

private static final byte[] keyValue =
        new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',
                'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };

private static final byte[] ivValue =
        new byte[] { '0', '1', '2', '3', '4', '5', '6',
                '7', '8', '9', '0','1', '2', '3', '4', '5' };

JAVA(关键)代:

String ALGO = "AES/CBC/ZeroBytePadding";
Key key = new SecretKeySpec(keyValue, ALGO);

JAVA(iv)代:

IvParameterSpec ivSpec = new IvParameterSpec(ivValue); 

然后我用它来加密/解密JAVA,如下所示:

  //ENCRYPTION
  String encrypted = encrypt("Hello World!",key,ivSpec);

  //DECRYPTION
  String decrypted = decrypt(encrypted,key,ivSpec);

public static String encrypt(String Data, Key key, IvParameterSpec ivSpec) throws Exception {

    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, key, ivSpec);       
    byte[] encVal = c.doFinal(Data.getBytes());     
    String encryptedValue = Base64.encodeToString(encVal, Base64.NO_WRAP);
    return encryptedValue;
}


public static String decrypt(String encryptedData, Key key, IvParameterSpec ivSpec) throws Exception {

    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key, ivSpec);   
    byte[] decordedValue = Base64.decode(encryptedData,Base64.NO_WRAP);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
}

现在,在PHP中,我通过POST获得加密值,并且我硬编码了KEY和IV值:

$encrypted = $_POST["encrypted"];
$key = "TheBestSecretKey";
$iv = "0123456789012345";

$decrypted = decryptMessage($encrypted,$key,$iv);

function decryptMessage($encrypted,$key,$iv)
{
   $ivNum = (int)$iv;
   $ivIn = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), $ivNum);
   $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $ivIn);
}

加密消息:TXCv3f + r + h71y / NzCk08Hw ==

(解密)变量的预期结果:“Hellow World!”

(解密)变量的当前结果: @ 6 I Ԗmݕ WMu

是否有其他解决方法可以达到我的预期效果。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您需要以十六进制提供密钥,iv,输入数据和加密数据,以便检查它们,加密适用于数据,而不是字符串。

  

键:546865426573745365637265744b6579
  iv:30313233343536373839303132333435
  文字:48656c6c6f7720576f726c6421

并且在CBC模式下使用零填充进行加密应该加密:

   AE64AA4836D7251E03070C1647A4B531

但你没有,你得到

  

4D70AFDDFFABFA1EF5CBF3730A4D3C1F

所以看起来加密很糟糕。

请参阅:AES CALCULATOR