登陆

极彩在线app下载-前后端别离架构中的接口安全(上)

admin 2019-12-04 347人围观 ,发现0个评论

互联网开展至今,已由传统的前后端一致架构演变为现在的前后端别离架构,开始的前端网页大多由JSP、ASP、PHP等动态网页技能生成,前后端非常耦合,也不利于扩展。现在的前端分支许多,如:Web前端、Android端、IOS端,乃至还有物联网等。前后端别离的优点便是后端只需求完成一套界面,一切前端即可通用。

前后端的传输经过HTTP进行传输,也带来了一些安全问题,假如抓包、模仿恳求、洪水进犯、参数绑架、网络爬虫等等。怎么对不合法恳求进行有用阻拦,维护合法恳求的权益是这篇文章需求评论的。

作者根据多年互联网后端开发经历,总结出了以下提高网络安全的方法:

  • 选用HTTPS协议
  • 密钥存储到服务端而非客户端,客户端应从服务端动态获取密钥
  • 恳求隐私接口,运用token机制校验其合法性
  • 对恳求参数进行合法性校验
  • 对恳求参数进行签名认证,避免参数被篡改
  • 对输入输出参数进行加密,客户端加密输入参数,服务端加密输出参数

那么,下面我将对以上方法打开做详细阐明。

HTTP VS HTTPS

一般的HTTP协议是以明文方法进行传输,不供给任何方法的数据加密,很简略解读传输报文。而HTTPS协议在HTTP基础上加入了SSL层,而SSL层经过证书来验证服务器的身份,并为浏览器和服务器之间的通讯加密,维护了传输过程中的数据安全。

动态密钥的获取

关于可逆加密算法,是需求经过密钥进行加解密,假如直接放到客户端,那么很简略反编译后拿到密钥,这是适当不安全的做法,因此考虑将密钥放到服务端,由服务端供给接口,让客户单动态获取密钥,详细做法如下:

1、客户端先经过RSA算法生成一套客户端的公私钥对(clientPublicKey和clientPrivateKey)

2、调用getRSA接口,服务端会回来serverPublicKey

3、客户端拿到serverPublicKey后,用serverPublicKey作为公钥,clientPublicKey作为明文对clientPublicKey进行RSA加密,调用getKey接口,将加密后的clientPublicKey传给服务端,服务端接收到恳求后会传给客户端RSA加密后的密钥

4、客户端拿到后以clientPrivateKey为私钥对其解密,得到终究的密钥,此流程完毕。

(注:上述说到的所以数据均不能保存到文件里,有必要保存到内存中,因为只要保存到内存中,黑客才拿不到这些中心数据,所以每次运用获取的密钥前先判别内存中的密钥是否存在,不存在,则需求获取。)

为了便于了解,我画了一个简略的流程图:


那么详细是怎么完成的呢,请看代码:

#大局密钥装备,所以加密算法一致密钥
api:
encrypt:
key: d7b85c6e414dbcda
#此装备的公司钥信息为测试数据,不能直接运用,请自行从头生成公私钥
rsa:
publicKey: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcZlkHaSN0fw3CWGgzcuPeOKPdNKHdc2nR6KLXazhhzFhe78NqMrhsyNTf3651acS2lADK3CzASzH4T0bT+GnJ77joDOP+0SqubHKwAIv850lT0QxS+deuUHg2+uHYhdhIw5NCmZ0SkNalw8igP1yS+2TEIYan3lakPBvZISqRswIDAQAB
privateKey: MIICeAIBADANBgkqhkiG9w0BAQeFAcSCAmIwggJeAgEAAoGBAJxmWQdpI3R/DcJYaDNy4944o900od1zadHootdrOGHMWF7vw2oyuGzI1N/frmxoVLaUAMrcLMBLMfhPRtP4acnvuOgM4/7RKq5scrAAi/znSVPRDFL5165QeDb64diF2EjDk0KZnRKQ1qXDyKA/XJL7ZMQhhqfeVqQ8G9khKpGzAgMBAAECgYEAj+5AkGlZj6Q9bVUez/ozahaF9tSxAbNs9xg4hDbQNHByAyxzkhALWVGZVk3rnyiEjWG3OPlW1cBdxD5w2DIMZ6oeyNPA4nehYrf42duk6AI//vd3GsdJa6Dtf2has1R+0uFrq9MRhfRunAf0w6Z9zNbiPNSd9VzKjjSvcX7OTsECQQD20kekMToC6LZaZPr1p05TLUTzXHvTcCllSeXWLsjVyn0AAM山东移动E17FJRcL9VXQuSUK7PQ5Lf5+OpjrCRYsIvuZg9AkEAojdC6k3SqGnbtftLfGHMDn1fe0nTJmL05emwXgJvwToUBdytvgbTtqs0MsnuaO极彩在线app下载-前后端别离架构中的接口安全(上)xMIMrBtpbhS6JiB5Idb7GArwJAfKTkmP5jFWT/8dZdBgFfhJGv6FakEjrqLMSM1QT7VzvStFWtPNYDHC2b8jfyyAkGvpSZb4ljZxUwBbuh5QgM4QJBAJDrV7+lOP62W9APqdd8M2X6gbPON3JC09EW3jaObLKupTa7eQicZsX5249IMdLQ0A43tanez3XXo0ZqNhwT8wcCQQDUubpNLwgAwN2X7kW1btQtvZW47o9CbCv+zFKJYms5WLrVpotjkrCgPeuloDAjxeHNARX8ZTVDxls6KrjLH3lT

commons-codec
commons-codec


commons-io
commons-io
2.6

public class AesEncryptUtils {
private static final String KEY = "d7585fde114abcda";
private static final String ALGORITHMSTR = "AES/CBC/NoPadding"; public static String base64Encode(byte[] bytes) { return Base64.encodeBase64String(bytes);
} public static byte[] base64Decode(String base64Code) throws Exception { return Base64.decodeBase64(base64Code);
} public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES")); return cipher.doFinal(content.getBytes("utf-8"));
} public static String aesEncrypt(String content, String encryptKey) throws Exception { return base64Encode(aesEncryptToBytes(content, encryptKey));
} public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES")); byte[] decryptBytes = cipher.doFinal(encryptBytes); return new String(decryptBytes);
} public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception { return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
} public static void main(String[] args) throws Exception {
String content = "{name:\"lynn\",id:1}";
System.out.println("加密前:" + content);
String encrypt = aesEncrypt(content, KEY);
System.out.println(encrypt.length() + ":加密后:" + encrypt);
String decrypt = aesDecrypt("H9pGuDMV+iJoS8YSfJ2Vx0NYN7v7YR0tMm1ze5zp0WvNEFXQPM7K0k3IDUbYr5ZIckTkTHcIX5Va/cstIPrYEK3KjfCwtOG19l82u+x6soa9FzAtdL4EW5HAFMmpVJVyG3wz/XUysIRCwvoJ20ruEwk07RB3ojc1Vtns8t4kKZE=", "d7b85f6e214abcda");
System.out.println("解密后:" + decrypt);
}
}public class RSAUtils {
public static final String CHARSET = "UTF-8"; public static final String RSA_ALGORITHM = "RSA"; public static Map createKeys(int keySize){ //为RSA算法创立一个KeyPairGenerator目标
KeyPairGenerator kpg; try{
kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
}catch(NoSuchAlgorithmException e){ throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
} //初始化KeyPairGenerator目标,密钥长度
kpg.initialize(keySize); //生成密匙对
KeyPair keyPair = kpg.generateKeyPair(); //得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded()); //得到私钥
Key privateKey = keyPair.getPrivate();
String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
Map keyPairMap = new HashMap<>(2);
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr); return keyPairMap;
} /**
* 得到公钥
* @param publicKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { //经过X509编码的Key指令取得公钥目标
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec); return key;
} /**
* 得到私钥
* @param privateKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException { //经过PKCS#8编码的Key指令取得私钥目标
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec); return key;
} /**
* 公钥加密
* @param data
* @param publicKey
* @return
*/
public static String publicEncrypt(String data, RSAPublicKey publicKey){ try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey); return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
}catch(Exception e){ throw new RuntimeException("加密字符串[" + data + "]时遇到反常", e);
}
} /**
* 私钥解密
* @param data
* @param privateKey
* @return
*/
public static String privateDecrypt(String data, RSAPrivateKey privateKey){ try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey); return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
}catch(Exception e){ throw new RuntimeException("解密字符串[" + data + "]时遇到反常", e);
}
} /**
* 私钥加密
* @param data
* @param privateKey
* @return
*/
public static String privateEncrypt(String data, RSAPrivateKey privateKey){ try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey); return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
}catch(Exception e){ throw new RuntimeException("加密字符串[" + data + "]时遇到反常", e);
}
} /**
* 公钥解密
* @param data
* @param publicKey
* @return
*/
public static String publicDecrypt(String data, RSAPublicKey publicKey){ try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey); return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
}catch(Exception e){ throw new RuntimeException("解密字符串[" + data + "]时遇到反常", e);
}
} private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){ int maxBlock = 0; if(opmode == Cipher.DECRYPT_MODE){
maxBlock = keySize / 8;
}else{
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] buff; int i = 0; try{ while(datas.length > offSet){ if(datas.length-offSet > maxBlock){
buff = cipher.doFinal(datas, offSet, maxBlock);
}else{
buff = cipher.doFinal(datas, offSet, datas.length-offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
}catch(Exception e){ throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发作反常", e);
} byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out); return resultDatas;
} public static void main(String[] args) throws Exception{
Map keyMap = RSAUtils.createKeys(1024);
String publicKey = keyMap.get("publicKey");
String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJxmWQdpI3R/DcJYaDNy4944o900od1zadHootdrOGHMWF7vw2oyuGzI1N/frmxoVLaUAMrcLMBLMfhPRtP4acnvuOgM4/7RKq5scrAAi/znSVPRDFL5165QeDb64diF2EjDk0KZnRKQ1qXDyKA/XJL7ZMQhhqfeVqQ8G9khKpGzAgMBAAECgYEAj+5AkGlZj6Q9bVUez/ozahaF9tSxAbNs9xg4hDbQNHByAyxzkhALWVGZVk3rnyiEjWG3OPlW1cBdxD5w2DIMZ6oeyNPA4nehYrf42duk6AI//vd3GsdJa6Dtf2has1R+0uFrq9MRhfRunAf0w6Z9zNbiPNSd9VzKjjSvcX7OTsECQQD20kekMToC6LZaZPr1p05TLUTzXHvTcCllSeXWLsjVyn0AAME17FJRcL9VXQuSUK7PQ5Lf5+OpjrCRYsIvuZg9AkEAojdC6k3SqGnbtftLfGHMDn1fe0nTJmL05emwXgJvwToUBdytvgbTtqs0MsnuaOxMIMrBtpbhS6JiB5Idb7GArwJAfKTkmP5jFWT/8dZdBgFfhJGv6FYkEjrqLMSM1QT7VzvStFWtPNYDHC2b8jfyyAkGvpSZb4ljZxUwBbuh5QgM4QJBAJDrV7+lOP62W9APqdd8M2X6gbPON3JC09EW3jaObLKupTa7eQicZsX5249IMdLQ0A43tanez3XXo0ZqNhwT8wcCQQDUubpNLwgAwN2X7kW1btQtvZW47o9CbCv+zFKJYms5WLrVpotjkrCgPeuloDAjxeHNARX8ZTVDxls6KrjLH3lT";
System.out.println("公钥: \n\r" + publicKey);
System.out.println("私钥: \n\r" + privateKey);
System.out.println("公钥加密——私钥解密");
String str = "站在大明门前护卫的禁卫军,事前没有接到\n" + "有关的指令,但看到大批盛装的官员降临,也就\n" + "认为确系举办大典,因此未加问询。进大明门即\n" + "为皇城。文武百官看到端门午门之前气氛安静,\n" + "城楼上下也无朝会的痕迹,既无几案,站队点名\n" + "的御史和御前侍卫“大汉将军”也不见踪影,难免\n" + "心中推测,相互问询:所谓午朝是否讹传?";
System.out.println("\r明文:\r\n" + str);
System.out.println("\r明文巨细:\r\n" + str.getBytes().length);
String encodedData = RSAUtils.publicEncrypt(str, RSAUtils.getP极彩在线app下载-前后端别离架构中的接口安全(上)ublicKey(publicKey));
System.out.println("密文:\r\n" + encodedData);
String decodedData = RSAUtils.privateDecrypt("X4hHPa9NjPd5QJGPus+4+hWmOzbWg7oCJ1+Vc+7dHW81nEhkYnJpFyV5xcDkg70N2Mym+YAJ1PvYY9sQWf9/EkUE61TpUKBmDaGWLjEr3A1f9cKIelqLKLsJGdXEOr7Z55k4vYFvA7N3Vf5KQo3NrouvIT4wR+SjH4tDQ8tNh3JH8BvXLtXqGa2TCK2z1AzHNgYzcLCrqDasd7UDHRPZPiW4thktM/whjBn0tU9B/kKjAjLuYttKLEmy5nT7v7u16aZ6ehkk+kzvuCXF%2B3RsqraISDPbsTki2agJyqsycRx3w7CvKRyUbZhFaNcWigOwmcbZVoiom+ldh7Vh6HYqDA==", RSAUtils.getPrivateKey(privateKey));
System.out.println("解密后文字: \r\n" + decodedData);
}
}/**
* 私钥输入参数(其实便是客户端经过服务端回来的公钥加密后的客户端自己生成的公钥)
*/public class KeyRequest {
/**
* 客户端自己生成的加密后公钥
*/
@NotNull
private String clientEncryptPublicKey; public String getClientEncryptPublicKey() { return clientEncryptPublicKey;
} public void setClientEncryptPublicKey(String clientEncryptPublicKey) { this.clientEncryptPublicKey = clientEncryptPublicKey;
}
}/**
* RSA生成的公私钥输出参数
*/public class RSAResponse extends BaseResponse{
private String serverPublicKey; private String serverPrivateKey; public static class Builder{
private String serverPublicKey; private String serverPrivateKey; public Builder setServerPublicKey(String serverPublicKey){ this.serverPublicKey = serverPublicKey; return this;
} public Builder setServerPrivateKey(String serverPrivateKey){ this.serverPrivateKey = serverPrivateKey; return this;
} public RSAResponse build(){ return new RSAResponse(this);
}
} public static Builder options(){ return new Builder();
} public RSAResponse(Builder builder){ this.serverPrivateKey = builder.serverPrivateKey; this.serverPublicKey = builder.serverPublicKey;
} public String getServerPrivateKey() { return serverPrivateKey;
} public String getServerPublicKey() { return serverPublicKey;
}
}/**
* 私钥输出参数
*/public class KeyResponse extends BaseResponse{
/**
* 整个系一致切加密算法共用的密钥
*/
private String key; public static class Builder{
private String key; public Builder setKey(String key){ this.key = key; return this;
} public KeyResponse build(){ return new KeyResponse(this);
}
} public static Buil极彩在线app下载-前后端别离架构中的接口安全(上)der options(){ return new Builder();
} private KeyResponse(Builder builder){ this.key = builder.key;
} public String getKey() { return key;
}
}/**
* API传输加解密相关接口
*/public interface EncryptOpenService {
/**
* 生成RSA公私钥
* @return
*/
SingleResult getRSA(); /**
* 取得加解密用的密钥
* @param request
* @return
*/
SingleResult getKey(KeyRequest request) throws Exception;
}
@Servicepublic class EncryptOpenServiceImpl implements EncryptOpenService{
@Value("${rsa.publicKey}") private String publicKey; @Value("${rsa.privateKey}") private String privateKey; @Value("${api.encrypt.key}") private String key; @Override
public SingleResult getRSA() {
RSAResponse response = RSAResponse.options()
.setServerPublicKey(publicKey)
.build(); return SingleResult.buildSuccess(response);
} @Override
public SingleResult getKey(KeyRequest request)throws Exception {
String clientPublicKey = RSAUtils.privateDecrypt(request.getClientEncryptPublicKey(), RSAUtils.getPrivateKey(privateKey));
String encryptKey = RSAUtils.publicEncrypt(key,RSAUtils.getPublicKey(clientPublicKey));
KeyResponse response = KeyResponse.options()
.setKey(encryptKey)
.build(); return SingleResult.buildSuccess(response);
}
}
@RestController
@RequestMapping("open/encrypt")
public class EncryptController {
@Autowired
private EncryptOpenService encryptOpenService;
@RequestMapping(value = "getRSA",method = RequestMethod.POST) //@DisabledEncrypt
public SingleResult getRSA(){
return encryptOpenService.getRSA();
}
@RequestMapping(value = "getKey",method = RequestMethod.POST) //@DisabledEncrypt
public SingleResult getKey(@Valid @RequestBody KeyRequest request)throws Exception{
return encryptOpenService.getKey(request);
}
}

接口恳求的合法性校验

关于一些隐私接口(即有必要要登录才干调用的接口),咱们需求校验其合法性,即只要登录用户才干成功调用,详细思路如下:

1、调用登录或注册接口成功后,服务端会回来token(设置较短有用时刻)和refreshToken(设定较长有用时刻)

2、隐私接口每次恳求接口在恳求头带上token如header(“tok极彩在线app下载-前后端别离架构中的接口安全(上)en”,token),若服务端 回来403过错,则调用refreshToken接口获取新的token从头调用接口,若refreshToken接口持续回来403,则跳转到登录界面。

这种算法较为简略,这儿就不写出详细完成了。

因为篇幅问题,剩下方法下篇会持续介绍,敬请期待!

请关注微信公众号
微信二维码
不容错过
Powered By Z-BlogPHP