Php Android跨平台加密


Php Android cross platform encryption

我在Php WebSerice中使用此代码来加密和解密数据:

<?php
/**
 * Class that will deal with the encryption of the api
 */
class Encryption
{
    private $KEY = "some key"; //the encryption key
    /**
     * Encrypt data
     * @param $data string the data to encrypt
     * @return string the encrypted data
     */
    public function encrypt($data)
    {
        if (!empty($data))
            return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->KEY, $data, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
    }
    /**
     * Decrypt data
     * @param $data string the data to decrypt
     * @return string the decrypted data
     */
    public function decrypt($data)
    {
        if (!empty($data))
            return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->KEY, base64_decode($data), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
    }
}
?>

在我的Android应用程序中,这是我的加密方法:

    /**
     * api encryption key
     */
    private static final String KEY = Base64.encodeBytes("some key".getBytes());
    /**
     * api's encryption algorithm
     */
    private static final String ALGOITHM = "AES/CBC/PKCS5Padding";  

    /**
     * Encrypt a data string
     * @param data the data string
     * @return an encrypted string
     * @throws Exception when encryption failed 
     */
    public static String encrypt(String data) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(), ALGOITHM);
        Cipher cipher = Cipher.getInstance(ALGOITHM);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] dataBytes = data.getBytes(););
        byte[] encryptedBytes = cipher.doFinal(dataBytes);
        return Base64.encodeBytes(encryptedBytes);
   }

但数据显示不对。。。有什么想法吗?

您落入了mcrypt陷阱。

MCRYPT_RIJNDAEL_256不是AES-256,它是Rijndael的256位块大小变体。即使使用256位密钥,AES也始终是128位块大小。

转而研究利钠。有Android、iOS和PHP的绑定。如果你升级到PHP 7.2或更高版本,你应该已经安装好了。