2013-03-28 41 views
1

我有3類:Android的AES加密錯誤墊座損壞

  1. AESCrypt
  2. ChooseMasterPasswordActivity
  3. UnlockPocketActivity

我成功地將數據添加到SQLite數據庫,但我有解密問題數據庫中的數據。

我得到這個錯誤:

W/System.err(1034): javax.crypto.BadPaddingException: pad block corrupted. 

在我使用此代碼加密的文本添加到SQLite數據庫ChooseMasterPasswordActivity類。

String masterKey, encryptedMPW; 
     masterKey = tvPassword.getText().toString(); 

     AESCrypt aes = new AESCrypt(); 
     encryptedMPW = aes.encrypt(masterKey); 

     user = new User(null, encryptedMPW); 
     userDao.insert(user); 

在類UnlockPocketActivity我有方法createMasterPassword()與此代碼:

private void checkMasterPassword() throws Exception { 

    String pw = tvUnlockMPW.getText().toString(); 
    String decryptedMPW; 

    AESCrypt aes = new AESCrypt(); 

    decryptedMPW = aes.decrypt(map.get("MPW").toString()); 



    if (pw.equals(decryptedMPW)) { 
     Intent i = new Intent(UnlockPocketActivity.this, 
       MainListActivity.class); 
     startActivity(i); 
    } else { 
     Toast.makeText(getApplicationContext(), "Pogresna sifra...", 
       Toast.LENGTH_SHORT).show(); 
    } 
} 

我用於CLAS AESCrypt此代碼:

公共類AESCrypt {

private final Cipher cipher; 
private final SecretKeySpec key; 
private AlgorithmParameterSpec spec; 
private String encryptedText, decryptedText; 
private String password = "PASSWORD"; 

public AESCrypt() throws Exception { 

    // hash password with SHA-256 and crop the output to 128-bit for key 
    MessageDigest digest = MessageDigest.getInstance("SHA-256"); 
    digest.update(password.getBytes("UTF-8")); 
    byte[] keyBytes = new byte[16]; 
    System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length); 

    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
    key = new SecretKeySpec(keyBytes, "AES"); 
    spec = getIV(); 
    } 

public AlgorithmParameterSpec getIV() { 
    AlgorithmParameterSpec ivspec; 
    byte[] iv = new byte[cipher.getBlockSize()]; 
    new SecureRandom().nextBytes(iv); 
    ivspec = new IvParameterSpec(iv); 
    return ivspec; 
    } 

public String encrypt(String plainText) throws Exception {  
    cipher.init(Cipher.ENCRYPT_MODE, key, spec); 
    byte[] encrypted = cipher.doFinal(plainText.getBytes()); 
    encryptedText = Base64.encodeToString(encrypted, Base64.DEFAULT); 
    return encryptedText; 
} 

public String decrypt(String cryptedText) throws Exception { 
    cipher.init(Cipher.DECRYPT_MODE, key, spec); 
    byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT); 
    byte[] decrypted = cipher.doFinal(bytes); 
    decryptedText = new String(decrypted, "UTF-8"); 
    return decryptedText; 
} 

}

回答

2

您似乎使用SecureRandom()來初始化您的初始化向量,它會在每次調用時產生不同的數據。

byte[] iv = new byte[cipher.getBlockSize()]; 
new SecureRandom().nextBytes(iv); 
ivspec = new IvParameterSpec(iv); 

加密和解密時初始化向量需要相同。將初始化向量與加密的數據一起保存,或者找到生成它的方法,以便在加密和解密時獲得相同的結果。它不需要是保密的,但它應該與你加密的每一件新事物有所不同。

+0

謝謝,這解決了我的問題。 – Zookey