How to encrypt and decrypt springboot data security transmission

  • 的头像-Tumi
  • 16 day agopublish

Zhe Pian Wen Zhang Gei Da Jia Jie Shao Ru He Jin Xing Springboot Shu Ju An Quan Chuan Shu Jia Mi Yu Jie Mi , Nei Rong Fei Chang Xiang Xi , Gan Xing Qu De Xiao Huo Ban Men Ke Yi Can Kao Jie Jian , Xi Wang Dui Da Jia Neng You Suo Bang Zhu 。

Huan Jing :springboot2.2.6.RELEASE、Vue+axios

Tong Guo Ji Cheng RequestBodyAdviceAdapter Shi Xian Dui Yu Qing Qiu De Nei Rong Jin Xing Jie Mi Cao Zuo , Shi Xian ResponseBodyAdvice Lai Dui Xiang Ying Nei Rong Jin Xing Jia Mi Chu Li 。

Ding Yi Jia Mi Jie Mi De Jie Kou :

SecretProcess.java

public interface SecretProcess {          /**      *  <p> Shu  Ju  Jia  Mi </p>      *  <p> Shi  Jian :2020 Nian 12 Yue 24 Ri - Xia  Wu 12:22:13</p>      * @author xg      * @param data  Dai  Jia  Mi  Shu  Ju       * @return String  Jia  Mi  Jie  Guo       */     String encrypt(String data) ;          /**      *  <p> Shu  Ju  Jie  Mi </p>      *  <p> Shi  Jian :2020 Nian 12 Yue 24 Ri - Xia  Wu 12:23:20</p>      * @author xg      * @param data  Dai  Jie  Mi  Shu  Ju       * @return String  Jie  Mi  Hou  De  Shu  Ju       */     String decrypt(String data) ;          /**      *  <p> Jia  Mi  Suan  Fa  Ge  Shi : Suan  Fa [/ Mo  Shi / Tian  Chong ]</p>      *  <p> Shi  Jian :2020 Nian 12 Yue 24 Ri - Xia  Wu 12:32:49</p>      * @author xg      * @return String      */     String getAlgorithm() ;          public static class Hex {                  private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',                 'a', 'b', 'c', 'd', 'e', 'f' };                  public static byte[] decode(CharSequence s) {             int nChars = s.length();             if (nChars % 2 != 0) {                 throw new IllegalArgumentException("16 Jin  Zhi  Shu  Ju  Cuo  Wu ");             }             byte[] result = new byte[nChars / 2];             for (int i = 0; i < nChars; i += 2) {                 int msb = Character.digit(s.charAt(i), 16);                 int lsb = Character.digit(s.charAt(i + 1), 16);                 if (msb < 0 || lsb < 0) {                     throw new IllegalArgumentException(                         "Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");                 }                 result[i / 2] = (byte) ((msb << 4) | lsb);             }             return result;         }                  public static String encode(byte[] buf) {             StringBuilder sb = new StringBuilder() ;             for (int i = 0, leng = buf.length; i < leng; i++) {                 sb.append(HEX[(buf[i] & 0xF0) >>> 4]).append(HEX[buf[i] & 0x0F]) ;             }             return sb.toString() ;         }              }      }

Gai Jie Kou Zhong Ding Yi Liao Liang Ge Fang Fa Fen Bie Shi Jia Mi Yu Jie Mi De Fang Fa , Huan You Hex Lei Gai Lei Yong Lai Dui Shu Ju Chu Li 16 Jin Zhi De Zhuan Huan 。

Ding Yi Yi Ge Chou Xiang Lei Shi Xian Shang Mian De Jie Kou , Ju Ti De Jia Jie Mi Shi Xian Xi Jie Zai Gai Chou Xiang Lei Zhong

AbstractSecretProcess.java

public abstract class AbstractSecretProcess implements SecretProcess {          @Resource     private SecretProperties props ;          @Override     public String decrypt(String data) {         try {             Cipher cipher = Cipher.getInstance(getAlgorithm()) ;             cipher.init(Cipher.DECRYPT_MODE, keySpec()) ;             byte[] decryptBytes = cipher.doFinal(Hex.decode(data)) ;             return new String(decryptBytes) ;         } catch (Exception e) {             throw new RuntimeException(e) ;         }     }          @Override     public String encrypt(String data) {         try {             Cipher cipher = Cipher.getInstance(getAlgorithm()) ;             cipher.init(Cipher.ENCRYPT_MODE, keySpec()) ;             return Hex.encode(cipher.doFinal(data.getBytes(Charset.forName("UTF-8")))) ;         } catch (Exception e) {             throw new RuntimeException(e) ;         }     }          /**      *  <p> Gen  Ju  Mi  Yue  Sheng  Cheng  Bu  Tong  De  Mi  Yue  Cai  Liao </p>      *  <p> Mu  Qian  Zhi  Chi :AES, DES</p>      *  <p> Shi  Jian :2020 Nian 12 Yue 25 Ri - Xia  Wu 1:02:54</p>      * @author xg      * @param secretKey  Mi  Yue       * @param algorithm  Suan  Fa       * @return Key      */     public Key getKeySpec(String algorithm) {         if (algorithm == null || algorithm.trim().length() == 0) {             return null ;         }         String secretKey = props.getKey() ;         switch (algorithm.toUpperCase()) {             case "AES":                 return new SecretKeySpec(secretKey.getBytes(), "AES") ;             case "DES":                 Key key = null ;                 try {                     DESKeySpec desKeySpec = new DESKeySpec(secretKey.getBytes()) ;                     SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES") ;                     key = secretKeyFactory.generateSecret(desKeySpec);                 } catch (Exception e) {                     throw new RuntimeException(e) ;                 }                 return key ;             default:                 return null ;         }     }          /**      *  <p> Sheng  Cheng  Mi  Yue  Cai  Liao </p>      *  <p> Shi  Jian :2020 Nian 12 Yue 25 Ri - Shang  Wu 11:35:03</p>      * @author xg      * @return Key  Mi  Yue  Cai  Liao       */     public abstract Key keySpec() ;      }

Gai Chou Xiang Lei Zhong Ti Gong Liao 2 Zhong Dui Cheng Jia Mi De Mi Yue Huan Yuan , Fen Biao Shi AES He DES Suan Fa 。 Yi Ge Chou Xiang Fang Fa , Gai Chou Xiang Fang Fa

keySpec Gai Fang Fa Xu Yao Zi Lei Shi Xian ( Ju Ti Shi Yong De Shi Na Zhong Dui Cheng Jia Mi Suan Fa )。

Ju Ti Jia Mi Suan Fa De Shi Xian Lei

AESAlgorithm.java

public class AESAlgorithm extends AbstractSecretProcess {      @Override     public String getAlgorithm() {         return "AES/ECB/PKCS5Padding";     }          @Override     public Key keySpec() {         return this.getKeySpec("AES") ;     }  }

SecretProperties.java Shu Xing Pei Zhi Lei

@Configuration public class SecretConfig {          @Bean     @ConditionalOnMissingBean(SecretProcess.class)     public SecretProcess secretProcess() {         return new AESAlgorithm() ;     }          @Component     @ConfigurationProperties(prefix = "secret")     public static class SecretProperties {                  private Boolean enabled ;         private String key ;          public Boolean getEnabled() {             return enabled;         }          public void setEnabled(Boolean enabled) {             this.enabled = enabled;         }          public String getKey() {             return key;         }          public void setKey(String key) {             this.key = key;         }              }      }

Pei Zhi Wen Jian Zhong Ru Xia Pei Zhi :

secret:   key: aaaabbbbccccdddd # Mi  Yue    enabled: true # Shi  Fou  Kai  Qi  Jia  Jie  Mi  Gong  Neng 

Zai Xiang Mu Zhong Ke Neng Bu Shi Suo You De Fang Fa Du Yao Jin Xing Shu Ju De Jia Mi Jie Mi Chu Lai , Suo Yi Jie Xia Lai Ding Yi Yi Ge Zhu Jie , Zhi You Tian Jia You Gai Zhu Jie De Controller Lei Huo Shi Ju Ti Jie Kou Fang Fa Cai Jin Xing Shu Ju De Jia Mi Jie Mi , Ru Xia :

SIProtection.java

@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Mapping @Documented public @interface SIProtection {  }

Dui Qing Qiu Nei Rong Jin Xing Jie Mi Chu Lai , Tong Guo RequestBodyAdvice

DecryptRequestBodyAdivce.java

@ControllerAdvice @ConditionalOnProperty(name = "secret.enabled", havingValue = "true") public class DecryptRequestBodyAdivce extends RequestBodyAdviceAdapter {      @Resource     private SecretProcess secretProcess ;          @Override     public boolean supports(MethodParameter methodParameter, Type targetType,             Class<? extends HttpMessageConverter<?>> converterType) {         return methodParameter.getMethod().isAnnotationPresent(SIProtection.class)                  || methodParameter.getMethod().getDeclaringClass().isAnnotationPresent(SIProtection.class) ;     }      @Override     public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,             Class<? extends HttpMessageConverter<?>> converterType) throws IOException {         String body = secretProcess.decrypt(inToString(inputMessage.getBody())) ;         return new HttpInputMessage() {             @Override             public HttpHeaders getHeaders() {                 return inputMessage.getHeaders();             }             @Override             public InputStream getBody() throws IOException {                 return new ByteArrayInputStream(body.getBytes()) ;             }         } ;     }          private String inToString(InputStream is) {         byte[] buf = new byte[10 * 1024] ;         int leng = -1 ;         StringBuilder sb = new StringBuilder() ;         try {             while ((leng = is.read(buf)) != -1) {                 sb.append(new String(buf, 0, leng)) ;             }             return sb.toString() ;         } catch (IOException e) {             throw new RuntimeException(e) ;         }     }  }

Zhu Yi Zhe Li De :@ConditionalOnProperty(name = "secret.enabled", havingValue =  "true") Zhu Jie , Zhi You Kai Qi Liao Jia Jie Mi Gong Neng Cai Hui Sheng Xiao 。 Zhu Yi Zhe Li De supports Fang Fa

Dui Xiang Ying Nei Rong Jia Mi Chu Lai

EncryptResponseBodyAdivce.java

@ControllerAdvice @ConditionalOnProperty(name = "secret.enabled", havingValue = "true") public class EncryptResponseBodyAdivce implements ResponseBodyAdvice<Object>  {      @Resource     private SecretProcess secretProcess ;      @Override     public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {         return returnType.getMethod().isAnnotationPresent(SIProtection.class)                  || returnType.getMethod().getDeclaringClass().isAnnotationPresent(SIProtection.class) ;     }      @Override     public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,             Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,             ServerHttpResponse response) {         if (body == null) {             return body ;         }         try {             String jsonStr = new ObjectMapper().writeValueAsString(body) ;             return secretProcess.encrypt(jsonStr) ;         } catch (Exception e) {             throw new RuntimeException(e) ;         }     } }

Controller Ying Yong

@PostMapping("/save")     @SIProtection     public R save(@RequestBody Users users) {         return R.success(usersService.save(users)) ;     } //  Zhe  Dui  Ju  Ti  Fang  Fa  Jin  Xing  Jia  Jie  Mi   @RestController @RequestMapping("/users") @SIProtection  public class UsersController { //  Dui  Gai Controller Zhong  De  Suo  You  Fang  Fa  Jin  Xing  Jia  Jie  Mi  Chu  Li  }

Qian Duan

Yin Ru Di San Fang Cha Jian :crypto-js

Gong Ju Fang Fa Jia Jie Mi :

/**      *  Jia  Mi  Fang  Fa       * @param data  Dai  Jia  Mi  Shu  Ju       * @returns {string|*}      */     encrypt (data) {       let key = CryptoJS.enc.Utf8.parse(Consts.Secret.key)       if (typeof data === 'object') {         data = JSON.stringify(data)       }       let plainText = CryptoJS.enc.Utf8.parse(data)       let secretText = CryptoJS.AES.encrypt(plainText, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7}).ciphertext.toString()       return secretText     },     /**      *  Jie  Mi  Shu  Ju       * @param data  Dai  Jie  Mi  Shu  Ju       */     decrypt (data) {       let key = CryptoJS.enc.Utf8.parse(Consts.Secret.key)       let secretText = CryptoJS.enc.Hex.parse(data)       let encryptedBase64Str = CryptoJS.enc.Base64.stringify(secretText)       let result = CryptoJS.AES.decrypt(encryptedBase64Str, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7}).toString(CryptoJS.enc.Utf8)       return JSON.parse(result)     }

Pei Zhi :

let Consts = {   Secret: {     key: 'aaaabbbbccccdddd', //  Bi  Xu 16 Wei ( Qian  Hou  Duan  Yao  Yi  Zhi , Mi  Yue )     urls: ['/users/save']   } } export default Consts

Zhe Li De urls Biao Shi Dui Na Xie Qing Qiu Jin Xing Lan Jie Chu Lai ( Jia Jie Mi ), Zhe Li Ye Ke Yi Pei Zhi  "*" Biao Shi Dui Suo You De Qing Qiu Chu Lai 。

axios Qing Qiu Qian He Xiang Ying Hou Dui Shu Ju Jin Xing Jia Jie Mi Chu Lai :

Fa Song Qing Qiu Qian :

axios.interceptors.request.use((config) => {       let uri = config.url       if (uri.includes('?')) {         uri = uri.substring(0, uri.indexOf('?'))       }       if (window.cfg.enableSecret === '1' && config.data && (Consts.Secret.urls.indexOf('*') > -1 || Consts.Secret.urls.indexOf(uri) > -1)) {         let data = config.data         let secretText = Utils.Secret.encrypt(data)         config.data = secretText       }       return config     }, (error) => {       let errorMessage = ' Qing  Qiu  Shi  Bai '       store.dispatch(types.G_SHOW_ALERT, {title: ' Qing  Qiu  Shi  Bai ', content: errorMessage, showDetail: false, detailContent: String(error)})       return Promise.reject(error)     }) axios.interceptors.response.use((response) => {       let uri = response.config.url       if (uri.includes('?')) {         uri = uri.substring(0, uri.indexOf('?'))       }       if (window.cfg.enableSecret === '1' && response.data && (Consts.Secret.urls.indexOf('*') > -1 || Consts.Secret.urls.indexOf(uri) > -1)) {         let data = Utils.Secret.decrypt(response.data)         if (data) {           response.data = data         }       }       return response     }, (error) => {       console.error(`test interceptors.response is in, ${error}`)       return Promise.reject(error)     })

Zhe Li De window.cfg.enableSecret   Pei Zhi Shi Wo Zi Ji Xiang Mu Zhong You Ge Pei Zhi Wen Jian Pei Zhi Shi Fou Kai Qi , Zhe Ge Da Jia Ke Yi Gen Ju Zi Ji De Huan Jing Lai Shi Xian 。

Ce Shi :

 Ru  He  Jin  Xing Springboot Shu  Ju  An  Quan  Chuan  Shu  Jia  Mi  Yu  Jie  Mi

Zhe Li Ke Yi Kan Dao Qian Duan Fa Qi De Qing Qiu Nei Rong Yi Jing Bei Jia Mi Liao

Xiang Ying Nei Rong :

 Ru  He  Jin  Xing Springboot Shu  Ju  An  Quan  Chuan  Shu  Jia  Mi  Yu  Jie  Mi

Guan Yu Ru He Jin Xing Springboot Shu Ju An Quan Chuan Shu Jia Mi Yu Jie Mi Jiu Fen Xiang Dao Zhe Li Liao , Xi Wang Yi Shang Nei Rong Ke Yi Dui Da Jia You Yi Ding De Bang Zhu , Ke Yi Xue Dao Geng Duo Zhi Shi 。 Ru Guo Jue De Wen Zhang Bu Cuo , Ke Yi Ba Ta Fen Xiang Chu Qu Rang Geng Duo De Ren Kan Dao 。

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment