在android / ios中加密,在php中解密

时间:2014-07-02 16:57:38

标签: php android encryption aes

我正在尝试解密我的网站上的字符串,该字符串在移动设备(Android或ios)上加密。 我有两个设备的类似输出,它使用以下Android代码(没有例外,保持简短)。

public static String encode(String keyString, String stringToEncode){
    SecretKeySpec skeySpec = getKey(keyString);
    byte[] clearText = stringToEncode.getBytes("UTF-8");            
    // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
    final byte[] iv = new byte[16];
    Arrays.fill(iv, (byte) 0x00);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);          
    // Cipher is not thread safe
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);            
    String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.NO_WRAP);
    return encrypedValue;
}


private static SecretKeySpec getKey(String password) throws UnsupportedEncodingException {
    int keyLength = 256;
    byte[] keyBytes = new byte[keyLength / 8];
    // explicitly fill with zeros
    Arrays.fill(keyBytes, (byte) 0x0);
    // if password is shorter then key length, it will be zero-padded to key length
    byte[] passwordBytes = password.getBytes("UTF-8");
    int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
    System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    return key;
}

然后我尝试解密php中的给定输出,几乎半天在线搜索(包括StackOverflow上的许多类似帖子),我发现: http://dev.strategystar.net/2011/10/php-cryptography-padding-ansi-x-923-iso-10126-pkcs7-bit-zero/ 这似乎与我认为我想要/需要的最接近,但仍然无效。

require_once('padCrypt.php');
require_once('AES_Encryption.php');

$key              = "3358733656775333";
//$key            = "33587336567753333358733656775333";
$iv               = "0000000000000000";
$message          = "The quick brown fox jumped over the lazy dog andtrhe doig";
$AES              = new AES_Encryption($key, $iv, 'PKCS7');
$enc = 't12h8jkMrVbFXBUy0ZpwJ0EEoRICsk/NBKniGrDv+/UlAwxBdRuUFp8NDEv3SFXzz0Qaiqt68n2Z9rjUfb5B46BXyAVDlltColEAv3pflkc1NNxByFE4YTpFNH/pXCO1kqGxnrc+e8Sz6Ux+HBJ7c51zzw91EvwpAbq9aVba16q0hzg1izqAXOTYrHFRhX1dIuFbwT4dFWLiZIf/YCsBGhRjTsMKCcliJQQG04K8XKdcr5T/6Tv9CqaEZJk7p+5roo3klCS0rTguDPsz0jY1I7i8XGTwhJrwedjwTRUHREJl6ReXfR2z6Vp3ABG+mkAYyNTAjuNCDXY7P4y8q0VChQp44Eidv/MqCszRXCtjBDVc7yB0fqkzrFgfTNmg27fd0dUOfaLe9Xb5CoMGlIcVEinVwRvgaQatE+RQTamKa2bqRWnfb5anbWdJUWdIdJrVdurzF1XIHRMCgXmqoN8b1KO6qc7DU46vuccxw7cZCUy2Nse27PNqVKVhMYKPhNR7tkwtHUwQ6pj25cnqgbP5wih45stv/BV//l2xcABLIPZWHUx2ciQD+us4SMyPqCvBfSjMnN0yvGI0KiYH1LbfGRdm4ARWbCuWl1eU0Qe5p5OzDzxiXqUCOXbfXPM4Yz8JWcgXGNe8TUwPIrYsQhqVR7IGemUA0pgMWXMfvD846yin7iV7KzfVQXBrJJ5yYf/qP1IIKW/wUzIvi2B8d2aZN+9gy/hEW2OZAZhiAlNs7it2cYSjKbe8SBp7/2tVVa1Hs+GV7epNsX5pTzZOuIbg7vudZ9E4zSPzChewKyems3CTIEQtyz/IhMqRnLYS8ZUEqOxNivwed/vbqm2wLeGHnHH4EahUYUZEbr4gIBJYVZw1wfucd5pdL+J+4uOekeN49vXX4FxO3E8axKmpetewXA==';
$enc = base64_decode($enc, true);
$decrypted  = $AES->decrypt($enc);
var_dump(($decrypted));

由于我不知道这些加密内容是如何运作的,也不是我出错的地方,我希望有人可以帮助我。

到目前为止,我已经尝试过改变所有类型的东西,然后将其设置为rijndael128和rijndael256,更改填充,iv等等。但我完全无能为力。还有什么可以尝试。

任何有用的信息都将非常感激。

1 个答案:

答案 0 :(得分:0)

试用此代码

在android中:

public String encode(String text)
            throws NoPassGivenException, NoTextGivenException {

        if (text.length() == 0 || text == null) {
            throw new NoTextGivenException("Please give text");
        }

        try {
            SecretKeySpec skeySpec = getKey(KEY);

            System.out.println("-----Encoding Key-----"+skeySpec);
            byte[] clearText = text.getBytes("UTF8");

            //IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
            final byte[] iv = new byte[16];
            Arrays.fill(iv, (byte) 0x00);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

            // Cipher is not thread safe
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

//          IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
//          cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);

            String encrypedValue = Base64.encodeToString(
                    cipher.doFinal(clearText), Base64.DEFAULT);
            return new String(encrypedValue);

        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

/**
     * Generates a SecretKeySpec for given password
     * @param password
     * @return SecretKeySpec
     * @throws UnsupportedEncodingException
     */
    public SecretKeySpec getKey(String password)
            throws UnsupportedEncodingException {


        int keyLength = 128;
        byte[] keyBytes = new byte[keyLength / 8];
        // explicitly fill with zeros
        Arrays.fill(keyBytes, (byte) 0x0);

        // if password is shorter then key length, it will be zero-padded
        // to key length
        byte[] passwordBytes = password.getBytes("UTF-8");
        int length = passwordBytes.length < keyBytes.length ?          passwordBytes.length
                : keyBytes.length;
        System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        return key;
    }

在php中:

.// PHP Code to decrypt
    public function decrypt($code) { 

      $decoded = base64_decode($code);
      $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
      $decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, trim($decoded), MCRYPT_MODE_ECB, $iv));
      $blocksize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

     return  $this->pkcs7unpad($decrypted,$blocksize);
    }
 function pkcs7unpad($padded, $blocksize)
    {
        $l = strlen($padded);

        if ($l % $blocksize != 0) 
        {
            throw new Exception("Padded plaintext cannot be divided by the block size");
        }

        $padsize = ord($padded[$l - 1]);

        if ($padsize === 0)
        {
            throw new Exception("Zero padding found instead of PKCS#7 padding");
        }    

        if ($padsize > $blocksize)
        {
            throw new Exception("Incorrect amount of PKCS#7 padding for blocksize");
        }

        // check the correctness of the padding bytes by counting the occurance
        $padding = substr($padded, -1 * $padsize);
        if (substr_count($padding, chr($padsize)) != $padsize)
        {
            throw new Exception("Invalid PKCS#7 padding encountered");
        }

        return substr($padded, 0, $l - $padsize);
    }