2013-08-16 68 views
1

我使用這種算法在android中加密和解密數據。但是,當使用utf-8字符時,顯示此錯誤:[加密]數據不是塊大小對齊。如何在JAVA或Android中加密和解密UTF-8?

我用這個算法的加密和解密:https://snipt.net/raw/ee573b6957b7416f28aa560ead71c3a2/?nice

我的代碼:

HttpClient client = new DefaultHttpClient(); 

     HttpPost post = new HttpPost(ServerIP.frooshgah_URL); 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     JSONObject json = new JSONObject(); 



     try { 
      json.put("UserId", "0s"); 
      json.put("N_frooshgah", N_frooshgah); 
      json.put("N_masol", N_masol); 
      json.put("N_makan", N_makan); 
      json.put("address", address); 
      json.put("tel", tel); 
      json.put("time_baz", time_baz); 
      json.put("time_baste", time_baste); 
      json.put("tavzihat", tavzihat); 
      json.put("tag", tag); 
      json.put("categori", "پوشاک"); 
      json.put("city", city); 
      json.put("lat", lat); 
      json.put("long", Long); 

     } catch (JSONException e3) { 
      // TODO Auto-generated catch block 
      e3.printStackTrace(); 
     } 

     MCrypt mcrypt = new MCrypt(); 
     String encrypted = ""; 
     try { 

      encrypted = MCrypt.bytesToHex(mcrypt.encrypt(json.toString())); 
      //encrypted = encryption.hexToString(json.toString(), 2); 
       //key = UUID.randomUUID().toString().replaceAll("-", ""); 
      //encrypted=Crypto.encrypt(json.toString(),key); 


     } catch (Exception e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

如何解決這個問題?

感謝

+0

http://stackoverflow.com/questions/17079579/aes-algo-decryption-issue/17080884#17080884。檢查它是否有幫助 – Raghunandan

+2

編寫Mcrypt代碼的人犯了一些初學者的錯誤,例如假設每個字符在轉換爲二進制表示時都是一個字節,並使用一些平臺默認文本編碼(這在發送加密的平臺上可能不同數據)。 – Codo

+0

我想要發送數據到php yii框架和Encrpted –

回答

1

首先,我看到你的使用MCrypt類提供源代碼。下載源代碼,並將其添加到您的項目並修改padString(string)方法是:

private static String padString(String source){ 
    char paddingChar = ' '; 
    int size = 16; 
    int x = source.getBytes(Charset.forName("UTF-8")).length % size; 
    int padLength = size - x; 

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

    return source; 
} 

這將允許該代碼同時使用UTF-8作爲charset執行。如果要「改善」庫以支持多重字符集,請考慮在該類的encrypt/decrypt方法中添加charset參數。

+0

謝謝..工作完美 –

+0

如果您認爲它有幫助,請不要忘記接受答案。 – initramfs

+0

請原諒...... Decrypt中的錯誤:java.lang.Exception:[decrypt]無法解析' <'as integer –