AES加密解密

来源:互联网 发布:办公软件好不好学 编辑:程序博客网 时间:2024/05/07 09:32

/**     * @Description: 生成密钥     * @param password     * @return     * @throws Exception     */    public static SecretKeySpec initKey(String password) throws Exception    {        KeyGenerator kgen = KeyGenerator.getInstance("AES");         kgen.init(128, new SecureRandom(password.getBytes()));          SecretKey secretKey = kgen.generateKey();          byte[] enCodeFormat = secretKey.getEncoded();        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");        return key;    }        /**      * 加密      *       * @param content 需要加密的内容      * @param [password 加密密钥     * @return      * @throws Exception      */      public static String encryptNew(String content, String password) throws Exception     {          SecretKeySpec key = initKey(password);        byte[] byteContent = content.getBytes("UTF-8");        IvParameterSpec ivSpec = new IvParameterSpec("abcdefghijklmnop".getBytes());        // 创建密码器        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");        // 初始化        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);        return Base64.encodeBase64String(cipher.doFinal(byteContent));    }        /**解密      * @param content  待解密内容      * @param password 解密密钥      * @return      */      public static String decryptNew(String content, String password) throws Exception     {          SecretKeySpec key = initKey(password);        IvParameterSpec ivSpec = new IvParameterSpec("abcdefghijklmnop".getBytes());        // 创建密码器        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);// 初始化        return new String(cipher.doFinal(Base64.decodeBase64(content)));    }


0 0