2013-02-27 30 views
1

我有一個應用程序,我需要將用戶名轉換爲加密格式,然後在php.My中加密解密。但在PHP端解密的字符串總是包含兩到三個額外的字符在不可讀的格式。我只是不知道它從哪裏採取這些額外的字符?這與填充有關嗎? 我發佈android代碼和php代碼。Php以不可讀的格式返回解密的字符串

的Android端代碼

public String encryptStringWithAES(String Message) throws Exception { 

    String key = "123456789abcdefg"; 

    String iv = "123456789"; 

    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='123456789'; 



$message=$_POST['msg']; 

$decoded_string=base64_decode($message); 

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

回答

0

我想你可能有字符編碼問題。 Android代碼使用UTF-8進行字符串編碼。因爲這確保從android到php的整個數據流都使用這種編碼。

我對你的具體建議是檢查php腳本文件的編碼。您還必須確定UTF-8編碼是否帶有BOM或沒有它。

編輯:

當我說 「編碼」 我想 「character encoding」。在Android的負責字符編碼代碼大概是這樣的:

key.getBytes("UTF8") 

我不知道你正在使用的編輯器,但你應該檢查什麼字符編碼設置爲您正在使用的PHP腳本文件。確保它是UTF-8。並用BOM測試並且不用它,因爲我不確定什麼是ororid正在使用的。

+0

thax for you replay。我第一次嘗試編碼和解碼的東西。即在android中使用base64編碼字符串,並在php中解碼。它運作良好,但是當我嘗試使用常量Base64.SAFE_URL或任何其他常量時,我​​會以不可讀的格式獲取更少或更多的字符。 – user1393609 2013-02-27 10:20:12

+0

這是我的輸出: – user1393609 2013-02-27 10:28:21

+0

原始字符串=測試是強制性加密字符串= m + 0nVREKQweWMeWhR0RnevVJmSDi解密字符串=測試是強制性的 – user1393609 2013-02-27 10:30:13

0

我最近使用C#和PHP有類似的編程經驗。

它可能是解密對象包含空字符。你可以嘗試剝離它們。我還從字符串的末尾去掉回車符:

$decrypted_string = str_replace("\0", "", $Decrypted); 
$decrypted_string = str_replace("\r", "", $Decrypted); 
$decrypted_string = str_replace("\n", "", $Decrypted); 
+0

好的。 thax回覆。我會試試這個。 – user1393609 2013-02-27 10:31:21

+0

仍然無法使用!現在做什麼? – user1393609 2013-02-27 10:37:20