2024年最新微服务实战系列之API加密_api做微服务开发加密和哈希


#### 3、定义AOP


##### 3.1 返回体加密Advice(EncryptResponse)



> 
> `一句话总结`:通过将返回体(response)转换为String,实现数据加密。
> 
> 
> 



import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import cn.hutool.json.JSONUtil;

/**
* @description:加密
* @date 2024/01/06 14:02
*/
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice {

public EncryptResponse() {}

public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return returnType.hasMethodAnnotation(Encrypt.class);
}

@Override
public Object beforeBodyWrite(Object res, MethodParameter returnType,
		MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
		ServerHttpRequest request, ServerHttpResponse response) {
	try {
		String content =  JSONUtil.toJsonStr(JSONUtil.parseObj(res, false));
		//加密算法,自选,可以是AES,可以是RSA...
        String encryptResBody = AesEncryptUtils.encrypt(content, Constants.AESKEY);
        return encryptResBody;
    } catch (Exception e) {
        e.printStackTrace();
    }
	return res;	
}

}


##### 3.2 请求体解密Advice(DecryptRequest)



> 
> `一句话总结`:通过将请求体(request)转换为字节流,实现数据解密。
> 
> 
> 



import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

/**
* @description:解密
* @date 2024/01/06 14:35
*/
@ControllerAdvice
public class DecryptRequest extends RequestBodyAdviceAdapter {

public DecryptRequest() {}

public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
    return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
}

public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
    byte[] body = new byte[inputMessage.getBody().available()];
    inputMessage.getBody().read(body);
    try {
        //解密算法,自选,可以是AES,可以是RSA...
    	byte[] decrypt = AesEncryptUtils.decrypt(new String(body,Constants.UTF8),Constants.AESKEY).getBytes();
        final ByteArrayInputStream bais = new ByteArrayInputStream(decrypt);
        return new HttpInputMessage() {
            public InputStream getBody() throws IOException {
                return bais;
            }
            public HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }
        };
    } catch (Exception e) {
        e.printStackTrace();
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}

}


#### 4、使用注解


完成以上注解实现, 即可满足API的加密需求了。


如何使用?那不就简单了…直接在`Controller`的接口中使用注解即可,可参考:



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;

/**
* @description: API加密
* @date 2024/01/06 15:58
*/
@Slf4j
@RestController
@RequestMapping(“/api”)
public class TestController
{
@Encrypt
@Decrypt
@PostMapping(“/getData”)
public Object getData(@RequestBody String input)
{
// TODO
}
}


### 四、AES算法


本文使用的加密算法是基于AES完成,博主分享大家(已解决已知问题,比如长度不足128,支持分段),供参考:



import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* AES加解密
*/
public class AesEncryptUtils {
private static Logger log = LoggerFactory.getLogger(AesEncryptUtils.class);

private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
private static final String KEY = "1234567890abcdef";//可支持128位长度
private static final String AES = "AES";

/\*\*

* 解密算法
*/
public static String decrypt(String decryptStr, String decryptKey) {
try {

        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(decryptKey.getBytes());

        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT\_MODE, new SecretKeySpec(secretKey.getEncoded(), AES));

        //采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(decryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }catch (Exception e){
        log.error("decryptNew({} , {})解密异常", decryptStr, decryptKey, e);
    }

    return null;
}

/\*\*

* 加密算法
*/
public static String encrypt(String encryptStr, String encryptKey) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(AES);

        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(encryptKey.getBytes());

        kgen.init(128,secureRandom);
        SecretKey secretKey = kgen.generateKey();

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT\_MODE, new SecretKeySpec(secretKey.getEncoded(), AES));
        byte[] b = cipher.doFinal(encryptStr.getBytes("utf-8"));
        //采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);
    }catch (Exception e){
        log.error("encryptNew({} , {})加密异常", encryptStr, encryptKey, e);
    }

    return null;
}

public static void main (String[] args) throws Exception{
	String content = "今天是2024年1月6日";
	
	String encrypt1 = encrypt(content, KEY);
    System.out.println("加密后:" + encrypt1);

    String decrypt1 = decrypt(encrypt1, KEY);
    System.out.println("解密后:" + decrypt1);
}

}




---


### 结语


本文通过对API安全问题进行粗浅探讨,并从常用的数据加密措施入手,提供相关操作规范和指导,希望各位盆友有所收获。如需进一步了解,可留言,欢迎大家订阅与指正!


2024首篇博文,正式发布喽!!!




---


##### 历史回顾




---


* [微服务实战系列之Dubbo(下)]( )
* [微服务实战系列之Dubbo(上)]( )
* [微服务实战系列之ZooKeeper(实践篇)]( )
* [微服务实战系列之ZooKeeper(下)]( )
* [微服务实战系列之ZooKeeper(中)]( )
* [微服务实战系列之ZooKeeper(上)]( )
* [微服务实战系列之MQ]( )
* [微服务实战系列之通信]( )
* [微服务实战系列之J2Cache]( )
* [微服务实战系列之Cache(技巧篇)]( )
* [微服务实战系列之MemCache]( )
* [微服务实战系列之EhCache]( )


### 如何自学黑客&网络安全


#### 黑客零基础入门学习路线&规划


**初级黑客**  
 **1、网络安全理论知识(2天)**  
 ①了解行业相关背景,前景,确定发展方向。  
 ②学习网络安全相关法律法规。  
 ③网络安全运营的概念。  
 ④等保简介、等保规定、流程和规范。(非常重要)


**2、渗透测试基础(一周)**  
 ①渗透测试的流程、分类、标准  
 ②信息收集技术:主动/被动信息搜集、Nmap工具、Google Hacking  
 ③漏洞扫描、漏洞利用、原理,利用方法、工具(MSF)、绕过IDS和反病毒侦察  
 ④主机攻防演练:MS17-010、MS08-067、MS10-046、MS12-20等


**3、操作系统基础(一周)**  
 ①Windows系统常见功能和命令  
 ②Kali Linux系统常见功能和命令  
 ③操作系统安全(系统入侵排查/系统加固基础)


**4、计算机网络基础(一周)**  
 ①计算机网络基础、协议和架构  
 ②网络通信原理、OSI模型、数据转发流程  
 ③常见协议解析(HTTP、TCP/IP、ARP等)  
 ④网络攻击技术与网络安全防御技术  
 ⑤Web漏洞原理与防御:主动/被动攻击、DDOS攻击、CVE漏洞复现


**5、数据库基础操作(2天)**  
 ①数据库基础  
 ②SQL语言基础  
 ③数据库安全加固


**6、Web渗透(1周)**  
 ①HTML、CSS和JavaScript简介  
 ②OWASP Top10  
 ③Web漏洞扫描工具  
 ④Web渗透工具:Nmap、BurpSuite、SQLMap、其他(菜刀、漏扫等)  
 恭喜你,如果学到这里,你基本可以从事一份网络安全相关的工作,比如渗透测试、Web 渗透、安全服务、安全分析等岗位;如果等保模块学的好,还可以从事等保工程师。薪资区间6k-15k


到此为止,大概1个月的时间。你已经成为了一名“脚本小子”。那么你还想往下探索吗?


如果你想要入坑黑客&网络安全,笔者给大家准备了一份:282G全网最全的网络安全资料包评论区留言即可领取!


**7、脚本编程(初级/中级/高级)**  
 在网络安全领域。是否具备编程能力是“脚本小子”和真正黑客的本质区别。在实际的渗透测试过程中,面对复杂多变的网络环境,当常用工具不能满足实际需求的时候,往往需要对现有工具进行扩展,或者编写符合我们要求的工具、自动化脚本,这个时候就需要具备一定的编程能力。在分秒必争的CTF竞赛中,想要高效地使用自制的脚本工具来实现各种目的,更是需要拥有编程能力.


如果你零基础入门,笔者建议选择脚本语言Python/PHP/Go/Java中的一种,对常用库进行编程学习;搭建开发环境和选择IDE,PHP环境推荐Wamp和XAMPP, IDE强烈推荐Sublime;·Python编程学习,学习内容包含:语法、正则、文件、 网络、多线程等常用库,推荐《Python核心编程》,不要看完;·用Python编写漏洞的exp,然后写一个简单的网络爬虫;·PHP基本语法学习并书写一个简单的博客系统;熟悉MVC架构,并试着学习一个PHP框架或者Python框架 (可选);·了解Bootstrap的布局或者CSS。

**8、超级黑客**  
 这部分内容对零基础的同学来说还比较遥远,就不展开细说了,附上学习路线。  
 ![img](https://img-blog.csdnimg.cn/img_convert/3fd39c2ba8ec22649979f245f4221608.webp?x-oss-process=image/format,png)


#### 网络安全工程师企业级学习路线


![img](https://img-blog.csdnimg.cn/img_convert/931ac5ac21a22d230645ccf767358997.webp?x-oss-process=image/format,png)  
 如图片过大被平台压缩导致看不清的话,评论区点赞和评论区留言获取吧。我都会回复的


视频配套资料&国内外网安书籍、文档&工具


当然除了有配套的视频,同时也为大家整理了各种文档和书籍资料&工具,并且已经帮大家分好类了。

![img](https://img-blog.csdnimg.cn/img_convert/153b2778a3fe5198265bed9635d63469.webp?x-oss-process=image/format,png)  
 一些笔者自己买的、其他平台白嫖不到的视频教程。  
 ![img](https://img-blog.csdnimg.cn/img_convert/32eb4b22aa740233c5198d3c161b37e8.webp?x-oss-process=image/format,png)



**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化资料的朋友,可以点击这里获取](https://bbs.csdn.net/topics/618540462)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值