Php Android跨平台加密

时间:2013-08-04 13:14:47

标签: php android 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);
   }

但数据显示不正确......有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您爱上了the mcrypt trap

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

改为查看libsodium。有针对Android,iOS和PHP的绑定。如果您升级到PHP 7.2或更高版本,则应该已经安装了它。