AES/CBC/PKCS5Padding密码解密

/** AES/CBC/PKCS5Padding密码解密 **/
    private static byte[] ivValue = null;
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    static {
        try {
            ivValue = PUBLIC_SEC_IV.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static final IvParameterSpec IV_SPEC = new IvParameterSpec(ivValue);

    public static String decrypt(String encryptedData, String key ,String iv) {
        try {
            return decrypt(encryptedData,ALGORITHM,new SecretKeySpec(key.getBytes("UTF-8"), "AES"),new IvParameterSpec(iv.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
        return encryptedData;
    }

    public static String decrypt(String data,SecretKeySpec keySpec){
        return decrypt(data,ALGORITHM,keySpec,IV_SPEC);
    }

    /**
     * 根据算法模式,key,iv信息解密数据
     * @param encryptedData 待解密的内容
     * @param algorithm 算法
     * @param keySpec  key
     * @param ivSpec iv信息
     * @return
     */
    public static String decrypt(String encryptedData, String algorithm,SecretKeySpec keySpec,IvParameterSpec ivSpec) {
        if(encryptedData==null || encryptedData.length()==0){
            return "";
        }
        try {
            Cipher c = Cipher.getInstance(algorithm);
            if(ivSpec!=null){
                c.init(Cipher.DECRYPT_MODE, keySpec,ivSpec);
            }else{
                c.init(Cipher.DECRYPT_MODE, keySpec);
            }
            byte[] decordedValue = Base64.decodeBase64(encryptedData);
            byte[] decValue = c.doFinal(decordedValue);
            String decryptedValue = new String(decValue,"utf-8");
            return decryptedValue;
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage());
        } catch (InvalidKeyException e) {
            log.error(e.getMessage());
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage());
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(),e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
        return encryptedData;
    }

你可能感兴趣的:(java,加密解密)