我知道这个问题经常被问到但是我已经检查了我在Stack Overflow中找到的所有内容并且没有找到问题的解决方案。
我使用DESede进行加密和解密,并使用外部24字节键输入。但得到例外。
这是我的代码:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.DESedeKeySpec;
import javax.xml.bind.DatatypeConverter;
public class DESede {
private static Cipher encryptCipher;
private static Cipher decryptCipher;
public static void main(String[] args) throws InvalidKeySpecException {
try {
String desKey = "0123456789abcdef0123456789abcdef0123456789abcdef"; // value from user
byte[] keyBytes = DatatypeConverter.parseHexBinary(desKey);
System.out.println((int)keyBytes.length);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(keyBytes));
encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key); //throwing Exception
byte[] encryptedData = encryptData("Confidential data");
decryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
decryptData(encryptedData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
//加密方法
private static byte[] encryptData(String data)
throws IllegalBlockSizeException, BadPaddingException {
System.out.println("Data Before Encryption :" + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = encryptCipher.doFinal(dataToEncrypt);
System.out.println("Encryted Data: " + encryptedData);
return encryptedData;
}
//解密方法
private static void decryptData(byte[] data)
throws IllegalBlockSizeException, BadPaddingException {
byte[] textDecrypted = decryptCipher.doFinal(data);
System.out.println("Decryted Data: " + new String(textDecrypted));
}
}
我在该行获得异常:java.security.InvalidKeyException:密钥长度无效:24字节
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
任何人都知道为什么会这样?
答案 0 :(得分:1)
您在代码中犯了两个错误
您使用DESede
在此行中创建密钥工厂
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
但您使用DES
获取Cipher
对象。你必须使用DESede
代替
所以请使用此行
encryptCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
而不是这一行
encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
使用相同的算法来获取decripting cipher
另一个是使用AlgorithmParameterSpec
来初始化解密密码。
byte iv[] = encryptCipher.getIV();
IvParameterSpec dps = new IvParameterSpec(iv);
decryptCipher.init(Cipher.DECRYPT_MODE, key, dps);
您可以使用上面的代码将AlgorithmParameterSpec
应用于密码的初始化