如果在Android中解密过程中抛出了java.security.InvalidAlgorithmParameterException: Must specify IV for CBC mode.
异常,这意味着在使用CBC模式进行解密时没有指定初始化向量(IV)。下面是一个解决方案的示例代码:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DecryptUtil {
public static String decrypt(String encryptedText, String key, String iv) throws Exception {
byte[] encryptedData = android.util.Base64.decode(encryptedText, android.util.Base64.DEFAULT);
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = iv.getBytes("UTF-8");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedData);
return new String(decryptedBytes, "UTF-8");
}
}
使用示例:
try {
String encryptedText = "your_encrypted_text";
String key = "your_key";
String iv = "your_iv";
String decryptedText = DecryptUtil.decrypt(encryptedText, key, iv);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
确保在调用Cipher.init()
方法时,传递正确的密钥和初始化向量(IV)。