zoukankan      html  css  js  c++  java
  • AES加密解密

    AES是一种对称加密,简单理解为秘钥只有一个,加密解密都用它,安全性不是很好

    package com.aisino.qysds.common.util;
    
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.util.Random;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;
    
    
    public class AESUtil {
    
        private static final String charset = "UTF-8";
        private final static int length=128;
        private final static String base = "abcdefghijklmnopqrstuvwxyz0123456789"; 
        private static final String KEY_AES = "AES";
        
        /**
         * aes ECB 模式加密
         * @param encryptStr
         * @param decryptKey
         * @return
         */
        public static String encryptECB(String encryptStr, String decryptKey){
            try{
                 return parseByte2HexStr(encrypt_ECB(encryptStr, decryptKey)); 
            }catch(Exception e) {
                    return null;
            }
        }
    
        /**
         * aes ECB 模式解密
         * @param encryptStr
         * @param decryptKey
         * @return
         * @throws Exception
         */
        public static String decryptECB(String encryptStr, String decryptKey)throws Exception{
            return decrypt_ECB(parseHexStr2Byte(encryptStr), decryptKey);  
        }
        /**
         * 加密 ECB
         * @param content
         * 需要加密的内容
         * @param password
         * 加密密码
         * @return
         */
        private static byte[] encrypt_ECB(String content, String encryptKey) throws Exception {
            try {
                Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
                SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), KEY_AES);
                aesECB.init(Cipher.ENCRYPT_MODE, key);
                byte[] result = aesECB.doFinal(content.getBytes(charset));
                return result;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }
        
        /**
         * 解密 ECB
         * @param content 待解密内容
         * @param password 解密密钥
         * @return
         */
        private static String decrypt_ECB(byte[] encryptBytes, String decryptKey) throws Exception {
            try {
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
                SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), KEY_AES);
                cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
                //byte[] result = parseHexStr2Byte(content);
                return new String(cipher.doFinal(encryptBytes)); // 解密
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
            return null;
            
        }
        
        
        
        /**
         * aes 默认加密
         * @param content
         * 需要加密的内容
         * @param password
         * 加密密码
         * @return
         */
        private static byte[] encrypt(String content, String password) throws Exception {
            KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 
            secureRandom.setSeed(password.getBytes());
            kgen.init(length, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat,KEY_AES);
            Cipher cipher = Cipher.getInstance(KEY_AES);// 创建密码器
            byte[] byteContent = content.getBytes(charset);
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        }
    
    
        /**
         * aes 默认解密
         * @param content 待解密内容
         * @param password 解密密钥
         * @return
         */
        private static byte[] decrypt(byte[] content, String password) throws Exception {
            KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 
            secureRandom.setSeed(password.getBytes());
            kgen.init(length, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat,KEY_AES);
            Cipher cipher = Cipher.getInstance(KEY_AES);// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        }
    
    
        /**
         * aes 默认加密
         * @param content
         * @param password
         * @return
         */
        public static String encryptAES(String content, String password){
            try{
                byte[] encryptResult = encrypt(content, password);
                return encode(encryptResult);
            }catch(Exception e) {
                    return null;
            }
        }
    
        /**
         * aes 默认解密
         * @param content
         * @param password
         * @return
         */
        
        public static String decryptAES(String content, String password){
            try{
                byte[] decryptResult = decrypt(decode(content.getBytes()), password);
                return new String(decryptResult,charset);
            }catch(Exception e) {
                    return null;
            }
        }
    
    
        /**
         * 获得随机数
         * @param len
         * @return
         */
        public static String randomStr(int len) {
            Random random = new Random();     
            StringBuffer sb = new StringBuffer();     
            for (int i = 0; i < len; i++) {     
                int number = random.nextInt(base.length());     
                sb.append(base.charAt(number));     
            }     
            return sb.toString();  
        }
    
        /**将二进制转换成16进制 
         * @param buf 
         * @return 
         */  
        public 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();  
        } 
        
        /**将16进制转换成2进制 
         * @param buf 
         * @return 
         */
        public 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;  
        }
        
        /**
         * 数据编码为BASE64字符串 转为 二进制
         * @param bytes
         * @return
         */
        public static byte[] decode(final byte[] bytes) {  
            return Base64.decodeBase64(bytes);  
        }  
        /** 
         * 二进制数据编码为BASE64字符串 
         * 
         * @param bytes 
         * @return 
         * @throws Exception 
         */  
        public static String encode(final byte[] bytes) {  
            return new String(Base64.encodeBase64(bytes));  
        }  
        /** 
         * 字符串转换unicode 
         */  
        public static String string2Unicode(String string) {  
            StringBuffer unicode = new StringBuffer();  
            for (int i = 0; i < string.length(); i++) {  
                // 取出每一个字符  
                char c = string.charAt(i);  
                // 转换为unicode  
                unicode.append("\u" + Integer.toHexString(c));  
            }  
            return unicode.toString();  
        } 
        /** 
         * unicode 转字符串 
         */  
        public static String unicode2String(String unicode) {  
            StringBuffer string = new StringBuffer();  
            String[] hex = unicode.split("\\u");  
            for (int i = 1; i < hex.length; i++) {  
                // 转换出每一个代码点  
                int data = Integer.parseInt(hex[i], 16);  
                // 追加成string  
                string.append((char) data);  
            }  
            return string.toString();  
        } 
        
        public static void main(String[] args) throws Exception {
            String content ="1231";
            String key = "AAAAAAAAAAAAAAAA";
            // 加密
            System.out.println("加密前:"+content );
            String tt4 = encryptECB(content, key);
            System.out.println(new String(tt4));
    
            // 解密
            String d = decryptECB(tt4, key);
            System.out.println("解密后:"+ d);
        }
        
    }

    结果输出

    加密前:1231
    15428541F01951FF4F0A2990535F2C81
    解密后:1231
  • 相关阅读:
    spark 集合交集差集运算
    Scala学习笔记1(安装)
    shell脚本调用spark-sql
    R语言中判断是否是整数。以及读写excel
    el-table的type="selection"的使用
    el-mement表单校验-校验失败时自动聚焦到失败的input框
    "org.eclipse.wst.validation" has been removed 导入maven 项目出错。
    java compiler level does not match the version of the installed java project facet 解决方案
    Referenced file contains errors (http://www.springframework.org/schema/context). For more information, right click on the message in the Problems
    编译异常 Caused by: java.lang.UnsupportedClassVersionError:
  • 原文地址:https://www.cnblogs.com/zwdx/p/8639583.html
Copyright © 2011-2022 走看看