java - 获取 java.security.InvalidKeyException: Key must be 128, 192, or 256 bit long twofish
问题描述
以下代码用于加密纯文本,我在下面的示例代码中使用IAIK Twofish加密/解密代码在 java 中使用 128 位密钥可以正常工作,但是当我使用 192 和 156 位密钥尝试它时,它给出了一个例外 java.security.InvalidKeyException: Key must be 128, 192, or 256 bit long!
-
private static void doCrypto(int cipherMode, String key, File inputFile, File outputFile) throws CryptoException {
try {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION, "IAIK");
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
对于上述方法,当我提供 128 位密钥时,它可以正常工作,如下所示,
KeyGenerator keyGen = KeyGenerator.getInstance("Twofish", "IAIK");
keyGen.init(192);
txtSecretKey.setText(iaik.utils.Util.toString(key.getEncoded()));
SekertKey key = key.generateKey();
encrypt(txtSecretKey.getText(), inputFile, encryptedFile);
Caused by: java.security.InvalidKeyException: Key must be 128, 192, or 256 bit long!
at iaik.security.cipher.N.a(Unknown Source)
at iaik.security.cipher.i.a(Unknown Source)
at iaik.security.cipher.a.engineInit(Unknown Source)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1189)
at com.opensourse.crypto.twofish.CryptoUtils.doCrypto(CryptoUtils.java:38)
解决方案
推荐阅读
- python - 在 Python 中显示 ASCII 表
- python - DLL 加载失败:找不到特定模块(VSCode、Numpy)
- javascript - 在角度组件中使用 jquery/js 模块
- linux - Bazel 运行指定多行命令
- elasticsearch - ElasticSearch:如何更新现有索引中的文档类型
- javascript - 使用 Typeahead.js 进行下拉列表替换 MVC
- vb6 - vb6 从 txt 文件中提取此数据
- python-3.x - 如何使用 numpy 加速计算质心的代码?
- c# - OPC-UaFx 采样速度极慢
- c# - 将嵌套/复杂 JSON 转换为 CSV 未获得实际输出