我在 Android 项目中使用以下代码进行加密:
SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
String key = "abcdefg";
DESKeySpec keySpec = new DESKeySpec(key.getBytes());
SecretKey _key = kf.generateSecret(keySpec);
String xform = "DES";
Cipher cipher = Cipher.getInstance(xform);
byte[] IV = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 18, 69, 17, 72, 94, 18, 30 };
IvParameterSpec ips = new IvParameterSpec(IV);
cipher.init(Cipher.ENCRYPT_MODE, _key, ips);
String plainText = "abcdeffdkflsdkf";
byte[] cipherText = cipher.doFinal(plainText.getBytes());
我将此加密数据写入文件中,我想在我使用以下代码的 java 项目中解密此文件:
SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
String key = "abcdefg";
DESKeySpec keySpec = new DESKeySpec(key.getBytes());
SecretKey _key = kf.generateSecret(keySpec);
String xform = "DES";
Cipher cipher = Cipher.getInstance(xform);
byte[] IV = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 18, 69, 17, 72, 94, 18, 30 };
IvParameterSpec ips = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, _key, ips);
String cipherText;
//cipher text is read from file.
byte[] plainText = cipher.doFinal(cipherText.getBytes());
但它不起作用。当我们不指定操作模式(即CBC/ECB
)和填充方法(即PKCS5Padding/NoPadding
)并且只指定算法名称来获取 Cipher 实例时,那么 Android 和 Java 使用的默认值是什么?
Android是否默认使用CBC?因为它不会给出 IV 的错误。如果我在init
方法中指定 IV 并且未在我的 java 项目中指定模式,则会引发异常,因为 IV 不能用于 ECB。
谢谢。