spring boot集成RSA加密數(shù)據(jù)傳輸

最近看有小伙伴在弄項目使用密文傳輸數(shù)據(jù)狞甚,然后我看了下工秩,集成這個大佬的依賴不錯黔衡,但是我發(fā)現(xiàn)他的注解不支持加在類上,我進(jìn)行了一點改動后完美支持忌锯。
項目demo地址 https://github.com/songshijun1995/spring-boot-RSA
大致說下不引入依賴凭疮,直接集成的步驟。

  1. 配置yml文件膛腐,公鑰和密鑰可以用其他軟件生成
rsa:
  encrypt:
    open: true # 是否開啟加密 true  or  false
    showLog: true # 是否打印加解密log true  or  false
    # RSA公鑰 軟件生成
    publicKey: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiquj4HR5VBtSJiKTyr18/vLaO5fJb6L/BrawFR4u+QCP3SF6SEd4pwp5Ev2R5pS34YGU00XFCejPgDfsSnRITanvv5a5wnNLFJMaz7ACxCrZjmW3z+ZppR/I19mJsaTOOopChUMJNBdvxUO13suwYad1Nhk5fmAJn0xQJgeWR/QIDAQAB
    # RSA私鑰 軟件生成
    privateKey: MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKKq6PgdHlUG1ImIpPKvXz+8to7l8lvov8GtrAVHi75AI/dIXpIR3inCnkS/ZHmlLfhgZTTRcUJ6M+AN+xKdEhNqe+/lrnCc0sUkxrPsALEKtmOZbfP5mmlH8jX2YmxpM46ikKFQwk0F2/FQ7Xey7Bhp3U2GTl+YAmfTFAmB5ZH9AgMBAAECgYANiipQFKRksWfZds08AgrslDmh1VQCAHKNnXYXDmh8Unxr5dMxV1llonRoBoJHec9EwElMRy6lOOS+fotqdjZ90yTGTl5wPLX7Yan+OfeOJCkDdPhIurcPPi0RYXKSRags/SX3mvkhauxGIUY0xPDJJDJ/Kaby7HrT9PQELSbV5QJBAN3zio37hJxH5G7T2WMNbxA5sB4Ey5rOc+f7c5fARFs9QC2vbIyHP73pR9igZ4Pm8OiMcuWLrK0kvZfuCuFruBcCQQC7ny61wekt6bfCCfK0mtZt+SEEINqDsXICIyzgEShfURWoIPKlUQseqhtLg7vkPErkBoA8I3y9ozejwV8zIT8LAkEAhAaCvMKIt43sTCCoh0tObZBjOvgPRR7Zw3zH3dT41G0y5/oZz94EBKvnmOyRptyRIUOqdPEI3lWkkeN/hWfWMQJBAKOXVUwHqsBss9vNfsD47RTwj1ghKUaAlu7EKuGoNDJ/6ckyCUAZ3P88xRXf5BlKdOZDwNYu/xn+0YnIFrDnQScCQFobGRWnckBrm/GZ59/9vl5H1Z2MSbuDHgJBuxe6cq5RUhxFMW/KJ4hgfeiwp7xfpt162yMGlcqPNHyCTf6bVnA=
  1. 新建兩個工具類
package com.rsa.util;

import org.apache.commons.codec.binary.Base64;

public class Base64Util {
    public Base64Util() {
    }

    public static byte[] decode(String base64) throws Exception {
        return Base64.decodeBase64(base64);
    }

    public static String encode(byte[] bytes) throws Exception {
        return new String(Base64.encodeBase64(bytes));
    }
}
package com.rsa.util;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {
    public static final String KEY_ALGORITHM = "RSA";
    private static final int MAX_ENCRYPT_BLOCK = 117;
    private static final int MAX_DECRYPT_BLOCK = 256;

    public RSAUtil() {
    }

    public static byte[] encrypt(byte[] data, String publicKey) throws Exception {
        byte[] keyBytes = Base64Util.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對數(shù)據(jù)分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }

        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    public static byte[] decrypt(byte[] text, String privateKey) throws Exception {
        byte[] keyBytes = Base64Util.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = text.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對數(shù)據(jù)分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(text, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(text, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }

        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }
}
  1. 新建SecretKeyConfig配置文件睛约,加載yml里的配置
package com.rsa.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "rsa.encrypt")
public class SecretKeyConfig {
    private String privateKey;
    private String publicKey;
    private String charset = "UTF-8";
    private boolean open = true;
    private boolean showLog = false;
}
  1. 添加三個注解,EnableSecurity哲身、Decrypt辩涝、Encrypt
package com.rsa.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.rsa.advice.EncryptRequestBodyAdvice;
import com.rsa.advice.EncryptResponseBodyAdvice;
import com.rsa.config.SecretKeyConfig;
import org.springframework.context.annotation.Import;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Import({SecretKeyConfig.class, EncryptResponseBodyAdvice.class, EncryptRequestBodyAdvice.class})
public @interface EnableSecurity {
}

package com.rsa.annotation;

import java.lang.annotation.*;

//加密注解
@Target({ElementType.TYPE,ElementType.METHOD}) // 可以作用在類上和方法上
@Retention(RetentionPolicy.RUNTIME) // 運行時起作用
@Documented
public @interface Encrypt {
}

package com.rsa.annotation;

import java.lang.annotation.*;

//解密注解
@Target({ElementType.TYPE,ElementType.METHOD}) // 可以作用在類上和方法上
@Retention(RetentionPolicy.RUNTIME) // 運行時起作用
@Documented
public @interface Decrypt {
}
  1. 新建DecryptHttpInputMessage類
package com.rsa.advice;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import com.rsa.util.Base64Util;
import com.rsa.util.RSAUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

public class DecryptHttpInputMessage implements HttpInputMessage {
    private final HttpHeaders headers;
    private final InputStream body;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset, boolean showLog) throws Exception {
        if (StringUtils.isEmpty(privateKey)) {
            throw new IllegalArgumentException("privateKey is null");
        } else {
            this.headers = inputMessage.getHeaders();
            String content = (String)(new BufferedReader(new InputStreamReader(inputMessage.getBody()))).lines().collect(Collectors.joining(System.lineSeparator()));
            String decryptBody;
            Logger log = LoggerFactory.getLogger(this.getClass());
            if (content.startsWith("{")) {
                log.info("Unencrypted without decryption:{}", content);
                decryptBody = content;
            } else {
                StringBuilder json = new StringBuilder();
                content = content.replaceAll(" ", "+");
                if (!StringUtils.isEmpty(content)) {
                    String[] contents = content.split("\\|");
                    String[] var9 = contents;
                    int var10 = contents.length;

                    for(int var11 = 0; var11 < var10; ++var11) {
                        String value = var9[var11];
                        value = new String(RSAUtil.decrypt(Base64Util.decode(value), privateKey), charset);
                        json.append(value);
                    }
                }

                decryptBody = json.toString();
                if (showLog) {
                    log.info("Encrypted data received:{},After decryption:{}", content, decryptBody);
                }
            }

            this.body = new ByteArrayInputStream(decryptBody.getBytes());
        }
    }

    public InputStream getBody() {
        return this.body;
    }

    public HttpHeaders getHeaders() {
        return this.headers;
    }
}
  1. 新建EncryptRequestBodyAdvice類
package com.rsa.advice;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Objects;

import com.rsa.annotation.Decrypt;
import com.rsa.annotation.Encrypt;
import com.rsa.config.SecretKeyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
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.RequestBodyAdvice;

@ControllerAdvice
public class EncryptRequestBodyAdvice implements RequestBodyAdvice {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private boolean encrypt;
    @Autowired
    private SecretKeyConfig secretKeyConfig;

    public EncryptRequestBodyAdvice() {
    }

    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        Annotation[] annotations = methodParameter.getDeclaringClass().getAnnotations();
        if (annotations.length > 0 && this.secretKeyConfig.isOpen()) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Encrypt) {
                    return this.encrypt = true;
                }
            }
        }

       return this.encrypt = Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(Decrypt.class) && this.secretKeyConfig.isOpen();
    }

    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (this.encrypt) {
            try {
                return new DecryptHttpInputMessage(inputMessage, this.secretKeyConfig.getPrivateKey(), this.secretKeyConfig.getCharset(), this.secretKeyConfig.isShowLog());
            } catch (Exception var6) {
                this.log.error("Decryption failed", var6);
            }
        }

        return inputMessage;
    }

    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
  1. 新建EncryptResponseBodyAdvice類
package com.rsa.advice;

import com.alibaba.fastjson.JSON;
import com.rsa.annotation.Encrypt;
import com.rsa.config.SecretKeyConfig;
import com.rsa.util.Base64Util;
import com.rsa.util.RSAUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;
import java.util.Objects;

@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private static final ThreadLocal<Boolean> encryptLocal = new ThreadLocal<>();
    private boolean encrypt;
    @Autowired
    private SecretKeyConfig secretKeyConfig;

    public EncryptResponseBodyAdvice() {
    }

    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Annotation[] annotations = returnType.getDeclaringClass().getAnnotations();
        if (annotations.length > 0 && this.secretKeyConfig.isOpen()) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Encrypt) {
                    return this.encrypt = true;
                }
            }
        }
        return this.encrypt = Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(Encrypt.class) && this.secretKeyConfig.isOpen();
    }

    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Boolean status = encryptLocal.get();
        if (null != status && !status) {
            encryptLocal.remove();
        } else {
            if (this.encrypt) {
                String publicKey = this.secretKeyConfig.getPublicKey();

                try {
                    String content = JSON.toJSONString(body);
                    if (!StringUtils.hasText(publicKey)) {
                        throw new NullPointerException("Please configure rsa.encrypt.publicKey parameter!");
                    }

                    byte[] data = content.getBytes();
                    byte[] encodedData = RSAUtil.encrypt(data, publicKey);
                    String result = Base64Util.encode(encodedData);
                    if (this.secretKeyConfig.isShowLog()) {
                        this.log.info("Pre-encrypted data:{},After encryption:{}", content, result);
                    }

                    return result;
                } catch (Exception var13) {
                    this.log.error("Encrypted data exception", var13);
                }
            }

        }
        return body;
    }
}
  1. 在啟動類上加@EnableSecurity注解
  2. 新建測試類
package com.rsa.controller;

import com.alibaba.fastjson.JSON;
import com.rsa.annotation.Decrypt;
import com.rsa.annotation.Encrypt;
import com.rsa.entities.TestBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
//@Encrypt
//@Decrypt
@RestController
public class TestController {

    @Encrypt
    @GetMapping("/encryption")
    public TestBean encryption(){
        TestBean testBean = new TestBean();
        testBean.setUsername("小明覺得不錯");
        testBean.setAge(18);
        return testBean;
    }

    @Decrypt
    @PostMapping("/decryption")
    public TestBean Decryption(@RequestBody String testBean) {
        log.info("testBean : [{}]", testBean);
        return JSON.parseObject(testBean, TestBean.class);
    }
}

啟動項目勘天,訪問swagger地址進(jìn)行測試

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末怔揩,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子脯丝,更是在濱河造成了極大的恐慌商膊,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,482評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件宠进,死亡現(xiàn)場離奇詭異晕拆,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)砰苍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評論 2 382
  • 文/潘曉璐 我一進(jìn)店門潦匈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人赚导,你說我怎么就攤上這事〕嗑” “怎么了吼旧?”我有些...
    開封第一講書人閱讀 152,762評論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長未舟。 經(jīng)常有香客問我圈暗,道長掂为,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,273評論 1 279
  • 正文 為了忘掉前任员串,我火速辦了婚禮勇哗,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘寸齐。我一直安慰自己欲诺,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 64,289評論 5 373
  • 文/花漫 我一把揭開白布渺鹦。 她就那樣靜靜地躺著扰法,像睡著了一般。 火紅的嫁衣襯著肌膚如雪毅厚。 梳的紋絲不亂的頭發(fā)上塞颁,一...
    開封第一講書人閱讀 49,046評論 1 285
  • 那天,我揣著相機(jī)與錄音吸耿,去河邊找鬼祠锣。 笑死,一個胖子當(dāng)著我的面吹牛咽安,可吹牛的內(nèi)容都是我干的伴网。 我是一名探鬼主播,決...
    沈念sama閱讀 38,351評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼板乙,長吁一口氣:“原來是場噩夢啊……” “哼是偷!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起募逞,我...
    開封第一講書人閱讀 36,988評論 0 259
  • 序言:老撾萬榮一對情侶失蹤蛋铆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后放接,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體刺啦,經(jīng)...
    沈念sama閱讀 43,476評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,948評論 2 324
  • 正文 我和宋清朗相戀三年纠脾,在試婚紗的時候發(fā)現(xiàn)自己被綠了玛瘸。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,064評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡苟蹈,死狀恐怖糊渊,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情慧脱,我是刑警寧澤渺绒,帶...
    沈念sama閱讀 33,712評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響宗兼,放射性物質(zhì)發(fā)生泄漏躏鱼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,261評論 3 307
  • 文/蒙蒙 一殷绍、第九天 我趴在偏房一處隱蔽的房頂上張望染苛。 院中可真熱鬧,春花似錦主到、人聲如沸茶行。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,264評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拢军。三九已至,卻和暖如春怔鳖,著一層夾襖步出監(jiān)牢的瞬間茉唉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,486評論 1 262
  • 我被黑心中介騙來泰國打工结执, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留度陆,地道東北人。 一個月前我還...
    沈念sama閱讀 45,511評論 2 354
  • 正文 我出身青樓献幔,卻偏偏與公主長得像懂傀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蜡感,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,802評論 2 345

推薦閱讀更多精彩內(nèi)容