首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

Java AES加密有关问题

2012-01-22 
Java AES加密问题使用KeyGenerator做AES加密解密,有两个问题:1、kgen.init(128, new SecureRandom(okey))

Java AES加密问题
使用KeyGenerator做AES加密解密,有两个问题:
1、kgen.init(128, new SecureRandom(okey)); 这句代码是使用128位密钥加密,也就是okey必须是128位字节,但我的okey长度不是128位(大于、小于都可以),为什么也能通过,得出密文,用该密文解密也没问题?

2、我看说AES支持128位、192位、256位加密,但使用kgen.init(192,xxx), kgen.init(256, xxx)就报Illegal key size or default parameters异常。为什么?

API说明不太明白。谢谢各位赐教。。。。


下面是加密的源代码

Java code
    /**     * 数据加密     *      * @param name     *               算法名称     * @param password     *               密钥     * @param message     *               明文     * @return 返回密文     */    public static byte[] Encode(String name, String password, byte[] message) {        if (name == null || name.length() <= 0                || password == null || password.length() <= 0                || message == null || message.length <= 0)            return null;                if (!name.equals(ALGO_AES))            return null;                byte[] content = null;                KeyGenerator kgen = null;                try {            kgen = KeyGenerator.getInstance(name);            byte[] okey = password.getBytes();            kgen.init(128, new SecureRandom(okey));            SecretKey secretKey = kgen.generateKey();                        Cipher cipher = Cipher.getInstance(name);    // 创建密码器             cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 初始化            content = cipher.doFinal(message);        } 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();        }        return content;    }


[解决办法]
1、kgen.init(128, new SecureRandom(okey)); 这句代码是使用128位密钥加密,也就是okey必须是128位字节,但我的okey长度不是128位(大于、小于都可以),为什么也能通过,得出密文,用该密文解密也没问题?

128位指的是kgen生成的密钥长度,不是你的okey的长度

2、我看说AES支持128位、192位、256位加密,但使用kgen.init(192,xxx), kgen.init(256, xxx)就报Illegal key size or default parameters异常。为什么?

AES算法支持多种密钥长度,但是不同的生产商实现的AES是不同的

热点排行