异常如下:
Exception in thread "main" java.security.InvalidKeyException: Invalid key length: 7 bytes
at com.sun.crypto.provider.DESCipher.engineGetKeySize(DESCipher.java:373)
at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1067)
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1025)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at com.yrp.CipherDemo.desEncript(CipherDemo.java:33)
at com.yrp.CipherDemo.main(CipherDemo.java:24)
或者:
原因:
DES的密钥必须是64位,即8个字节,少或者多都不行,AES的密钥必须是128位,即16字节才可以,我的原始密钥如下:
public class CipherDemo {
public static void main(String[] args) throws Exception {
String clearText="yeruiping";
//密钥必须是64位,即八个字节,我这边是只有4个字节,所以就出现异常了
String secretTest="1234";
String encript = desEncript(clearText, secretTest);
System.out.println(encript);
}
private static String desEncript(String clearText, String secretTest) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
//获取加密工具类
Cipher cipher=Cipher.getInstance("DES");
//对工具类进行初始化
SecretKeySpec key=new SecretKeySpec(secretTest.getBytes(),"DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
//用工具类对象对明文进行加密
byte[] bytes = cipher.doFinal(clearText.getBytes());
return new String(bytes);
}
}
解决办法:将密钥改成8个字节
public class CipherDemo {
public static void main(String[] args) throws Exception {
String clearText="yeruiping";
//密钥必须是64位,即八个字节
String secretTest="12345678";
String encript = desEncript(clearText, secretTest);
System.out.println(encript);
}
private static String desEncript(String clearText, String secretTest) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
//获取加密工具类
Cipher cipher=Cipher.getInstance("DES");
//对工具类进行初始化
SecretKeySpec key=new SecretKeySpec(secretTest.getBytes(),"DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
//用工具类对象对明文进行加密
byte[] bytes = cipher.doFinal(clearText.getBytes());
return new String(bytes);
}
}