aes加密字符串c++_springboot2.2.X手冊:防抓包?快速實現API接口數據加密

溪云閣:專注編程教學,架構,JAVA,Python,微服務,機器學習等,歡迎關注

上一篇:springboot2.2.X手冊:redis的7種類型100個方法全解析

有沒有遇到這樣子的接口,放到互聯網上面去,誰都可以調用,誰都可以訪問,完全就是公開的,這樣子的接口,如果只是普通的數據,其實可以考慮,只是可以考慮,但是,一般情況下,我們是不允許這樣子做的。

975099973736543e576bc5b18362da03.png

接口安全防什么

1、防止惡意調用攻擊

2、防止篡改信息攻擊

3、防攔截攻擊,數據被截取后進行修改后重新放回去

4、防止數據泄漏攻擊

edd5a863f36a0e644308de54ef9789d2.png

什么是抓包

抓包(packet capture)就是將網絡傳輸發送與接收的數據包進行截獲、重發、編輯、轉存等操作,也用來檢查網絡安全。抓包也經常被用來進行數據截取等。

這是百度百科給我們的解釋,當我們一些放到互聯網上的數據,直接采用明文的話,就很容易被抓包,然后進行修改或者被惡意植入木馬,這是比較惡心的行為,今天我們就來研究一下怎么樣對接口進行數據加密。

db2032479a0eaba2b4326ef170495176.png

POM文件

         org.springframework.boot            spring-boot-starter-web        org.springframework.boot            spring-boot-autoconfigure        com.bootsmodule-boots-api2.0.0.RELEASE

編寫加密解密工具類

/** * All rights Reserved, Designed By 林溪 * Copyright:    Copyright(C) 2016-2020 * Company       溪云閣 . */package com.module.boots.api.de.utils;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import org.apache.tomcat.util.codec.binary.Base64;import com.module.boots.exception.CommonRuntimeException;/** * AES加密解密 * @author:溪云閣 * @date:2020年6月4日 */public class AesUtils {    private static final String KEY_ALGORITHM = "AES";    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// 默認的加密算法    /**     * AES 加密操作     * @author 溪云閣     * @param content 待加密內容     * @param password 加密密碼     * @return String 返回Base64轉碼后的加密數據     */    public static String encrypt(String content, String password) {        try {            // 創建密碼器            final Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);            // 設置為UTF-8編碼            final byte[] byteContent = content.getBytes("utf-8");            // 初始化為加密模式的密碼器            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));            // 加密            final byte[] result = cipher.doFinal(byteContent);            // 通過Base64轉碼返回            return Base64.encodeBase64String(result);        }        catch (final Exception ex) {            throw new CommonRuntimeException(ex.fillInStackTrace());        }    }    /**     * AES 解密操作     * @author 溪云閣     * @param content     * @param password     * @return String     */    public static String decrypt(String content, String password) {        try {            // 實例化            final Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);            // 使用密鑰初始化,設置為解密模式            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));            // 執行操作            final byte[] result = cipher.doFinal(Base64.decodeBase64(content));            // 采用UTF-8編碼轉化為字符串            return new String(result, "utf-8");        }        catch (final Exception ex) {            throw new CommonRuntimeException(ex.fillInStackTrace());        }    }    /**     * 生成加密秘鑰     * @author 溪云閣     * @param password 加密的密碼     * @return SecretKeySpec     */    private static SecretKeySpec getSecretKey(final String password) {        // 返回生成指定算法密鑰生成器的 KeyGenerator 對象        KeyGenerator kg = null;        try {            kg = KeyGenerator.getInstance(KEY_ALGORITHM);            // AES 要求密鑰長度為 128            kg.init(128, new SecureRandom(password.getBytes()));            // 生成一個密鑰            final SecretKey secretKey = kg.generateKey();            // 轉換為AES專用密鑰            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);        }        catch (final NoSuchAlgorithmException ex) {            throw new CommonRuntimeException(ex.fillInStackTrace());        }    }    public static void main(String[] args) {        final String str = "V9JofCHn02eyXRiDb1VuseRSuOgEQftROwudMPWwMAO2Wk5K7aYZ4Vtm6xiTn5i5";        System.out.println(decrypt(str, "xy934yrn9342u0ry4br8cn-9u2"));    }}

編寫加密注解

/** * All rights Reserved, Designed By 林溪 * Copyright:    Copyright(C) 2016-2020 * Company       溪云閣 . */package com.module.boots.api.de;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * 返回對body加密,針對類跟方法 * @author:溪云閣 * @date:2020年6月4日 */@Target({ ElementType.METHOD, ElementType.TYPE })@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ResponseEncrypt {    /**     * 返回對body加密,默認是true     * @author 溪云閣     * @return boolean     */    boolean value() default true;}

編寫加密判斷類

/** * All rights Reserved, Designed By 林溪 * Copyright:    Copyright(C) 2016-2020 * Company       溪云閣 . */package com.module.boots.api.de;import org.springframework.core.MethodParameter;/** * 是否需要加密解密 * @author:溪云閣 * @date:2020年6月4日 */public class NeedDe {    /**     * 判斷是否需要加密     * @author 溪云閣     * @param returnType     * @return boolean     */    public static boolean needEncrypt(MethodParameter returnType) {        boolean encrypt = false;        // 獲取類上的注解        final boolean classPresentAnno = returnType.getContainingClass().isAnnotationPresent(ResponseEncrypt.class);        // 獲取方法上的注解        final boolean methodPresentAnno = returnType.getMethod().isAnnotationPresent(ResponseEncrypt.class);        if (classPresentAnno) {            // 類上標注的是否需要加密            encrypt = returnType.getContainingClass().getAnnotation(ResponseEncrypt.class).value();            // 類不加密,所有都不加密            if (!encrypt) {                return false;            }        }        if (methodPresentAnno) {            // 方法上標注的是否需要加密            encrypt = returnType.getMethod().getAnnotation(ResponseEncrypt.class).value();        }        return encrypt;    }}

編寫加密攔截

/** * All rights Reserved, Designed By 林溪 * Copyright:    Copyright(C) 2016-2020 * Company       溪云閣 . */package com.module.boots.api.de;import org.springframework.beans.factory.annotation.Value;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 com.module.boots.api.de.utils.AesUtils;import com.module.boots.api.message.ResponseMsg;/** * 對接口數據進行加密 * @author:溪云閣 * @date:2020年6月4日 */@ControllerAdvicepublic class ResponseEncryptAdvice implements ResponseBodyAdvice {    @Value("${module.boots.response.aes.key}")    private String key;    @Override    public boolean supports(MethodParameter returnType, Class extends HttpMessageConverter>> converterType) {        return true;    }    /**     * 在寫入之前更改body的值     * @author 溪云閣     * @param body     * @param returnType     * @param selectedContentType     * @param selectedConverterType     * @param request     * @param response     * @return     * @return     */    @SuppressWarnings({ "unchecked", "rawtypes" })    @Override    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,            Class extends HttpMessageConverter>> selectedConverterType, ServerHttpRequest request,            ServerHttpResponse response) {        // 判斷是否需要加密        final boolean encrypt = NeedDe.needEncrypt(returnType);        if (!encrypt) {            return body;        } else {            // 如果body是屬于ResponseMsg類型,只需要對data里面的數據進行加密即可            if (body instanceof ResponseMsg) {                final ResponseMsg responseMsg = (ResponseMsg) body;                final Object data = responseMsg.getData();                if (data == null) {                    return body;                } else {                    responseMsg.setData(AesUtils.encrypt(data.toString(), key));                    return responseMsg;                }            } else {                return body;            }        }    }}

加入密鑰

# aes的密鑰module.boots.response.aes.key: xy934yrn9342u0ry4br8cn-9u2

編寫加密解密接口

/** * All rights Reserved, Designed By 林溪 * Copyright:    Copyright(C) 2016-2020 * Company       溪云閣 . */package com.boots.api.de.view.de.view;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.boots.api.de.view.de.vo.GetEncryptVO;import com.module.boots.api.de.ResponseEncrypt;import com.module.boots.api.de.utils.AesUtils;import com.module.boots.api.message.ResponseMsg;import com.module.boots.api.utils.MsgUtils;import com.module.boots.exception.CommonRuntimeException;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import lombok.SneakyThrows;/** * 加密數據接口 * @author:溪云閣 * @date:2020年6月4日 */@SuppressWarnings("deprecation")@Api(tags = { "web服務:加密數據接口" })@RestController@RequestMapping("view/deView")public class DeView {    @Value("${module.boots.response.aes.key}")    private String key;    /**     * 獲取加密數據     * @author 溪云閣     * @return ResponseMsg     */    @ApiOperation(value = "獲取加密數據")    @GetMapping(value = "/getEncrypt", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)    @SneakyThrows(CommonRuntimeException.class)    @ResponseEncrypt    public ResponseMsg getEncrypt() {        final GetEncryptVO vo = new GetEncryptVO();        vo.setId("b037123c");        vo.setUserName("xnwqr98urx");        return MsgUtils.buildSuccessMsg(vo);    }    /**     * 獲取解密數據     * @author 溪云閣     * @return ResponseMsg     */    @ApiOperation(value = "獲取解密數據")    @GetMapping(value = "/getDecrypt", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)    @SneakyThrows(CommonRuntimeException.class)    public ResponseMsg getDecrypt(@RequestParam(value = "content") String content) {        final String str = AesUtils.decrypt(content, key);        return MsgUtils.buildSuccessMsg(str);    }}

測試

6a2e30724808ef72f20a36e8e8f6fa13.png
9c205a524b8e116e3585b9e0c8260ff0.png

從實驗的結果上看,我們在獲取數據的時候,直接對data里面的數據進行了加密,這種加密方式只有我們自己可以破解,放到網上去,即使只有密鑰,也破解不了。

這里只做接口的數據的加密,生產中經常需要加入token,時間戳等進行驗證,各位同學自行拓展即可。

--END--

作者:@溪云閣

原創作品,抄襲必究,轉載注明出處

如需要源碼,轉發,關注后私信我

部分圖片或代碼來源網絡,如侵權請聯系刪除,謝謝!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/529088.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/529088.shtml
英文地址,請注明出處:http://en.pswp.cn/news/529088.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

鴻蒙系統打造完備終端,搭載鴻蒙系統的手機很快推出,華為生態更加完善

2019年的8月9日,在華為開發者大會上華為向大家正式的發布了一款操作系統——鴻蒙系統。這個系統備受大家的關注,鴻蒙2.0的發布也在時刻期待中。因為在目前的操作系統中,華為的鴻蒙操作系統是僅次于安卓、ios的存在,而今日&#xf…

curl socket 訪問_使用Curl、socket、file_get_contents三種方法POST提交數據 | 學步園

# <?php # /**# * Socket版本# * 使用方法&#xff1a;# * $post_string "appsocket&versionbeta";# * request_by_socket(facebook.cn,/restServer.php,$post_string);# */# function request_by_socket($remote_server,$remote_path,$post_string,$port …

html 標簽 r語言,從R中的字符串中刪除html標簽

我正在嘗試將網頁源代碼讀入R并將其作為字符串處理。我正在嘗試刪除段落并從段落文本中刪除html標簽。我遇到了以下問題&#xff1a;我嘗試實現一個功能來刪除html標簽&#xff1a;cleanFunfunction(fullStr){#find location of tags and citationstagLoccbind(str_locate_all(…

python給圖片加半透明水印_Python 批量加水印就這么簡單!

工作的時候&#xff0c;尤其是自媒體&#xff0c;我們必備水印添加工具以保護我們的知識產權,網上有許多的在線/下載的水印添加工具&#xff0c;但他們或多或少都存在以下問題&#xff1a; 在線工具需要將圖片上傳到對方服務器&#xff0c;信息不安全。 很多工具不具備批量處理…

html 選中狀態,html默認選中狀態

html中標簽用法解析及如何設置selec標簽定義和用法 select 元素可創建單選或多選菜單。當提交表單時&#xff0c;瀏覽器會提交選定的項目&#xff0c;或者收集用逗號分隔的多個選項&#xff0c;將其合成一個單獨的參數列表&#xff0c;并且在將 表單數據提交給服務器時包括 nam…

nemesis什么車_nemesis是什么意思_nemesis的翻譯_音標_讀音_用法_例句_愛詞霸在線詞典...

全部報應Was he aiming at Bryant, his old nemesis and a favorite target in the past?他是不是暗指科比, 一直的“競爭對手”和過去最中意的目標?期刊摘選After the defeat of their old arch nemesis, the Turtle have grown apart as a family.在擊敗舊時強敵后, 忍者神…

wxpython制作表格界面_[Python] wxPython 菜單欄控件學習總結(原創)

1、總結 1、大體創建過程 1、創建一個 菜單欄 : menuBar wx.MenuBar()相當于這個白色地方&#xff0c;沒有File這個菜單 2、創建 菜單 : fileMenu wx.Menu()這兩個不是直接“用的”&#xff0c;叫菜單。既用來分類其他 菜單項 的文件夾樣 3、創建 菜單項 : newItem wx.MenuI…

android 8三星note8,信息太多很煩瑣?告訴你三星Note8有妙招

不知從何時開始&#xff0c;我們眼前的信息變得豐富而繁雜。簡潔的新聞無需經過報紙過濾&#xff0c;發生數分鐘已經城皆知。預測晴雨也無需依靠天氣先生&#xff0c;點亮手機即可洞悉風雨。生活在信息時代的我們僅用幾英寸的窗口觀察世界&#xff0c;信息的洪流難免會遮蔽眼前…

realloc函_realloc(重新分配內存空間的函數)

在頭文件中定義void * realloc(void * ptr&#xff0c;size_t new_size);重新分配給定的內存區域。它必須預先分配malloc()&#xff0c;calloc()或realloc()尚未釋放與free或呼叫realloc。否則&#xff0c;結果是不確定的。重新分配由以下兩者之一完成&#xff1a;a)ptr如有可能…

python做excel表格教程視頻_基于Python實現excel表格讀寫

首先安裝對應的xlrd和xlwt 打開cmd命令窗口輸入pip install xlrd和pip install xlwt就可以安裝。之后輸入pip list檢查是否成功配置&#xff1a;xlrd操作# 接下來就是常用的語法操作&#xff1a; excel_data xlrd.open_workbook(文件路徑)#得到對應的工作表 sheet excel_data…

虛無鴻蒙哪個厲害,【圖說鴻蒙】鴻蒙設定之七柱神(五)

原標題&#xff1a;【圖說鴻蒙】鴻蒙設定之七柱神(五)七柱神玄冥神飛來流去本無心&#xff0c;無空無我混天塵。幻作人形深簡出&#xff0c;不是老嫗是海神。玄冥神 虛無荒海司掌海洋、流動之力 神威之色為藍執掌海洋、流動之力的神&#xff0c;是神道“熵”的最高掌控者&#…

java lambda 排序_Java8特性:Lambda表達式之概念篇

Java自誕生已經有十幾個年頭了&#xff0c;目前也已經發布了第十三個大版本&#xff0c;其中Java8是常用的版本中最新的一個版本。而Java8最大的特性就是&#xff1a;Lambda表達式、函數式接口和Stream流。本篇我只介紹Lamda表達式的概念以及簡單使用&#xff0c;至于別的我打算…

jq獲取表格里的checkbox_Python抓取網頁表格(一)

Python有很多包可以抓取數據&#xff0c;如selenium、requests、scrapy、pandas&#xff0c;每個包都有其適用性&#xff0c;個人認為在抓取數據時&#xff0c;代碼簡潔性和數據獲取的準確性是需要考慮的因素&#xff0c;時間快慢倒不用太在意&#xff0c;畢竟用python抓數據本…

html一個空格多少像素,一個空格占幾個字符?

一個空格通常占2個字符&#xff0c;但有些特殊情況占用3個字符。在程序中&#xff0c;空格占用的字符數取決于程序使用的字符集&#xff0c;如&#xff1a;1、使用多字節字符集時&#xff0c;半角空格占用1個字節&#xff0c;全角空格占用2個字節。2、使用Unicode字符集時&…

各種摳圖動態圖片_不用手。自動、智能摳圖,圖片去背景

BgEraser 是一款基于 AI 的自動、智能圖片去背景工具&#xff0c;無需勾選可用、可刪除區域&#xff0c;上傳圖片&#xff0c;立即下載即扣圖完成的圖片。AppinnBgEraser 真是懶人的福音。在此之前&#xff0c;比如很好用的在線去背景服務 remove.bg&#xff0c;是需要用戶手動…

html用dom顯示xml,html DOM文件引用一個XML文件將不會在瀏覽器中打印

我完全不熟悉這一點&#xff0c;我正在上課&#xff0c;現在變成了一個令人頭疼的問題。我有這個HTML DOM文件&#xff0c;它引用了一個XML文件&#xff0c;我需要在瀏覽器中顯示在屏幕上。它應該只打印標題&#xff0c;標題&#xff0c;第一個&#xff0c;最后一個&#xff0c…

bigdecimal 保留兩位小數_Python的保留小數及對齊

Python的保留小數&#xff1a;方法1&#xff1a;用round函數(有坑)。median 12.3004886print(round(median, 2)) # 保留兩位小數print(round(median, 3)) # 保留三位小數print(round(median, 4)) # 保留四位小數運行結果&#xff1a;12.312.312.3005可以看出Python中的r…

分布式光伏補貼_四川:2020年起工商業分布式光伏已無補貼

來源&#xff1a;四川省發改委日前&#xff0c;四川省發改委發布《四川省分布式光伏建設管理相關政策》&#xff0c;對該省分布式光伏發電項目定義、分類、備案程序、需要國補的項目相關政策進行了梳理。值得注意的是&#xff0c;文件明確&#xff0c;自2020年起&#xff0c;四…

用計算機玩游戲最簡單的方法,如何制作電腦簡易命令小游戲

滿意答案sylvia10172019.01.20采納率&#xff1a;48% 等級&#xff1a;7已幫助&#xff1a;460人簡單的Dos小游戲開始學習java&#xff0c;這周只簡單的學習了C的基本語法&#xff1a;輸入輸出&#xff0c;判斷循環&#xff0c;因此用這些東西在java上瞎寫了一個DOS小游戲。…

pandas filter_數據分析之Pandas操作(2)

接著數據分析之Pandas操作(1)的介紹&#xff0c;本次介紹在實際應用場景中幾個常用的函數。還是以titanic生存數據為例&#xff0c;本次需要導入pandas 、numpy 、scipy三個工具包。import pandas as pdimport numpy as npfrom scipy.stats import zscoretrain_data pd.read_c…