Base64AesEncryptUtils.java 6.7 KB
package com.glsx.libble.util;

import android.util.Base64;

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.spec.SecretKeySpec;

/**
 * @Package: com.glsx.module_carkey.util
 * @ClassName: Base64AesEncryptUtils
 * @Company GLSX
 * @Email yangks@didihu.com.cn
 * @Description: 作用描述:
 * @Author: yangks
 * @CreateDate: 2021/4/21 11:07
 * @Version:
 */
public class Base64AesEncryptUtils {
    //参数分别代表 算法名称/加密模式/数据填充方式
    private final static String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param content    加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) {
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        kgen.init(128);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(ALGORITHMSTR);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] b = new byte[0];
        try {
            b = cipher.doFinal(content.getBytes("utf-8"));
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeToString(b, Base64.DEFAULT);

    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) {
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        kgen.init(128);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(ALGORITHMSTR);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decode(encryptStr, Base64.DEFAULT);
        //ToolUtils.log_d("yuzhizhe---encryptBytes--"+ ToolUtils.bytes2String(encryptBytes));
        byte[] decryptBytes = new byte[0];
        try {
            decryptBytes = cipher.doFinal(encryptBytes);
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return new String(decryptBytes);
    }

    public static void main(String[] args) throws Exception {
        //Map map = new HashMap<String, String>();
        //map.put("key", "value");
        //map.put("中文", "汉字");
        //String content = JSONObject.toJSONString(map);
        //System.out.println("加密前:" + content);
        //
        //String encrypt = encrypt(content, KEY);
        //System.out.println("加密后:" + encrypt);
        //
//        String decrypt = decrypt1("6GRXvnluinolZWMqxHYFgG7+x8XoVSYlsYRRP/Zla5Y=", "0BDsQu0naQF9BYGr");
//        System.out.println("解密后:" + decrypt);

        //获取16位随机密钥
        //String secret = getGUID();
        //System.out.println("生成key:" + secret);


    }

    public static String decrypt1(String encryptStr, String decryptKey) {
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        kgen.init(128);
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decode(encryptStr, Base64.DEFAULT);
        byte[] decryptBytes = new byte[0];
        try {
            decryptBytes = cipher.doFinal(encryptBytes);
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return new String(decryptBytes);
    }


    /**
     * 生成16位不重复的随机数,含数字+大小写
     *
     * @return
     */
    public static String getGUID() {
        StringBuilder uid = new StringBuilder();
        //产生16位的强随机数
        Random rd = new SecureRandom();
        for (int i = 0; i < 16; i++) {
            //产生0-2的3位随机数
            int type = rd.nextInt(3);
            switch (type) {
                case 0:
                    //0-9的随机数
                    uid.append(rd.nextInt(10));
         /*int random = ThreadLocalRandom.current().ints(0, 10)
         .distinct().limit(1).findFirst().getAsInt();*/
                    break;
                case 1:
                    //ASCII在65-90之间为大写,获取大写随机
                    uid.append((char) (rd.nextInt(25) + 65));
                    break;
                case 2:
                    //ASCII在97-122之间为小写,获取小写随机
                    uid.append((char) (rd.nextInt(25) + 97));
                    break;
                default:
                    break;
            }
        }
        return uid.toString();
    }
}