0

在解密从 Android 应用程序发送的字符串时,我遇到了一个问题。只要写入非特殊字符(例如æ、ø、å),它就可以正常工作。如果我添加其中之一,它们将显示为“?”。

以下是字符串的加密方式(Java):

/*Constructor*/
public DataCrypt()
{
   ivspec = new IvParameterSpec(iv.getBytes());

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

   try
   {
      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
   }
   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(text.getBytes("UTF-8"));
    }
    catch (Exception e)
    {                       
      throw new Exception("[encrypt] " + e.getMessage());
    }      
    return encrypted;
}

以下是字符串的解密方式:

function decrypt($code)
{
  $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_decode(trim($decrypted));
}

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

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

function pkcs5_unpad($text)
{
    $pad = ord($text{strlen($text)-1});
    if ($pad > strlen($text))
        return false;

    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
        return false;

    return substr($text, 0, -1 * $pad);
}


$Username = pkcs5_unpad($crypto->decrypt($Username)); //$crypto is an instance of the cryptography class which holds the methods.
echo $Username.'<br/>'; /*Print ??? for special characters like æ, ø, å*/

希望有人对我如何解决这个问题有一个想法,所以也可以写 ø æ å 。

谢谢你的帮助!

4

1 回答 1

2

问题是utf8_decode()php 文档定义为Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1. 这意味着非 iso 字符被肢解。尝试简单地删除utf8_decode()

于 2012-09-08T11:16:05.570 回答