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

异常如下:

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值