http安全 Java_AES - HTTP安全通信实现(java)

本文介绍了如何使用Java的AES算法实现HTTP安全通信。通过CBC模式加密,结合PKCS#5填充,确保数据安全。文章详细展示了加密、解密过程的Java代码,并探讨了密钥轮换和HTTP请求中时间同步问题的解决方案。
摘要由CSDN通过智能技术生成

一、概述

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

dfdf674dfffdfa09d36e26f36800be91.png

二、加密算法实现

这里的实现,使用的是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 () )

2)生成向量:IV=SECURE_RANDOM()

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

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

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

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

3、java代码实现

public classAES {final String KEY_ALGORITHM = "AES"; //算法

final String algorithmStr = "AES/CBC/PKCS5Padding"; //填充类型("算法/模式/补码方式")

private Key key; //JAVA的密钥格式

privateCipher cipher;static int ivLength=0; //iv向量的长度

/*** 加密和解密前的初始化(这种模式下密匙、iv向量的长度都是16)*/

public void init(byte[] keyBytes) throwsException {//加入bouncyCastle支持

Security.addProvider(newBouncyCastleProvider());//初始化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 = newSecretKeySpec(keyBytes, KEY_ALGORITHM);

}/*** 加密*/

public byte[] encrypt(byte[] content, byte[] keyBytes) throwsException {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,newIvParameterSpec(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);returnresult;

}/***解密*/

public byte[] decrypt(byte[] encryptedData, byte[] keyBytes) throwsException {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,newIvParameterSpec(iv));

encryptedText=cipher.doFinal(data);

}catch(Exception e) {

e.printStackTrace();

}returnencryptedText;

}public static void main(String[] args) throwsException {

String key= "1234567890123456";

String content="1024,程序员节快乐";

AES aes= newAES();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"));

}

}

输出结果:

96d2b3ab852b03562abbabe02088da09.png

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

三、密匙轮换

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

1、定义密匙常量类

public classStaticConstant {//定义数组有60个值

static String [] keyList = {"abcQoU0iA6rLeabc",//此处省去58个字符串

"abcq&e1iEtRo?abc"};

2、根据时间获取动态密匙方法

publicString getKey(Date date){

Calendar calendar=Calendar.getInstance();

calendar.setTime(date);int minute=calendar.get(Calendar.MINUTE);returnStaticConstant.keyList[minute];

}

3、修改main方法:

public static void main(String[] args) throwsException {

String content="1024,程序员节快乐";

AES aes= newAES();//获取key

String key = aes.getKey(newDate());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 classMyHttpRequest {public static HashMap sendPost(String url, String param, Date date) throwsException {

StringBuffer buffer= newStringBuffer();

URL getUrl= newURL(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> 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 result = new HashMap();

result.put("date", reponseDate);

result.put("reponseText", reponseText);returnresult;

}

}

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

具体main实现方法如下

public static void main(String[] args) throwsException {//发送请求

String content ="1024,程序员节快乐";

AES aes= newAES();

Date date= newDate();//1.获取key

String key = aes.getKey(newDate());//2.加密

byte[] encDate = aes.encrypt(content.getBytes("UTF-8"), key.getBytes("UTF-8"));

System.out.println("加密:"+new String(encDate,"UTF-8"));//3.推送报文,并且返回响应信息。这里会对推送的信息进行base64编码

HashMap result = MyHttpRequest.sendPost("http:XXX", newsun.misc.BASE64Encoder().encode(encDate), date);//二、处理响应信息//1.解析时间

String reponseDate = result.get("Date").toString();

SimpleDateFormat sdf= new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);

date=sdf.parse(reponseDate);//2.获取密文和密匙

String reponseText = result.get("reponseText").toString();

key= aes.getKey(newDate());//3.解密,需对返回的密文进行base64解码

byte[] decDate = aes.decrypt(new sun.misc.BASE64Decoder().decodeBuffer(reponseText), key.getBytes("UTF-8"));

System.out.println("解密:"+new String(decDate,"UTF-8"));

}

DONE!   O(∩_∩)O

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值