http安全 Java_AES - HTTP安全通信实现(java)
一、概述
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 () )
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"));
}
}
輸出結果:
上面的代碼已經實現了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
總結
以上是生活随笔為你收集整理的http安全 Java_AES - HTTP安全通信实现(java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QGIS离线GeoJSON数据,使用Ce
- 下一篇: Java1.7版本解码base64_JD