2013-08-03 60 views
1
public static String Encrypt(String text){ 
    try {   
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     byte[] keyBytes= new byte[16]; 
     byte[] b= KEY.getBytes("UTF-8"); 
     int len= b.length; 
     if (len > keyBytes.length) len = keyBytes.length; 
     System.arraycopy(b, 0, keyBytes, 0, len); 
     SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); 
     IvParameterSpec ivSpec = new IvParameterSpec(keyBytes); 
     cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec); 

     byte[] results = cipher.doFinal(text.getBytes("UTF-8")); 
     String result = Base64.encodeToString(results, 0); 
     //result = URLEncoder.encode(result.trim(),"UTF-8"); 
     return result; 

    } catch (Exception e) { 
     // TODO: handle exception 
     return null; 
    } 
} 

public static String Decrypt(String text){ 
    try {   
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     byte[] keyBytes= new byte[16]; 
     byte[] b= KEY.getBytes("UTF-8"); 
     int len= b.length; 
     if (len > keyBytes.length) len = keyBytes.length; 
     System.arraycopy(b, 0, keyBytes, 0, len); 
     SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); 
     IvParameterSpec ivSpec = new IvParameterSpec(keyBytes); 
     cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec); 
     byte[] results = cipher.doFinal(text.getBytes("UTF-8")); 
     String result = Base64.encodeToString(results, 0); 
     //result = URLEncoder.encode(result.trim(),"UTF-8"); 
     return result; 

    } catch (Exception e) { 
     // TODO: handle exception 
     Log.d("decryption", e.getMessage()); 
     return null; 
    } 
} 

這是加密和解密的代碼,我從其他問題得到加密算法,它對我來說工作正常,但我也需要解密,我試圖模仿它像加密,但它的不工作。異常說最後一個塊不完整。解密算法在Android的AES

回答

6

問題是您沒有按相反順序執行反向序列。你已經結束了base64編碼數據 - 所以你需要做的第一件事是base64解碼,以獲得加密數據的二進制。然後解密,然後使用UTF-8將其轉換回字符串。

public static String decrypt(String text){ 
    try {   
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     byte[] keyBytes= new byte[16]; 
     byte[] b= KEY.getBytes("UTF-8"); 
     int len= b.length; 
     if (len > keyBytes.length) len = keyBytes.length; 
     System.arraycopy(b, 0, keyBytes, 0, len); 
     SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); 
     IvParameterSpec ivSpec = new IvParameterSpec(keyBytes); 
     cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec); 
     byte[] results = cipher.doFinal(Base64.decode(text, 0)); 
     return new String(results, "UTF-8"); 
    } catch (Exception e) { 
     // TODO: handle exception 
     Log.d("decryption", e.getMessage()); 
     return null; 
    } 
} 

當你從什麼地方拿代碼,它是你真正瞭解它正在做什麼是非常重要的 - 特別是,理解這些數據是什麼樣的,在每一個階段的位置:

  • 開始用純文本
  • UTF-8編碼爲一個字節數組
  • 加密到另一個字節陣列(其不是 UTF-8編碼的文本)
  • Base64編碼加密的二進制數據編碼爲一個字符串

任何時候你在做這樣的轉變,當你想扭轉這種局面,你需要扭轉的步驟的順序也一樣,爲了得到回原始數據。

+0

工作就像一個魅力。謝謝! – CodetrixStudio