• AES加密


    Base64工具类

    package test.test;
    
    import org.apache.commons.codec.binary.Base64;
    
    /**
     * Base64工具类
     * @author zhouky
     * 2016年9月29日下午2:36:00
     */
    public class Base64Util {
    
    	/**
    	 * 加密
    	 * @param bytes
    	 * @return
    	 */
    	public static String encrypt(byte[] bytes) {
    		byte[] arr = Base64.encodeBase64(bytes, true);
    		if(null == arr)
    			try {
    				throw new Exception();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		return new String(arr);
    	}
    
    
    	/**
    	 * 解密
    	 * @param encryptString
    	 * @return
    	 */
    	public static byte[] decrypt(String encryptString) {
    		byte[] arr = Base64.decodeBase64(encryptString.getBytes());
    		if(null == arr)
    			try {
    				throw new Exception();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		return arr;
    	}
    }
    

    AES加解密

    package test.test;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    
    import org.apache.log4j.Logger;
    
    /**
     * AES加密工具类
     * @author zhouky
     * 2016年9月29日下午2:29:35
     */
    @SuppressWarnings("static-access")
    public class AES {
    
    	protected static Logger logger = Logger.getLogger(AES.class);
    	
    	/**
    	 * 密钥算法 java6支持56位密钥,bouncycastle支持64位
    	 * */
    	public static final String KEY_ALGORITHM = "AES";
    
    	/**
    	 * 加密/解密算法/工作模式/填充方式
    	 * JAVA6 支持PKCS5PADDING填充方式 Bouncy castle支持PKCS7Padding填充方式
    	 * */
    	public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    
    	public static final String SECRET_KEY = "1234567890123456";
    	
    	private static AES instance = null;
    
        private AES() {
    
        }
    	
    	public static AES getInstance() {
            if (instance == null)
                instance = new AES();
            return instance;
        }
    	
    	/**
         * 加密
         * @param content 需要加密的内容
         * @param password  加密密码
         * @return
    	 * @throws Exception 
         */
    	public static byte[] encrypt(String content,String secretKey){
    		try {
    			SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), KEY_ALGORITHM);
    			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 创建密码器
    			byte[] byteContent = content.getBytes("utf-8");
    			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
    			byte[] result = cipher.doFinal(byteContent);
    			return result; // 加密
    		} catch (Exception e) {
    			logger.error("[AES加密 error]="+e.getMessage());
    			return null;
    		}
    	}
    	
    	/**
    	 * AES加密后用Base64进行二次加密
    	 * @param str
    	 * @return
    	 * @throws Exception 
    	 */
    	public static String encrypt16(String str,String key){
    		byte[] data; // 加密数据
    		try {
    			data = encrypt(str,key);
    			return parseByte2HexStr(data);
    		} catch (Exception e) {
    			logger.debug("[AES密文转16进制 error] ="+e.getMessage());
    			return null;
    		}
    	}
    	
    	/**
    	 * AES加密后用Base64进行二次加密
    	 * @param str
    	 * @return
    	 * @throws Exception 
    	 */
    	public static String encryptBase64(String str,String key){
    		byte[] data; // 加密数据
    		try {
    			data = encrypt(str,key);
    			return Base64Util.encrypt(data).trim();
    		} catch (Exception e) {
    			logger.debug("[Base64加密 AES密文 error] ="+e.getMessage());
    			return null;
    		}
    	}
        
        /**解密
         * @param content  待解密内容
         * @return
         * @throws Exception 
         */
    	public static byte[] decrypt(byte[] content,String secretKey){
    		try {
    			SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), KEY_ALGORITHM);
    			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 创建密码器
    			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
    			byte[] result = cipher.doFinal(content);
    			return result; 
    		} catch (Exception e) {
    			logger.error("[AES解密 error ]=" +e.getMessage());
    			return null;
    		}
    	}
    	
    	/**
    	 *  解密数据
    	 * @param value:base加密后的数据
    	 * @return
    	 * @throws Exception 
    	 */
    	public static String decrypt16(String value,String secretKey){
    		byte[] hex2Data; 
    		byte[] aes128Data; 
    		try {
    			hex2Data = parseHexStr2Byte(value);
    			aes128Data = decrypt(hex2Data,secretKey);
    			return new String(aes128Data);
    		} catch (Exception e) {
    			logger.error("[十六进制转换 AES密文 error] ="+e.getMessage());
    			return null;
    		}
    	}
    	
    	/**
    	 *  解密数据
    	 * @param value:base加密后的数据
    	 * @return
    	 * @throws Exception 
    	 */
    	public static String decryptBase64(String value,String secretKey){
    		byte[] base64Data; // base64解密数据
    		byte[] aes256Data; // base64解密数据
    		try {
    			base64Data = Base64Util.decrypt(value);//base64解密 base64数据
    			aes256Data = decrypt(base64Data,secretKey);
    			return new String(aes256Data);
    		} catch (Exception e) {
    			logger.error("[Base64解密 AES密文 error] ="+e.getMessage());
    			return null;
    		}
    	}
    	
    	private static String parseByte2HexStr(byte buf[]) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                String hex = Integer.toHexString(buf[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        }
    
        private static byte[] parseHexStr2Byte(String hexStr) {
            if (hexStr.length() < 1)
                return null;
            byte[] result = new byte[hexStr.length()/2];
            for (int i = 0;i< hexStr.length()/2; i++) {
                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
                result[i] = (byte) (high * 16 + low);
            }
            return result;
        }
    	
    	public static void main(String[] args) {
    		System.out.println(AES.getInstance().encrypt("15152200001", SECRET_KEY));
    		System.out.println(AES.getInstance().decrypt(AES.getInstance().encrypt("15152200001", SECRET_KEY), SECRET_KEY));
    		System.out.println(AES.getInstance().encrypt16("15152200001", SECRET_KEY));
    		System.out.println(AES.getInstance().decrypt16(AES.getInstance().encrypt16("15152200001", SECRET_KEY), SECRET_KEY));
    		System.out.println(AES.getInstance().encryptBase64("15152200001", SECRET_KEY));
    		System.out.println(AES.getInstance().decryptBase64(AES.getInstance().encryptBase64("15152200001", SECRET_KEY), SECRET_KEY));
    	}
    }
    

    Jar包依赖

      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j_version}</version>
      </dependency>
      <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>${commons-codec_version}</version>
      </dependency>
    

      

  • 相关阅读:
    【动态规划】01背包问题
    【Spring源码解读】bean标签中的属性(一)你可能还不够了解的 scope 属性
    【LeetCode】无重复字符串最长子串
    【LeetCode】两数之和
    LeetCode单排日记
    你不可不知的Java引用类型【总结篇】
    你不可不知的Java引用类型之——PhantomReference源码详解
    你不可不知的Java引用类型之——WeakReference源码详解
    你不可不知的Java引用类型之——SoftReference源码详解
    你不可不知的Java引用类型之——ReferenceQueue源码详解
  • 原文地址:https://www.cnblogs.com/therunningfish/p/6307607.html
Copyright © 2020-2023  润新知