1

我有一个应用程序,我需要将用户名转换为加密格式,然后在 php 中解密。我的加密代码运行良好。但是在 php 端解密的字符串总是包含两到三个不可读格式的附加字符。我只是不明白它从哪里获取这些附加字符?它与填充有关吗?我正在发布 android 代码和 php 代码。

安卓端代码

public String encryptStringWithAES(String Message) throws Exception {

    String key = "123456789abcdefg";

    String iv = "1234567890123456";

    String padding = "ZeroBytePadding";


    SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF8"), "AES");

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



    IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());


    cipher.init(Cipher.ENCRYPT_MODE, spec, ivspec);

    byte[] array = cipher.doFinal(Message.getBytes());

    System.out.println("encrypted ARRAY LENGHT:" + array.length);

    String encoded_string = android.util.Base64.encodeToString(array, 0,
    array.length, Base64.NO_PADDING);

    System.out.println("Requested encoded string: " + encoded_string);
    return encoded_string;

}

PHP端代码:

$key_for_AES='123456789abcdefg';

$iv='1234567890123456';



$message=$_POST['msg'];

$decoded_string=base64_decode($message);

$decrypted_string=mcrypt_decrypt('rijndael-128',$key_for_AES, $decoded_string,'cbc',$iv);
4

2 回答 2

0

我想你可能有字符编码问题。Android 代码使用UTF-8进行字符串编码。因此,请确保从 android 到 php 的整个数据流都使用这种编码。

我对您的具体建议是检查 php 脚本文件的编码。您还必须确定 UTF-8 编码是否带有 BOM。

编辑:

当我说“编码”时,我想到的是“字符编码”。android中负责字符编码的代码大概是这样的:

key.getBytes("UTF8")

我不知道您使用的是哪个编辑器,但您应该检查为您使用的 php 脚本文件设置的字符编码。确保它是 UTF-8。并使用 BOM 和不使用 BOM 进行测试,因为我不确定 andorid 使用的是什么。

于 2013-02-27T09:33:24.037 回答
0

我最近在 C# 和 PHP 方面有过类似的编程经验。

可能是解密后的对象包含空字符。您可以尝试剥离它们。我还从字符串的末尾去掉了回车:

$decrypted_string = str_replace("\0", "", $Decrypted);
$decrypted_string = str_replace("\r", "", $Decrypted);
$decrypted_string = str_replace("\n", "", $Decrypted);
于 2013-02-27T09:36:29.363 回答