为什么AES Java解密会返回额外的字符?

5

抱歉我的英语不好。 我使用的是从这里获取的mcryptMCrypt for php and java。在我的安卓应用程序中,我需要让php和java之间进行安全通信,因此我使用了上述提到的AES。 问题在于当php发送加密数据时,java可以解密它,但是一些额外的字符包含其中。

JAVA代码

    import java.security.NoSuchAlgorithmException;

    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;

    public class MCrypt {

            private String iv = "fedcba9876543210";//Dummy iv (CHANGE IT!)
            private IvParameterSpec ivspec;
            private SecretKeySpec keyspec;
            private Cipher cipher;

            private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!)

            public MCrypt()
            {
                    ivspec = new IvParameterSpec(iv.getBytes());

                    keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

                    try {
                            cipher = Cipher.getInstance("AES/CBC/NoPadding");
                    } catch (NoSuchAlgorithmException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (NoSuchPaddingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
            }

            public byte[] encrypt(String text) throws Exception
            {
                    if(text == null || text.length() == 0)
                            throw new Exception("Empty string");

                    byte[] encrypted = null;

                    try {
                            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

                            encrypted = cipher.doFinal(padString(text).getBytes());
                    } catch (Exception e)
                    {                       
                            throw new Exception("[encrypt] " + e.getMessage());
                    }

                    return encrypted;
            }

            public byte[] decrypt(String code) throws Exception
            {
                    if(code == null || code.length() == 0)
                            throw new Exception("Empty string");

                    byte[] decrypted = null;

                    try {
                            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

                            decrypted = cipher.doFinal(hexToBytes(code));
                    } catch (Exception e)
                    {
                            throw new Exception("[decrypt] " + e.getMessage());
                    }
                    return decrypted;
            }



            public static String bytesToHex(byte[] data)
            {
                    if (data==null)
                    {
                            return null;
                    }

                    int len = data.length;
                    String str = "";
                    for (int i=0; i<len; i++) {
                            if ((data[i]&0xFF)<16)
                                    str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
                            else
                                    str = str + java.lang.Integer.toHexString(data[i]&0xFF);
                    }
                    return str;
            }


            public static byte[] hexToBytes(String str) {
                    if (str==null) {
                            return null;
                    } else if (str.length() < 2) {
                            return null;
                    } else {
                            int len = str.length() / 2;
                            byte[] buffer = new byte[len];
                            for (int i=0; i<len; i++) {
                                    buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                            }
                            return buffer;
                    }
            }



            private static String padString(String source)
            {
              char paddingChar = ' ';
              int size = 16;
              int x = source.length() % size;
              int padLength = size - x;

              for (int i = 0; i < padLength; i++)
              {
                      source += paddingChar;
              }

              return source;
            }
    }

PHP代码

 <?php 

    class MCrypt
    {
            private $iv = 'fedcba9876543210'; #Same as in JAVA
            private $key = '0123456789abcdef'; #Same as in JAVA


            function __construct()
            {
            }

            function encrypt($str) {

              //$key = $this->hex2bin($key);    
              $iv = $this->iv;

              $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);

              mcrypt_generic_init($td, $this->key, $iv);
              $encrypted = mcrypt_generic($td, $str);

              mcrypt_generic_deinit($td);
              mcrypt_module_close($td);

              return bin2hex($encrypted);
            }

            function decrypt($code) {
              //$key = $this->hex2bin($key);
              $code = $this->hex2bin($code);
              $iv = $this->iv;

              $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);

              mcrypt_generic_init($td, $this->key, $iv);
              $decrypted = mdecrypt_generic($td, $code);

              mcrypt_generic_deinit($td);
              mcrypt_module_close($td);

              return utf8_encode(trim($decrypted));
            }

            protected function hex2bin($hexdata) {
              $bindata = '';

              for ($i = 0; $i < strlen($hexdata); $i += 2) {
                    $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
              }

              return $bindata;
            }

    }

情景是Java以JSON格式发送简单文本数据到PHP,PHP提取数据,对其进行加密,最后以JSON格式输出。

PHP调用:

<?php

$data =json_decode(file_get_contents('php://input'), true);

$data=$data["request"];
require_once "encryption.php";
$etool=new MCrypt();
$data=$etool->encrypt($data);
$array=array('data'=>$data);
echo json_encode($array);

JAVA 代码:

 //sb is StringBuilder
JSONObject j=new JSONObject(sb.toString());
encryption etool=new encryption();
result=j.get("data").toString();
result= new String(etool.decrypt( result ));
Log.d("success remote ",result );

结果如下:

示例������

如果我使用波斯语/阿拉伯语单词,情况会更糟

像这样-> درود����������������

此外,我查看了其他问题,但未能获得答案。

AES加密,在解密文件中获得额外的垃圾字符
PHP MCRYPT加密/解密返回不可见的奇怪字符?

提前感谢您!

2个回答

3

AES 每次加密的块大小为16个字节。如果你的输入不是16的倍数,就需要使用填充方案。由于您没有指定 Mcrypt 的任何填充选项,因此它使用了 "零填充"

在您的 Java 代码中,当您实例化 Cipher 时,指定 "NoPadding"

 cipher = Cipher.getInstance("AES/CBC/NoPadding");

因此,Java 认为由 php 进行的填充是加密数据的一部分。

您只需要确保您的 phpJava 代码使用相同的填充方案即可。


问题正是你所说的。我不知道填充的功能。在Java代码中,我将“无填充”更改为“PKCS5PADDING”。然后在PHP中,我从链接获取了pkcs5padding函数,该函数可在所提到页面的第4个部分下找到。谢谢。 - Ehsan Jeihani
对于那些使用此代码的人,请注意下一个简单问题[何时需要填充加密?] (http://stackoverflow.com/questions/35241522/when-padding-is-required-for-encryption)。 - Ehsan Jeihani

1
我认为这是二进制数据,无法显示。 在将其发送到PHP脚本之前,您尝试过使用base64将其转换为常规字符串吗?
然后在PHP脚本中,您可以执行以下操作来解码base64字符串。
$data=base64_decode($data["request"])

谢谢你写这个,但我只是将它转换为JSON。 - Ehsan Jeihani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接