Android Aes加密垫块已损坏

Ste*_*ios 3 encryption android aes

我正在使用下面的方法,如果我输入了正确的键,一切都会正常。但是,如果我输入了错误的密钥,我将收到BadPaddingException:pad块损坏……我做错了吗?

public  void initKey(String passwd, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException{

    byte[] localsalt = salt; 
   PBEKeySpec password = new PBEKeySpec(passwd.toCharArray(),localsalt, 1024,128);//, localsalt, 1000, 128);  //128bit enc aes
   SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5And128BitAES-CBC-OpenSSL","BC");  
   PBEKey key = (PBEKey) factory.generateSecret(password);  
   encKey = new SecretKeySpec(key.getEncoded(), "AES");
}


public   String txt2enc(String etxt) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

       final Cipher cipher = Cipher.getInstance("AES");//AES       
       cipher.init(Cipher.ENCRYPT_MODE, encKey);      

       byte[] encrypted = cipher.doFinal((etxt).getBytes("UTF-8"));
       return Base64.encodeToString(encrypted, 0);
}

//decryption
public  String txt2dec(String dtxt) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{

    final Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, encKey);
    byte[] decrypt = cipher.doFinal(Base64.decode(dtxt, 0));
    return new String(decrypt);//return Base64.encodeToString(decrypt, 0);
}
Run Code Online (Sandbox Code Playgroud)

Whi*_*g34 5

你没做错什么 可以预料的 从技术上讲,这是Java加密问题的复本(似乎不容易找到)。请参阅此答案以获得良好的解释。您可以考虑添加MAC(消息身份验证代码)以安全地完成类似于校验和的操作。