app开发中避免抓包,使用数据加密传输(AES、Base64)

问题:当数据调用没有使用https加密时,app被抓包,接口暴露,此时可能导致被刷等安全问题

解决:1. 使用https传输

   2. 在进行数据传输时进行手动加密(app端和后端定义统一的加密方式),这里采用普遍使用的AES+Base64加密

新建工具类:

package com.demo.utils;


import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class AESUtil {

//    private static final String SECRET_KEY = "51f14cbda893c2bc13826c2c1a0c88aa";//32位小写
    private static final String SECRET_KEY = "a893c2bc13826c2c";//目前jdk版本只支持16位秘钥(32位的需添加jar包)前后端统一的秘钥
    private static String ivParameter = "xinyongdashi1111";//偏移量    前后端统一的偏移量// 加密
    public static String encrypt(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
            byte[] raw = SECRET_KEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");// 转换为AES专用密钥
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);// 初始化为加密模式的密码器
            byte[] byteRresult = cipher.doFinal(content.getBytes("utf-8"));// 加密
            return new StringBuilder(Base64.encode(byteRresult)).reverse().toString();//进行base64编码,并倒序转换
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
                | IllegalBlockSizeException | BadPaddingException e) {
            return "";
        } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return "";
        }
    }

    // 解密
    public static String decrypt(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        try {
            byte[] byteRresult = Base64.decode(new StringBuilder(content).reverse().toString());//倒序转换并base64解码
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
            byte[] raw = SECRET_KEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");// 转换为AES专用密钥
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteRresult);// 解密
            return new String(result);
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
                | IllegalBlockSizeException | BadPaddingException e) {
            return "";
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return "";
        }
    }
    
    public static void main(String[] args) {
        String content = "程序默认没有bug";
        System.out.println("加密之前:" + content);

        // 加密
        String jiami = AESUtil.encrypt(content);
        System.out.println("加密后的内容:" + jiami);

        // 解密
        String jiemi = AESUtil.decrypt(jiami);
        System.out.println("解密后的内容:" + jiemi);

    }

}

运行结果如图:

以下加密会出现问题

刚开始时使用了AES的另一种加密方式:但是在与android联调时出现问题,具体如下:

package com.mobile.utils;


import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class AESUtil {

//    private static final String SECRET_KEY = "51f14cbda893c2bc13826c2c1a0c88aa";//xinyongdashi MD5加密32位小写
    private static final String SECRET_KEY = "a893c2bc13826c2c";//目前jdk版本只支持16位秘钥(32位的需添加jar包)前后端统一的秘钥
    private static String ivParameter = "xinyongdashi1111";//偏移量    前后端统一的偏移量

    //此方法会在安卓和java联调时出现问题(默认随机数序列不一致)解决:不要使用默认的创建方法。
    public static String encry(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  // 创建AES的Key生产者
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");// 初始化出
            random.setSeed(SECRET_KEY.getBytes());//利用自定义SECRET_KEY作为随机数
            kgen.init(128, random);// 128位的key生产者       //加密没关系,SecureRandom是生成安全随机数序列,SECRET_KEY.getBytes()是种子,只要种子相同,序列就一样,所以解密只要有password就行
            SecretKey secretKey = kgen.generateKey();//根据用户密码,生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥,如果此密钥不支持编码,则返回null。
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化为加密模式的密码器
            byte[] byteRresult = cipher.doFinal(byteContent);// 加密
            /*StringBuilder sb = new StringBuilder();
            for (byte aByteRresult : byteRresult) {
                String hex = Integer.toHexString(aByteRresult & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();*/
            return new StringBuilder(Base64.encode(byteRresult)).reverse().toString();//进行base64编码
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String unencry(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        /*byte[] byteRresult = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            byteRresult[i] = (byte) (high * 16 + low);
        }*/
        try {
            byte[] byteRresult = Base64.decode(new StringBuilder(content).reverse().toString());//base64解码
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(SECRET_KEY.getBytes());//利用自定义SECRET_KEY作为随机数
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();//返回基本编码格式的密钥
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化为解密模式的密码器
            byte[] result = cipher.doFinal(byteRresult);
            return new String(result);
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
                | IllegalBlockSizeException | BadPaddingException e) {
            return "";
        }
    }public static void main(String[] args) {
        String content = "程序默认没有bug";
        System.out.println("加密之前:" + content);

        // 加密
        String jiami = AESUtil.encrypt(content);
        System.out.println("加密后的内容:" + jiami);

        // 解密
        String jiemi = AESUtil.decrypt(jiami);
        System.out.println("解密后的内容:" + jiemi);

    }

}

使用此方式加密的结果就是:android端的加密数据,后台解密不了;

猜你喜欢

转载自www.cnblogs.com/mufengforward/p/10532428.html