zoukankan      html  css  js  c++  java
  • 【Java】AesCbcCodec(AES_CBC加解密工具类)

    Java AES_CBC加解密工具类

    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.security.Security;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    import org.apache.commons.codec.DecoderException;
    import org.apache.commons.codec.binary.Base64;
    import org.apache.commons.codec.binary.Hex;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    
    public class AesCbcCodec {
    
        /**
         * <tt>Java</tt> 支持 <tt>PKCS5Padding</tt> 填充方式 <br>
         * <tt>BouncyCastle</tt> 支持 <tt>PKCS7Padding</tt> 填充方式
         */
        private static final String TRANSFORMATION = "AES/CBC/PKCS7Padding";
        
        private static final String ALGORITHM = "AES";
    
        static {
            Security.addProvider(new BouncyCastleProvider());
        }
    
        /**
         * 加密数据
         * 
         * @param data          待加密数据
         * @param key           密钥
         * @param iv            偏移向量
         * @return 加密后的数据
         * @throws GeneralSecurityException
         */
        public static byte[] encrypt(byte[] data, byte[] key, byte[] iv) throws GeneralSecurityException {
            // 实例化Cipher对象,它用于完成实际的加密操作
            Cipher cipher = Cipher.getInstance(TRANSFORMATION, BouncyCastleProvider.PROVIDER_NAME);
            // 使用CBC模式,需要一个向量iv,可增加加密算法的强度
            IvParameterSpec ips = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, ALGORITHM), ips);
            return cipher.doFinal(data);
        }
    
        /**
         * 加密数据 (charset="UTF-8")
         * 
         * @param data                待加密数据
         * @param base64Key           密钥 (base64)
         * @param base64Iv            偏移向量 (base64)
         * @param charset             字符集编码
         * @return 加密后的数据 (base64)
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String encrypt_base64(String data, String base64Key, String base64Iv) 
                throws GeneralSecurityException, IOException {
            return encrypt_base64(data, base64Key, base64Iv, "UTF-8");
        }
    
        /**
         * 加密数据 (charset="UTF-8")
         * 
         * @param data             待加密数据
         * @param hexKey           密钥 (hex)
         * @param hexIv            偏移向量 (hex)
         * @param charset          字符集编码
         * @return 加密后的数据 (hex)
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String encrypt_hex(String data, String hexKey, String hexIv) 
                throws GeneralSecurityException, IOException {
            return encrypt_hex(data, hexKey, hexIv, "UTF-8");
        }
    
        /**
         * 加密数据
         * 
         * @param data                待加密数据
         * @param base64Key           密钥 (base64)
         * @param base64Iv            偏移向量 (base64)
         * @param charset             字符集编码
         * @return 加密后的数据 (base64)
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String encrypt_base64(String data, String base64Key, String base64Iv, String charset) 
                throws GeneralSecurityException, IOException {
            byte[] target = encrypt(data.getBytes(charset), decodeBase64(base64Key), decodeBase64(base64Iv));
            return encodeBase64String(target);
        }
    
        /**
         * 加密数据
         * 
         * @param data             待加密数据
         * @param hexKey           密钥 (hex)
         * @param hexIv            偏移向量 (hex)
         * @param charset          字符集编码
         * @return 加密后的数据 (hex)
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String encrypt_hex(String data, String hexKey, String hexIv, String charset) 
                throws GeneralSecurityException, IOException {
            byte[] target = encrypt(data.getBytes(charset), decodeHex(hexKey), decodeHex(hexIv));
            return encodeHexString(target);
        }
    
        /**
         * 解密数据
         * 
         * @param data          待解密数据
         * @param key           密钥
         * @param iv            偏移向量
         * @return 解密后的数据
         * @throws Exception
         */
        public static byte[] decrypt(byte[] data, byte[] key, byte[] iv) throws GeneralSecurityException {
            // 实例化Cipher对象,它用于完成实际的加密操作
            Cipher cipher = Cipher.getInstance(TRANSFORMATION, BouncyCastleProvider.PROVIDER_NAME);
            // 使用CBC模式,需要一个向量iv,可增加加密算法的强度
            IvParameterSpec ips = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, ALGORITHM), ips);
            return cipher.doFinal(data);
        }
    
        /**
         * 解密数据 (charset="UTF-8")
         * 
         * @param base64Data          待解密数据 (base64)
         * @param base64Key           密钥 (base64)
         * @param base64Iv            偏移向量 (base64)
         * @return 解密后的数据
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String decrypt_base64(String base64Data, String base64Key, String base64Iv) 
                throws GeneralSecurityException, IOException {
            return decrypt_base64(base64Data, base64Key, base64Iv, "UTF-8");
        }
    
        /**
         * 解密数据 (charset="UTF-8")
         * 
         * @param hexData          待解密数据 (hex)
         * @param hexKey           密钥 (hex)
         * @param hexIv            偏移向量 (hex)
         * @return 解密后的数据
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String decrypt_hex(String hexData, String hexKey, String hexIv) 
                throws GeneralSecurityException, IOException {
            return decrypt_hex(hexData, hexKey, hexIv, "UTF-8");
        }
    
        /**
         * 解密数据
         * 
         * @param base64Data          待解密数据 (base64)
         * @param base64Key           密钥 (base64)
         * @param base64Iv            偏移向量 (base64)
         * @param charset             字符集编码
         * @return 解密后的数据
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String decrypt_base64(String base64Data, String base64Key, String base64Iv, String charset) 
                throws GeneralSecurityException, IOException {
            byte[] target = decrypt(decodeBase64(base64Data), decodeBase64(base64Key), decodeBase64(base64Iv));
            return new String(target, charset);
        }
    
        /**
         * 解密数据
         * 
         * @param hexData          待解密数据 (hex)
         * @param hexKey           密钥 (hex)
         * @param hexIv            偏移向量 (hex)
         * @param charset          字符集编码
         * @return 解密后的数据
         * @throws GeneralSecurityException
         * @throws IOException
         */
        public static String decrypt_hex(String hexData, String hexKey, String hexIv, String charset) 
                throws GeneralSecurityException, IOException {
            byte[] target = decrypt(decodeHex(hexData), decodeHex(hexKey), decodeHex(hexIv));
            return new String(target, charset);
        }
    
        // ============================================================================================
    
        /**
         * Converts a String representing hexadecimal values into an array of bytes of those same values. The
         * returned array will be half the length of the passed String, as it takes two characters to represent any given
         * byte. An exception is thrown if the passed String has an odd number of elements.
         *
         * @param data
         *            A String containing hexadecimal digits
         * @return A byte array containing binary data decoded from the supplied char array.
         * @throws IOException
         *             Thrown if an odd number or illegal of characters is supplied
         */
        public static byte[] decodeHex(String data) throws IOException {
            try {
                return Hex.decodeHex(data);
            } catch (DecoderException e) {
                throw new IOException(e.getMessage(), e.getCause());
            }
        }
        
        /**
         * Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned
         * String will be double the length of the passed array, as it takes two characters to represent any given byte.
         *
         * @param data
         *            a byte[] to convert to Hex characters
         * @return A String containing upper-case hexadecimal characters
         */
        public static String encodeHexString(byte[] data) {
            return Hex.encodeHexString(data, false);
        }
    
        /**
         * Decodes a Base64 String into octets.
         * <p>
         * <b>Note:</b> this method seamlessly handles data encoded in URL-safe or normal mode.
         * </p>
         *
         * @param base64String
         *            String containing Base64 data
         * @return Array containing decoded data.
         */
        public static byte[] decodeBase64(String data) {
            return Base64.decodeBase64(data);
        }
    
        /**
         * Encodes binary data using the base64 algorithm but does not chunk the output.
         *
         * NOTE:  We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to
         * single-line non-chunking (commons-codec-1.5).
         *
         * @param binaryData
         *            binary data to encode
         * @return String containing Base64 characters.
         */
        public static String encodeBase64String(byte[] data) {
            return Base64.encodeBase64String(data);
        }
    
    }
    
  • 相关阅读:
    Socket开发框架之消息的回调处理
    Socket开发框架之数据加密及完整性检查
    Socket开发框架之数据传输协议
    Socket开发框架之框架设计及分析
    C#进行Visio二次开发之文件导出及另存Web页面
    Winform混合式开发框架的特点总结
    代码生成工具Database2Sharp中增加视图的代码生成以及主从表界面生成功能
    基于Metronic的Bootstrap开发框架经验总结(9)--实现Web页面内容的打印预览和保存操作
    基于C#的MongoDB数据库开发应用(4)--Redis的安装及使用
    基于C#的MongoDB数据库开发应用(3)--MongoDB数据库的C#开发之异步接口
  • 原文地址:https://www.cnblogs.com/zhuzhongxing/p/14147103.html
Copyright © 2011-2022 走看看