AES加密解密

/**
     * @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)));
    }


你可能感兴趣的:(JAVA)