Java功能点:AES - HTTP安全通信实现

一、概述

AES是一种对称性的高级加密算法,又称Rijndael加密法。对称加密算法也就是加密和解密用相同的密钥。其网络传输流程如下:

 

二、加密算法实现

这里的实现,使用的是CBC 模式。其中数据填充处理,采用PKCS#5 算法。在此模式下,私钥的长度不得少于 16 位,否则安全性无法保证。

1、关键术语:

  •  私钥 :加/解密时使用的、不能公开的内容,由加/解密双方保存在安全的位置
  • l V向量 :用于参与加密,作为初始种子使用的一组数据,与私钥不同的是,可以公开

2、伪代码描述说明

  • 给定字符串S‘encryption-secret’用于计算密匙,明文P‘hello world’,IV为向量采用安全随机生成,密匙K=SUBSTR ( S, GET_KEY_SIZE () ),其中GET_KEY_SIZE () 为CBC 模式下的私钥最大长度。
  • 描述:

 1)生成密匙:K=SUBSTR ( S, GET_KEY_SIZE () )/3生成向量:IV=SECURE_RANDOM()

 2)加密初始化:INIT( K, IV )

 3)生成密文:ENC = doFinal( DAT )

 4)输出加密信息:OUT=IV +ENC

注:这里的密匙必须为16位;输出结果是IV+ENC,这里输出IV是为了解密是用的,IV暴露不影响安全性。

3、java代码实现

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;

public class AES {
    final String KEY_ALGORITHM = "AES";    // 算法
   final String algorithmStr = "AES/CBC/PKCS5Padding"; // 填充类型("算法/模式/补码方式")
   private Key key;           //JAVA的密钥格式
   private Cipher cipher;
   static int ivLength=0;     //iv向量的长度
   
   /**
    * 加密和解密前的初始化(这种模式下密匙、iv向量的长度都是16)
    */
   public void init(byte[] keyBytes) throws Exception {
       //加入bouncyCastle支持 
       Security.addProvider(new BouncyCastleProvider());
       //初始化cipher
       cipher = Cipher.getInstance(algorithmStr, "BC");
       //获取iv向量长度
       ivLength=cipher.getBlockSize();   
      
       //密匙不足(ivLength)位的倍数,补足
       if (keyBytes.length % ivLength != 0) {
          int groups = keyBytes.length / ivLength + (keyBytes.length % ivLength != 0 ? 1 : 0);
          byte[] temp = new byte[groups * ivLength];
          Arrays.fill(temp, (byte) 0);
          System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
          keyBytes = temp;
       }
       //密匙超过(ivLength)位进行截取
       if(keyBytes.length>ivLength){
          byte[] temp = new byte[ivLength];
          Arrays.fill(temp, (byte) 0);
          System.arraycopy(keyBytes, 0, temp, 0, ivLength);
          keyBytes = temp;
       }      
       // 转化成JAVA的密钥格式  
       key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
   }
   
    /**
     * 加密 
     */
    public byte[]  encrypt(byte[] content, byte[] keyBytes) throws Exception {
       byte[] encryptedText = null;
       init(keyBytes);                            //初始化
       
       byte[] iv=new byte[ivLength];              //定义iv向量
       SecureRandom random = new SecureRandom();  //SecureRandom用于自动生成iv向量
       random.nextBytes(iv);
       try {
          cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
          encryptedText = cipher.doFinal(content);
       } catch (Exception e) {
          e.printStackTrace();
       }
       byte[] result = new byte[ivLength+encryptedText.length];                  
       System.arraycopy(iv, 0, result, 0, ivLength);//将iv和加密后的内容拼接
       System.arraycopy(encryptedText, 0, result, ivLength, encryptedText.length);
       return result;
    }
    
    
    /**
     *解密
     */
    public  byte[] decrypt(byte[] encryptedData, byte[] keyBytes) throws Exception {
       byte[] encryptedText = null;
       init(keyBytes);
      //将获取的密文,分离成iv和对应的内容
       byte[] iv=new byte[ivLength];                      
       byte[] data=new byte[encryptedData.length-16];      
       System.arraycopy(encryptedData, 0, iv, 0, 16);
       System.arraycopy(encryptedData, ivLength, data, 0, encryptedData.length-ivLength);
    
       try {
          cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
          encryptedText = cipher.doFinal(data);
       } catch (Exception e) {
          e.printStackTrace();
       }
       return encryptedText;
    }

  • 添加测试方法
public class Test {
    @org.junit.Test
    public void test() throws Exception{
        String key = "1234567890123456";
        String content ="1024,程序员节快乐";

        AES aes = new AES();
        //加密
        byte[] encDate = aes.encrypt(content.getBytes("UTF-8"), key.getBytes("UTF-8"));
        System.out.println("加密:"+new String(encDate,"UTF-8"));
        //解密
        byte[] decDate = aes.decrypt(encDate,  key.getBytes("UTF-8"));
        System.out.println("解密:"+new String(decDate,"UTF-8"));
    }
}

  • 输出结果:

  加密:�u�ޢ�]C�?�!^P�r�M�tٴg���� ��d�ȂOOUQ�uOSwb

  解密:1024,程序员节快乐


  • 上面的代码已经实现了AES加密和解密。但这个例子中,只采用了单个密匙,有一定的安全隐患。为了进一步加强加密安全性,密钥采用定期轮换,这样可以加大攻击者的攻击难度。

三、密匙轮换

  • 密匙轮换,简单的说就是双方通信过程中,我们必须采用一个可变化的,且双方都已知的常量,作为索引,去“轮转”选择密钥。一般情况下我们都采用当前时间,取作索引,获取密匙,下面的例子,以当前时间的分钟作为索引。
  • 定义ASE工具类,用于获取密匙
public class AesStaticUntil {

   //定义数组有60个密匙
   static String[] keyList = {"84eq&e1iEtRo?k_U",

//省略58个密匙...

"cRlucOUm5U9t_epr"" };


   //根据时间获取密匙
   public static String getKey(Date date){
       //获取分钟
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      int minute= calendar.get(Calendar.MINUTE);
      //根据分钟获取密匙
      return keyList[minute];

   }
}

  • 修改测试方法
public class Test {
    @org.junit.Test
    public void test() throws Exception{
        //根据当前时间获取密匙
        String key = AesStaticUntil.getKey(new Date());
        String content ="1024,程序员节快乐";

        AES aes = new AES();
        //加密
        byte[] encDate = aes.encrypt(content.getBytes("UTF-8"), key.getBytes("UTF-8"));
        System.out.println("加密:"+new String(encDate,"UTF-8"));
        //解密
        byte[] decDate = aes.decrypt(encDate,  key.getBytes("UTF-8"));
        System.out.println("解密:"+new String(decDate,"UTF-8"));
    }
}

测试结果同上

 

四、http安全通信

  • 上面的例子虽然采用当前时间获取动态密匙,但由于网络传输延迟、系统时间差异等,会造成一个“漂移”现象。可能会导致双方加解密失败。
  • 例如,请求由 A 系统向 B 系统发起(假设双方系统时间准确),A 系统发起请求的时间为 10时59分59秒,此时对应的密钥为 '123'。由于网络传输耗时,B 系统收到并处理此数据时,时间已是11时00分00秒,此时对应的密钥为 '456,此刻 B 系统中,解密就会失败,A 系统不得不重新发起请求(重试)。这样,系统复杂度会大大上升。
  • 解决方法:伪装http请求的Date,即将推送的时间伪装成格林格式的时间。
  • http请求代码(以流的形式发送报文)
public class MyHttpRequest {
   //url:请求地址,param:请求内容,date:获取密匙的时间(用于伪装时间)
    public static HashMap<String, Object> sendPost(String url, String param, Date date) throws Exception {

      StringBuffer buffer = new StringBuffer();
      URL getUrl = new URL(url);
      HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setUseCaches(false);
      connection.setConnectTimeout(10000);
      
      //伪装发送时间
      String strDate="";
      SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
      format.setTimeZone(TimeZone.getTimeZone("GMT"));  //如果不加这个语句,取的是中国时间
      strDate = format.format(date);
      connection.setRequestProperty("Date", strDate);
      connection.setRequestProperty("Content-Type", "application/xml");  //传输xml

      connection.connect();
      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
      out.write(param);
      out.flush();
      out.close();
      // 获取所有响应头字段(获取响应时间用于解密)
      Map<String, List<String>> map = connection.getHeaderFields();
      String reponseDate = map.get("Date").get(0);
   
      BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
      String line = "";
      while ((line = reader.readLine()) != null) {
         buffer.append(line);
      }
      reader.close();
      String reponseText = buffer.toString();
      //返回结果和解密
      HashMap<String, Object> result = new HashMap<String, Object>();
      result.put("date", reponseDate);
      result.put("reponseText", reponseText);       
      return result;
   }
}

注:推送报文是,需要用 base64 进行编码,即参数param是经过base64编码的,当然对于响应的报文需要进行解码便于使用基础通信协议进行传输

  • 测试方法
public class Test {
    @org.junit.Test
    public void test() throws Exception{
        //发送请求
        String content ="1024,程序员节快乐";
        AES aes = new AES();
        Date date  = new Date();
        //1.获取key
        String key = AesStaticUntil.getKey(new Date());
        //2.加密
        byte[] encDate = aes.encrypt(content.getBytes("UTF-8"), key.getBytes("UTF-8"));
        System.out.println("加密:"+new String(encDate,"UTF-8"));
        //3.推送报文(报文内容进行base64为加密),并且返回响应信息
        HashMap<String, Object> result = MyHttpRequest.sendPost("http:XXX",  new sun.misc.BASE64Encoder().encode(encDate), date);
        //4、进行解密(ase解密前需要进行base64解密)
        String  resultDate= result.get("Date").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        Date reponseDate = sdf.parse(resultDate); //获取返回时间
        String reponseText =result.get("reponseText").toString();

        //根据返回时间获取key
        String reponsekey = AesStaticUntil.getKey(reponseDate);
        //第一次解密失败,加一分钟再次解密,如果还是失败就按失败处理
        byte[] decDate =null;
        try{
             decDate = aes.decrypt(new sun.misc.BASE64Decoder().decodeBuffer(reponseText),  reponsekey.getBytes("UTF-8"));
        }catch(Exception e){
            Calendar cal = Calendar.getInstance();
            cal.setTime(reponseDate);
            cal.add(Calendar.MINUTE, 1);
            reponseDate =  sdf.parse(sdf.format(cal.getTime()));
            reponsekey = AesStaticUntil.getKey(reponseDate);
             decDate = aes.decrypt(new sun.misc.BASE64Decoder().decodeBuffer(reponseText),  reponsekey.getBytes("UTF-8"));
        }
        System.out.println("解密:"+new String(decDate,"UTF-8"));
    }
}

注:这里在第一次解密失败的时候,进行时间加一分钟后继续解密,这是因为在请求时候,我获取的当前时间是2018-07-15 02:09:59.99,这时候获取密匙是按9分钟去获取的,但是在对方接受到这个请求的时候,取到的时间可能是2018-07-15 02:10:00,导致密匙不一致,加上一分钟基本上就能解决这个问题(之前有个项目就是被这一分钟搞懵了)

  • 模拟servlet进行接受数据
public class AesServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("text/xml; charset=UTF-8");

            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 获取界面时间时间
            String date = request.getHeader("Date");

            final int bufferSize = 1024;
            final char[] buffer = new char[bufferSize];
            final StringBuilder out = new StringBuilder();
            try {
                InputStream inputStream = request.getInputStream();
                Reader in = new InputStreamReader(inputStream, "UTF-8");
                for (; ; ) {
                    int rsz = in.read(buffer, 0, buffer.length);
                    if (rsz < 0)
                        break;
                    out.append(buffer, 0, rsz);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取报文信息
            String requestContent = out.toString();

            //接受解密
            String responseContent = servletDes(date,requestContent);
            //返回信息
            writer.write(responseContent);
        }catch (Exception e){
            writer.write("接受数据失败");
        }
    }

    public String  servletDes(String  resultDate, String requestContent) throws Exception{
        //返回信息
        String reponseOfDec="";

        AES aes = new AES();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        Date reponseDate = sdf.parse(resultDate); //获取返回时间

        //根据返回时间获取key
        String reponsekey = AesStaticUntil.getKey(reponseDate);
        //第一次解密失败,加一分钟再次解密,如果还是失败就按失败处理
        byte[] decDate =null;
        try{
            decDate = aes.decrypt(new sun.misc.BASE64Decoder().decodeBuffer(requestContent),  reponsekey.getBytes("UTF-8"));
        }catch(Exception e){
            Calendar cal = Calendar.getInstance();
            cal.setTime(reponseDate);
            cal.add(Calendar.MINUTE, 1);
            reponseDate =  sdf.parse(sdf.format(cal.getTime()));
            reponsekey = AesStaticUntil.getKey(reponseDate);
            decDate = aes.decrypt(new sun.misc.BASE64Decoder().decodeBuffer(requestContent),  reponsekey.getBytes("UTF-8"));
        }

        //进行业务处理,并将处理后的加密信息返回
        //bussiness(decDate)
        return reponseOfDec;
    }
}

注:如果要防止请求丢失,可进行CRC32校验


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值