问题:当数据调用没有使用https加密时,app被抓包,接口暴露,此时可能导致被刷等安全问题
解决:1. 使用https传输
2. 在进行数据传输时进行手动加密(app端和后端定义统一的加密方式),这里采用普遍使用的AES+Base64加密
(注:AES加密方式中,生成安全随机数序列的加密方式,会导致java和安卓联调时出现无法解密的问题,文末会说)
加密后预期结果:
新建工具类并测试:
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 = "ceshiceshi111111";//偏移量 前后端统一的偏移量// 加密 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); } }
java中Base64的加密工具封装:
package com.mobile.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; /** * Created by Administrator on 2017/10/25. */ public class Base64 { private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); public static String encode(byte[] data) { int start = 0; int len = data.length; StringBuffer buf = new StringBuffer(data.length * 3 / 2); int end = len - 3; int i = start; int n = 0; while (i <= end) { int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff); buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append(legalChars[(d >> 6) & 63]); buf.append(legalChars[d & 63]); i += 3; if (n++ >= 14) { n = 0; buf.append(" "); } } if (i == start + len - 2) { int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8); buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append(legalChars[(d >> 6) & 63]); buf.append("="); } else if (i == start + len - 1) { int d = (((int) data[i]) & 0x0ff) << 16; buf.append(legalChars[(d >> 18) & 63]); buf.append(legalChars[(d >> 12) & 63]); buf.append("=="); } return buf.toString(); } private static int decode(char c) { if (c >= 'A' && c <= 'Z') return ((int) c) - 65; else if (c >= 'a' && c <= 'z') return ((int) c) - 97 + 26; else if (c >= '0' && c <= '9') return ((int) c) - 48 + 26 + 26; else switch (c) { case '+': return 62; case '/': return 63; case '=': return 0; default: throw new RuntimeException("unexpected code: " + c); } } /** * Decodes the given Base64 encoded String to a new byte array. The byte array holding the decoded data is returned. */ public static byte[] decode(String s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { decode(s, bos); } catch (IOException e) { throw new RuntimeException(); } byte[] decodedBytes = bos.toByteArray(); try { bos.close(); bos = null; } catch (IOException ex) { System.err.println("Error while decoding BASE64: " + ex.toString()); } return decodedBytes; } private static void decode(String s, OutputStream os) throws IOException { int i = 0; int len = s.length(); while (true) { while (i < len && s.charAt(i) <= ' ') i++; if (i == len) break; int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3))); os.write((tri >> 16) & 255); if (s.charAt(i + 2) == '=') break; os.write((tri >> 8) & 255); if (s.charAt(i + 3) == '=') break; os.write(tri & 255); i += 4; } } public static void main(String[] args) throws UnsupportedEncodingException { String content = "程序默认没有bug"; System.out.println("加密之前:" + content); // 加密 String jiami = Base64.encode(content.getBytes("utf-8")); System.out.println("加密后的内容:" + jiami); // 解密 String jiemi = new String(Base64.decode(jiami)); System.out.println("解密后的内容:" + jiemi); } }
运行结果如图:
以下加密在进行与android联调时会出现问题(单纯java后台使用可以用)
刚开始时使用了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位小写//此方法会在安卓和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端的加密数据,后台解密不了;
所以应该使用AES中的cbc模式(秘钥+偏移向量),即文章开始说的。