如何在JAVA或Android中加密和解密UTF-8?

我使用此算法在android中加密和解密数据。 但是当使用utf-8字符时..显示此错误:[加密]数据不对齐块大小。

我使用此算法进行加密和解密: https ://snipt.net/raw/ee573b6957b7416f28aa560ead71c3a2/ ? nice

我的代码:

HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(ServerIP.frooshgah_URL); List nameValuePairs = new ArrayList(); 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(); } 

如何解决这个问题?

谢谢

首先,我看到你使用的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 。 如果要“改进”库以支持多个字符集,请考虑将charset参数添加到类的encrypt / decrypt方法中。