網際網路互動加密安全:ECDH/ECC祕鑰磋商和AES加密組合加密
最近在專案中用到了一個加密方式,ECDH/ECC祕鑰磋商。
然後使用AES加密,這個加密方式非常的有點繞,也就是如此,他的加密方式會稍微有點麻煩,但是安全性我個人覺得比現在市面上的大多數組合對稱加密方式要安全吧。
這是一個組合的加密方式,通過ECDH演算法的EC/BC Provider進行祕鑰磋商,得到一個Key對請求和響應的報文進行安全AES演算法加密。
1. 我們先來了解下AES加密演算法:
高階加密標準(AES,Advanced Encryption Standard)為最常見的對稱加密演算法(微信小程式加密傳輸就是用這個加密演算法的)。對稱加密演算法也就是加密和解密用相同的金鑰,具體的加密流程如下圖:
2. 然後是ECDH/ECC祕鑰磋商:
ECC:Elliptic Curves Cryptography,橢圓曲線密碼編碼學
ECDSA:用於數字簽名,是ECC與DSA的結合,整個簽名過程與DSA類似,所不一樣的是簽名中採取的演算法為ECC,最後簽名出來的值也是分為r,s。
ECDH:是基於ECC(Elliptic Curve Cryptosystems,橢圓曲線密碼體制,參看ECC)的DH( Diffie-Hellman)金鑰交換演算法。交
重點說一下,ECDH用途:
由於通過ECDH,雙方可以在不共享任何祕密的前提下協商出一個共享祕密,因此,ECDH廣泛用於協議之中,通過ECDH得到對稱加密金鑰。如TLS中的*_ECDH_*密碼套件。使用DH演算法的協議,都可以升級到ECDH演算法。ECDH具有ECC的高強度、短金鑰長度、計算速度快等優點。
金鑰交換過程:
假設金鑰交換雙方為Alice、Bob,其有共享曲線引數(橢圓曲線E、階N、基點G)。
1.Alice生成隨機整數a,計算A=a*G。Bob生成隨機整數b,計算B=b*G。
2.Alice將A傳遞給Bob。A的傳遞可以公開,即攻擊者可以獲取A。由於橢圓曲線的離散對數問題是難題,
所以攻擊者不可以通過A、G計算出a。Bob將B傳遞給Alice。同理,B的傳遞可以公開。
3.Bob收到Alice傳遞的A,計算Q=b*A
4.Alice收到Bob傳遞的B,計算Q‘=a*B
最終:Alice、Bob雙方即得Q=b*A=b*(a*G)=(b*a)*G=(a*b)*G=a*(b*G)=a*B=Q' (交換律和結合律),
即雙方得到一致的金鑰Q
3.最後是使用ECDH/ECC祕鑰磋商,為AES加密提供加密/解密Key:
具體過程:
(1)伺服器初始化時,客戶端和服務端都會生成各自的一對初始化公私鑰,並各自擁有對方的初始化公鑰;
(2)客戶端請求服務端時,會生成一對臨時公私鑰,並使用初始化私鑰對明文進行加簽,然後客戶端臨時私鑰與服務端初始化公鑰進行祕鑰磋商生成key,使用key對加簽後的明文進行AES加密,對可無端請求時,會將簽名,客戶端臨時公鑰和密文一起傳給服務端;
(3)服務端獲取請求引數後,會使用客戶端臨時公鑰和自己服務端初始化私鑰進行祕鑰磋商獲得key,對明文進行AES解密,
然後使用簽名,客戶端初始化公鑰對密文進行解密操作;
另外這裡客戶端和服務端祕鑰磋商生成的key是一模一樣的,這就ECDH/ECC祕鑰磋商的效果
下面是我寫的簡單測試類
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import com.google.common.collect.Maps;
import cn.sunline.common.exception.ProcessException;
public class AESTest {
private static Logger logger = LoggerFactory.getLogger(AESTest.class);
private static final String DEFAULT_CHARSET = "UTF-8";
private static final String KEY_SET = "AES";
private final static String charset = "utf-8";
private final static String KEY_INSTANCE = "EC";
private final static String SIGN_INSTANCE = "SHA1withECDSA";
private final static String PROVIDER = "BC";
private final static String ECDH = "ECDH";
/** 服務端初始化公鑰 */
private static String serPubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEr5ztcktUiBfJuVSA2TQ+8CkSvtLNQRZg3XhyxlbAr+LxRg31WAC0mpIVx4PQEAZ9wyiIkD/2sPkA0ABIdxMEqQ==";
/** 服務端初始化私鑰 */
private static String serPriKey = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCAqpgFzWbt1EAEkhH9iU68J6IxPSRLhNSVPS26PmiDcmQ==";
/** 服務端臨時公鑰 */
private static String tmpSerPubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0sCyuvgbTD8mdIcGtHm4VRp0Mgp9MEtTLwIxCb37K4If48B9eotGBtpZOIimQAUoX6U+rkyFumKCmpwMd1eRkQ==";
/** 服務端臨時私鑰 */
private static String TmpSerPriKey = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCD2I/MPxobXJFH3ZuqXqtfxARJhMMR4QG1IMaez/Yytgg==";
/** 客戶端初始化公鑰 */
private static String cliPubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEwPf1HGy6slx7a3Ne/uIlfry2mOBsUOfNjoVkgNxbD+4YC2Uz0fiyJf8i/w2XD9OiYI2aap7h8ez+45g+butSQ==";
/** 客戶端初始化私鑰 */
private static String cliPriKey = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCDqh6fROJMhkWVuoee3bZKCEnnIT2nNBE+mgfqwAvvKfw==";
/** 客戶端臨時公鑰 */
private static String TmpCliPubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEtUYCQoax8bFbqpm4t797AzikHfOAhRyAJXctcZw7Ff3mW5uE6Nlq1TxjieySojdL9oHrsLgDC7je4bS9veGR5A==";
/** 客戶端臨時私鑰 */
private static String TmpCliPriKey = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA65SA+i6fh1KuNI9Nd5zK8A5+1d5473w0DEXZ+LwAGTQ==";
public static void main(String[] args) {
// String content = "7FD7C96E02B52341FD415374F0E3487B55F4987F87A32A8935A92AC6088ACE2B726AA314A3D4D52AA5874FC51CCC8CB3F6FF943E6CF224E6B3C7FED3D07DFFCBD82583D78BC58518149D79D956D0005DC3788D342855810306DF6B788CDD641364F00887736676C6347E19133D77A89221C025E9E0718B979ACFA8A532C14FC8FBF6C5C66B08FD5858C781F3911F375E17AEB8108CC79E87BA728BE2F39EBBDC4397ECEFE7EE961C4BF3ECF06BAFEA341B5BB93E7003B7228937C62CFDAE814A98B9B7644891CF0A62EC33B842B12D624DCC3A0FBFED9755EC600A355500BD76989AAE79AF43958F2258EBD2093C2F85";
// String content = "{\"serviceHeader\":{\"serviceId\":\"1010\",\"responseCode\":\"000000\",\"responseMsg\":\"請求成功\"},\"serviceBody\":{\"sessionId\":\"bf2d5af85239439aa56db5a149ddaaac\",\"userId\":null,\"deviceId\":\"990009263463476\",\"lastAccessTime\":\"2018-06-11 14:30:21\"}}";
Scanner scanner = new Scanner(System.in);
System.out.println("請開始你的操作:1.客戶端請求內容加密, 2.服務端對請求內容解密, 3.服務端相應內容解密, 4.客戶端對服務端相應內容解密");
System.out.println("請輸入要操作的編號:");
int number = scanner.nextInt();
switch (number) {
case 1:
System.out.println("開始客戶端加密--------------------->");
System.out.println("輸入你要加密的內容後回車:");
String content1 = scanner.next();
//客戶端加密
Map<String, String> clientRequest = encryption(content1);
String secretContent = clientRequest.get("secretContent");
String signData = clientRequest.get("signData");
System.out.println("加密後內容:"+secretContent);
System.out.println("加密後簽名:"+signData);
break;
case 2:
System.out.println("開始服務端解密--------------------->");
System.out.println("輸入你要解密的內容後回車:");
String secretContent1 = scanner.next();
System.out.println("輸入你的簽名:");
String signData1 = scanner.next();
//服務端解密
Map<String, String> sercerRequest = decryption(secretContent1, signData1);
String textContent = sercerRequest.get("textContent");
String res = sercerRequest.get("res");
System.out.println("解密後:"+textContent);
System.out.println("解密後驗簽結果:"+res);
break;
case 3:
System.out.println("開始服務端加密--------------------->");
System.out.println("輸入你要加密的內容後回車:");
String content2 = scanner.next();
//服務端加密
Map<String, String> serverResponse = serverEncryption(content2);
String secretContent3 = serverResponse.get("secretContent");
String signData3 = serverResponse.get("signData");
System.out.println("加密後內容:"+secretContent3);
System.out.println("加密後簽名:"+signData3);
break;
case 4:
System.out.println("開始客戶端解密--------------------->");
System.out.println("輸入你要加密的內容後回車:");
String secretContent2 = scanner.next();
System.out.println("輸入你的簽名:");
String signData2 = scanner.next();
//客戶端解密
Map<String, String> clientResponse = serverDecryption(secretContent2, signData2);
String textContent2 = clientResponse.get("textContent");
String res2 = clientResponse.get("res");
System.out.println("解密後:"+textContent2+", 解密後驗簽結果:"+res2);
break;
default:
break;
}
System.out.println("|---------------------------------------------------------------------------------------------------|");
System.out.println("| |");
System.out.println("|----------------------------------------服務結束,以上是結果內容-------------------------------------|");
System.out.println("| |");
System.out.println("|---------------------------------------------------------------------------------------------------|");
//
//
//
// Map<String, String> keys = generatorKey();
// String serPub = keys.get("serPubKey");
// String serPri = keys.get("serPriKey");
// String cliPub = keys.get("cliPubKey");
// String cliPri = keys.get("cliPriKey");
//
// System.out.println(serPub);
// System.out.println(serPri);
// System.out.println(cliPub);
// System.out.println(cliPri);
}
/**
* client加密前置
* @param content
* @return
*/
public static Map<String, String> encryption(String content){
System.out.println("加密前:"+content);
Map<String, String> encrypt = encrypt(content, TmpCliPriKey, serPubKey, cliPriKey);
return encrypt;
}
/**
* server解密前置
* @param secretContent
* @param signData
* @return
*/
public static Map<String, String> decryption(String secretContent, String signData){
Map<String, String> result = decrypt(secretContent, TmpCliPubKey, serPriKey, cliPubKey, signData);
return result;
}
/**
* server加密前置
* @param content
* @return
*/
public static Map<String, String> serverEncryption(String content){
System.out.println("加密前:"+content);
Map<String, String> encrypt = encrypt(content, TmpSerPriKey, cliPubKey, serPriKey);
return encrypt;
}
/**
* client解密前置
* @param secretContent
* @param signData
* @return
*/
public static Map<String, String> serverDecryption(String secretContent, String signData){
//解密 + 驗籤
Map<String, String> result = decrypt(secretContent, tmpSerPubKey, cliPriKey, serPubKey, signData);
return result;
}
/**
* 加密
* @param content 待加密明文
* @param serPriKey 服務端私鑰用於加簽
* @param cliPubKey 客戶端公鑰用於和生成的服務端臨時私鑰磋商加密
* @param cliPriKey2
* @return
*/
public static Map<String, String> encrypt(String content, String TmpCliPriKey, String serPubKey, String cliPriKey){
Map<String, String> result = Maps.newHashMap();
try {
//加簽
String signData = sign(cliPriKey, content);
System.out.println("加簽:"+signData);
//祕鑰磋商
String key = ecdhKey(TmpCliPriKey, serPubKey);
System.out.println("加鎖鑰匙:ecdhKey[----------{"+key+"}----------]");
String secretContent = doAES(content, key, Cipher.ENCRYPT_MODE);
result.put("secretContent", secretContent);
result.put("signData", signData);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 解密
* @param signData2
* @param data 明文
* @param key 加密祕鑰
* @param cliPubKey
* @return
*/
public static Map<String, String> decrypt(String content, String TmpCliPubKey, String serPriKey, String cliPubKey, String signData){
Map<String, String> result = Maps.newHashMap();
try {
//祕鑰磋商
String key = ecdhKey(serPriKey, TmpCliPubKey);
System.out.println("開鎖鑰匙:ecdhKey[----------{"+key+"}----------]");
String textContent = doAES(content, key, Cipher.DECRYPT_MODE);
System.out.println("解密後內容:" + textContent);
//驗籤
boolean res = verify(textContent, cliPubKey, signData);
result.put("textContent", textContent);
result.put("res", res+"");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 驗籤
* @param textContent 解密明文
* @param serPubKey 服務端公鑰
* @param signData 簽名
* @return
*/
private static boolean verify(String textContent, String serPubKey, String signData) {
try {
//驗籤
byte[] keyBytes = Base64Utils.decode(serPubKey.getBytes(charset));
byte[] contentBytes = Base64Utils.decode(textContent.getBytes(charset));
byte[] signBytes = Base64Utils.decode(signData.getBytes(charset));
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_INSTANCE);
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Signature signature = Signature.getInstance(SIGN_INSTANCE);
signature.initVerify(publicKey);
signature.update(contentBytes);
return signature.verify(signBytes);
} catch (Exception e) {
logger.error("報文簽名驗證出現異常", e);
throw new ProcessException("", "報文簽名驗證出現異常");
}
}
/**
* 祕鑰磋商
* @param serPriKey
* @param cliPubKey
* @return
*/
private static String ecdhKey(String serPriKey, String cliPubKey) {
try {
//使用ECDH-BC前,BC方法新增進環境資訊內
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//初始化ecdh keyFactory
KeyFactory keyFactory = KeyFactory.getInstance(ECDH, PROVIDER);
//處理私鑰
byte[] priKeyBytes = Base64Utils.decode(serPriKey.getBytes(charset));
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(priKeyBytes);
PrivateKey ecPriKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//處理公鑰
byte[] pubKeyBytes = Base64Utils.decode(cliPubKey.getBytes(charset));
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubKeyBytes);
PublicKey ecPubKey = keyFactory.generatePublic(pubX509);
//祕鑰磋商生成新的祕鑰byte陣列
KeyAgreement aKeyAgree = KeyAgreement.getInstance(ECDH, PROVIDER);
aKeyAgree.init(ecPriKey);
aKeyAgree.doPhase(ecPubKey, true);
return Base64Utils.encodeToString(aKeyAgree.generateSecret());
} catch (Exception e) {
logger.error("祕鑰磋商出現異常", e);
throw new ProcessException("", "祕鑰磋商出現異常");
}
}
/**
* 加簽
* @param serPriKey
* @param content
* @return
*/
private static String sign(String serPriKey, String content) {
try {
byte[] keyBytes = Base64Utils.decode(serPriKey.getBytes(charset));
byte[] contentBytes = Base64Utils.decode(content.getBytes(charset));
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_INSTANCE);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance(SIGN_INSTANCE);
signature.initSign(privateKey);
signature.update(contentBytes);
return Base64Utils.encodeToString(signature.sign());
} catch (Exception e) {
logger.error("報文加簽出現出現異常", e);
throw new ProcessException("", "報文加簽出現出現異常");
}
}
private static String doAES(String data, String key, int mode) {
try {
if(StringUtils.isBlank(data) || StringUtils.isBlank(key)){
return null;
}
boolean encrypt = mode == Cipher.ENCRYPT_MODE;
byte[] content;
//判斷加密還是解密
if(encrypt){
content = data.getBytes(DEFAULT_CHARSET);
}else{
content = parseHexStr2Byte(data);
}
//1.構造祕鑰生成器,指定為AES演算法,不區分大小寫
KeyGenerator kgen = KeyGenerator.getInstance(KEY_SET);
//2.根據EncodeResult規則初始化祕鑰生成器,生成一個128位的隨機源,根據傳入的位元組陣列
kgen.init(128, new SecureRandom((key.getBytes())));
//3.產生原始對稱祕鑰
SecretKey secretKey = kgen.generateKey();
//4.獲取原始對稱祕鑰的位元組陣列
byte[] enCodeFormat = secretKey.getEncoded();
//5.根據位元組陣列生成AES祕鑰
SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, KEY_SET);
//6.根據指定演算法AES自稱密碼器
Cipher cipher = Cipher.getInstance(KEY_SET);
//7.初始化祕鑰器,第一個引數為加密或者解密操作,第二個引數為使用的Key
cipher.init(mode, keySpec);//初始化
byte[] result = cipher.doFinal(content);
if(encrypt){
//將二進位制轉化成16進位制
return parseByte2HexStr(result);
}else{
return new String(result, DEFAULT_CHARSET);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 將二進位制轉化成十六進位制
* @param result
* @return
*/
private static String parseByte2HexStr(byte[] result) {
StringBuffer buffer = new StringBuffer();
for (int i=0;i < result.length;i++){
String hex = Integer.toHexString(result[i] & 0xFF);
if(hex.length() == 1){
hex = '0' + hex;
}
buffer.append(hex.toUpperCase());
}
return buffer.toString();
}
/**
* 將十六進位制轉換成二進位制
* @param data
* @return
*/
private static byte[] parseHexStr2Byte(String data) {
if(data.length() < 1){
return null;
}
int hexStr = data.length() / 2;
byte[] result = new byte[hexStr];
for(int i=0;i<hexStr;i++){
int high = Integer.parseInt(data.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(data.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 +low);
}
return result;
}
/**
* 生成客戶端服務端初始化公私鑰
* @return
*/
public static Map<String, String> generatorKey(){
Map<String, String> keys = Maps.newHashMap();
try {
Provider provider = new BouncyCastleProvider();
//1.服務端初始化金鑰
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", provider);
keyPairGenerator.initialize(256);
KeyPair keyPair = keyPairGenerator.generateKeyPair(); //生成金鑰對
// 生成服務端公私鑰
String serPubKey = Base64Utils.encodeToString(keyPair.getPublic().getEncoded());
String serPriKey = Base64Utils.encodeToString(keyPair.getPrivate().getEncoded());
//1.客戶端初始化金鑰
KeyPairGenerator keyPairGenerator2 = KeyPairGenerator.getInstance("ECDH", provider);
keyPairGenerator2.initialize(256);
KeyPair keyPair2 = keyPairGenerator2.generateKeyPair(); //生成金鑰對
// 生成客戶端公私鑰
String cliPubKey = Base64Utils.encodeToString(keyPair2.getPublic().getEncoded());
String cliPriKey = Base64Utils.encodeToString(keyPair2.getPrivate().getEncoded());
keys.put("serPubKey", serPubKey);
keys.put("serPriKey", serPriKey);
keys.put("cliPubKey", cliPubKey);
keys.put("cliPriKey", cliPriKey);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return keys;
}
}
---------------------