【问题标题】:Sending encrypted data between Android app and PHP script在 Android 应用程序和 PHP 脚本之间发送加密数据
【发布时间】:2015-06-27 23:25:33
【问题描述】:

我正在尝试将加密数据从我的 android 应用程序发送到解密数据的 PHP 脚本。

在android中我使用以下加密方法:

public String encryptAES(String key, String mdp) throws NoSuchPaddingException, NoSuchAlgorithmException {
    byte[] skey = key.getBytes();
    byte[] pwd = mdp.getBytes();
    byte[] encrypted = null;
    SecretKeySpec secretKeySpec = new SecretKeySpec(skey, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    try {
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    try {
        encrypted = cipher.doFinal(pwd);
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        e.printStackTrace();
    }
    return Arrays.toString(Base64.encode(encrypted, Base64.DEFAULT));
}

我用它在 PHP 中解密:

$data = mcrypt_decrypt(MCRYPT_RIJNADEAL_128, $key, $cipherText, MCRYPT_MODE_ECB);

问题是它不能解密为 PHP 中想要的纯文本。

【问题讨论】:

    标签: php android encryption encoding


    【解决方案1】:

    Arrays#toString() 返回带有[] 和逗号的数组表示。可以通过Base64 class直接获取Base 64编码的字符串:

    return Base64.encodeToString(encrypted, Base64.DEFAULT);
    

    在PHP中你需要在使用前对密文进行解码

    $cipherText = base64_decode($cipherText);
    

    为确保使用相同的操作模式,需要提供完整的密码字符串(提供者可能有不同的默认值,所以需要自己指定以防出现问题):

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    

    并且在PHP中使用相同的padding(PKCS#5/PKCS#7 padding是一样的)(只提供ZeroPadding)。 This answer 为此提供了代码。


    进一步的安全考虑

    不要使用 ECB 模式。它非常不安全。至少使用随机 IV 的 CBC 模式。 IV 不必保密,因此您可以在编码和发送之前简单地将其添加到密文中。 IV可以在解密前被切下用于解密。

    为了使其更加安全,您应该验证您的密文。这可以使用像 GCM 这样的身份验证模式,也可以使用像 HMAC-SHA256 这样的具有强 MAC 的 encrypt-then-MAC 方案。

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多