1. 程式人生 > 其它 >Bug解決-----Exception in thread “main“ java.security.InvalidKeyException: Invalid key length: 7 bytes

Bug解決-----Exception in thread “main“ java.security.InvalidKeyException: Invalid key length: 7 bytes

技術標籤:bug解決

異常如下:

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);
    }
}