0

I am trying to decrypt a string on my website, which wsa encrypted on a mobile device (either Android or ios). I have a similar output from both devices, which uses the following Android code (sans exceptions to keepit short).

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;
}

I then try to decrypt the given output in php, after searching online almost half of the day (including many similar posts here on StackOverflow), I found this: http://dev.strategystar.net/2011/10/php-cryptography-padding-ansi-x-923-iso-10126-pkcs7-bit-zero/ This seems to come the closest to what I think I want/need, but still doesnt work.

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));

As I don't really have any clue how this encryption stuff really works, nor where im going wrong, I hope someone here can assist me.

So far I've looked tried the changing all kinds of stuff along setting it to rijndael128 and rijndael256, changing the padding, the iv etc. But I'm completely clueless what else to try.

Any useful info at all would be greatly appreciated.

BlueEgg
  • 11
  • 3
  • 1
    Are you sure that `"0000000000000000"` in PHP is the same as `byte[]` with zero values in Java? This question applies to your handling of both the key and IV. – Oleg Estekhin Jul 03 '14 at 02:08
  • @OlegEstekhin If you see [`getKey()`](http://stackoverflow.com/a/15244133/589259) in encryption code, you can be sure that things will never work reliably anyway. – Maarten Bodewes Jul 03 '14 at 15:20
  • @OlegEstekhin that is a good question, in all fairness I have no idea. as far as the getKey function goes I dont know wht that would make it more unreliable but I added it to the original post, overlooked it initially – BlueEgg Jul 04 '14 at 08:11
  • hi @BlueEgg .. I am facing same issue. Did you find any solution for it? – Beena Oct 17 '16 at 11:28

1 Answers1

0

Try this Code

in 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;
    }

in 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);
    }
miladsolgi
  • 430
  • 5
  • 19
kubs
  • 117
  • 9