2016-11-16 80 views
0

我只想問一下。Eclipse:Android上的AES加密和解密密鑰

我在eclipse上有android的AES加密短信應用程序,但我有一個問題。

問題是,當我把關鍵字少於16個字符,消息不能被加密。但如果密鑰是16個字符,則可以加密該消息。

我想插入密鑰,無論金額多少。密鑰可以生成爲16個字符,以獲得128位。那麼,代碼應該如何解決這個問題呢?

在此先感謝 - 我希望你能幫助我。

public class AES { 
    public static String encrypt(String message, String key){ 
     try { 
      SecretKeySpec KS = new SecretKeySpec(key.getBytes(), "AES"); 
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
      cipher.init(Cipher.ENCRYPT_MODE, KS); 
      byte[] encrypted = cipher.doFinal(message.getBytes());  
      return Base64.encodeToString(encrypted, Base64.NO_PADDING); 
     } catch (Exception e) { 
      return "ERROR:"+e.getMessage(); 
     } 
    } 

    public static String decrypt(String chiperText, String key){ 
     try { 

      SecretKeySpec KS = new SecretKeySpec(key.getBytes(), "AES"); 
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
      cipher.init(Cipher.DECRYPT_MODE, KS); 
      byte[] decrypted = cipher.doFinal(Base64.decode(chiperText, Base64.NO_PADDING)); 
      return new String(decrypted); 
     } catch (Exception e) { 
      return "ERROR"; 
     } 
    } 

回答

1

您的代碼不安全,因爲您通過password.getBytes()直接使用密碼作爲密鑰。

永遠不要做這個!

使用像PBKDF2一樣的基於密碼生成密鑰的適當密鑰導出函數。相同的密碼和相同的PBKDF2參數將以相同的密鑰結束。

欲瞭解更多詳情,請閱讀例如本博文:Using Password-based Encryption on Android

+0

我解決了我的關鍵代碼問題。 我嘗試在沒有Google API的情況下在AVD上運行應用程序,所有功能都運行良好。 但是,如果我使用Google API在AVD上運行應用程序或在Android手機上安裝。加密文本無法正確解密。 如何解決這個問題? –

+0

GoogleAPI對AES加密/解密沒有影響。可能是使用的Android版本對您沒有發佈的代碼派對有影響。下一次你應該發佈一個完整的工作示例,包括樣本加密/解密數據和密鑰。 – Robert

+0

謝謝你的答案。 僅在兼容性方面存在問題。 :d –