2013-03-29 28 views
2

在iOS上使用的代碼罰款,並試圖將代碼轉換爲Android我們有以下但似乎有填充問題,任何人都可以提供一個手。Android和PHP加密/解密 - 填充問題

使用MD5關鍵

的Java(Android版)

public class AES256Cipher { 

    public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 


    public static String AES_Encode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { 

     byte[] textBytes = str.getBytes("UTF-8"); 
     AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); 
      SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); 
      Cipher cipher = null; 
     cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec); 

     return Base64.encodeToString(cipher.doFinal(textBytes), 0); 
    } 

    public static String AES_Decode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { 

     byte[] textBytes =Base64.decode(str,0); 
     //byte[] textBytes = str.getBytes("UTF-8"); 
     AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); 
     SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); 
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec); 
     return new String(cipher.doFinal(textBytes), "UTF-8"); 
    } 
} 

PHP

<?php 
function encrypt ($key, $value) 
{     
    $padSize = 16 - (strlen ($value) % 16) ; 
    $value = $value . str_repeat (chr ($padSize), $padSize) ; 
    $output = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;     
    return base64_encode ($output) ;   
} 

function decrypt ($key, $value)   
{      
    $value = base64_decode ($value) ;     
    $output = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;     

    $valueLen = strlen ($output) ; 
    if ($valueLen % 16 > 0) 
     $output = ""; 

    $padSize = ord ($output{$valueLen - 1}) ; 
    if (($padSize < 1) or ($padSize > 16)) 
     $output = "";    // Check padding.     

    for ($i = 0; $i < $padSize; $i++) 
    { 
     if (ord ($output{$valueLen - $i - 1}) != $padSize) 
      $output = ""; 
    } 
    $output = substr ($output, 0, $valueLen - $padSize) ; 

    return $output;   
} 

?> 

在Java方面的輸出。然而當代碼發送到工作正常PHP你得到一個剩餘的輸出,這讓我們認爲它是一個填充問題,任何幫助都會很棒。

+1

我不明白爲什麼$輸出被重置('$輸出=「」;')在多種情況下?!? –

+0

這是填充失敗的地方 – okett

回答