In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
In this issue, the editor will bring you about how the front and back-end API interaction ensures data security. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
Preface
In the development mode of the separation of front and rear ends, we take the interface as the standard to promote, define the interface, develop their own functions, and finally carry on the joint adjustment and integration. Whether it is developing native APP, webapp or PC-side software, as long as the front-end and back-end separation mode, it can not avoid calling the interface provided by the back-end for business interaction.
Web page or app, as long as you grab the package, you can clearly know the data obtained by this request. Such an interface is a boon for crawler engineers, and it is easy to capture your data.
The security of data is very important, especially user-related information, which will be embezzled by lawbreakers if there is any carelessness, so we should attach great importance to this piece and should not tolerate carelessness.
How to ensure the security of data when API is called?
Communication uses https
Request signature to prevent parameters from being tampered with
Identity confirmation mechanism, which verifies the legality of each request.
Using ssl pinning to prevent packet capture in APP
Encrypt and decrypt all requests and responses
Wait, the plan... .
Encrypt and decrypt all requests and responses
There are many kinds of solutions, and the more you do, the higher the security. today, I would like to introduce to you a scheme for encrypting and decrypting all requests and responses, even if you can grab packets, even if you can call my interface. but the data I return is encrypted, as long as the encryption algorithm is secure, it won't affect me if you get my encrypted content.
This kind of work is best handled uniformly. You can't let every developer pay attention to this matter. It is very troublesome to let every developer pay attention to this matter. When returning data, you have to manually call the encryption method. After receiving the data, you also have to call the decryption method.
To do this, I encapsulated a Starter based on Spring Boot with a built-in AES encryption algorithm. The GitHub address is as follows:
Https://github.com/yinjihuan/spring-boot-starter-encrypt
First, let's see how to use it. You can download the source code, then introduce it, and then add the @ EnableEncrypt annotation to the startup class to start the encryption and decryption operation:
@ EnableEncrypt
@ SpringBootApplication
Public class App {
Public static void main (String [] args) {
SpringApplication.run (App.class, args)
}
}
Add encrypted key configuration:
Spring.encrypt.key=abcdef0123456789
Spring.encrypt.debug=false
Spring.encrypt.key: encryption key, which must be 16 bits
Spring.encrypt.debug: whether to enable debug mode. Default is false. If true, encryption and decryption operations are not enabled.
For versatility, encryption and decryption are not performed on all requests, and control is based on annotations.
If the response data needs to be encrypted, simply annotate the Controller method with @ Encrypt.
@ Encrypt
@ GetMapping ("/ list")
Public Response queryNews (String city) {
Return Response.ok (city)
}
When we access the / list interface, the data returned is the base64 encoded format after encryption.
Another operation is the data submitted in the previous paragraph, which is divided into two cases. One is the get request, which is not processed for the time being. We will consider later. The post request that is currently only processed is based on the json format submission, that is, the backend needs to use @ RequestBody to receive data, and we can annotate the operation that needs to be decrypted with @ Decrypt.
@ Decrypt
@ PostMapping ("/ save")
Public Response savePageLog (@ RequestBody PageLogParam logParam, HttpServletRequest request) {
PageLogService.save (logParam)
Return Response.ok ()
}
After the @ Decrypt annotation is added, the data submitted by the front end needs to be encrypted according to the AES encryption algorithm, and then submitted to the backend, which will be automatically decrypted and then mapped to the parameter object.
The above is all the back-end code, if the front end is used, we will use js to explain, of course, you can also do it in other languages, if it is a native Android app, it is also handled by java code.
There are only two things the front end needs to do:
Uniformly process the response of the data and decrypt it before rendering to the page
Unified encryption when data requested by POST is issued
For js encrypted files, please refer to aes.js,crypto-js.js,pad-zeropadding.js in encrypt in my GitHub.
We use axios as the framework for requesting data, and use the interceptor of axios to handle encryption and decryption operations uniformly.
First of all, you need to encapsulate a js encryption and decryption class. It is important to note that the encrypted key needs to be aligned with the background, otherwise it cannot be decrypted each other. The code is as follows:
Var key = CryptoJS.enc.Latin1.parse ('abcdef0123456789')
Var iv = CryptoJS.enc.Latin1.parse ('abcdef0123456789')
/ / encryption
Function EncryptData (data) {
Var srcs = CryptoJS.enc.Utf8.parse (data)
Var encrypted = CryptoJS.AES.encrypt (srcs, key, {
Mode: CryptoJS.mode.ECB
Padding: CryptoJS.pad.Pkcs7
});
Return encrypted.toString ()
}
/ / decrypt
Function DecryptData (data) {
Var stime = new Date () .getTime ()
Var decrypt = CryptoJS.AES.decrypt (data, key, {
Mode: CryptoJS.mode.ECB
Padding: CryptoJS.pad.Pkcs7
});
Var result = JSON.parse (CryptoJS.enc.Utf8.stringify (decrypt) .toString ())
Var etime = new Date () .getTime ()
Console.log ("DecryptData Time:" + (etime-stime))
Return result
}
Unified processing code in axios interceptor:
/ / add request interceptor
Axios.interceptors.request.use (function (config) {
/ / Please encrypt all POST. It must be submitted by json data. Forms are not supported.
If (config.method = = "post") {
Config.data = EncryptData (JSON.stringify (config.data))
}
Return config
}, function (error) {
Return Promise.reject (error)
});
/ / add response interceptor
Axios.interceptors.response.use (function (response) {
/ / the string returned by the backend indicates that a decryption operation is required.
If (typeof (response.data) = = "string") {
Response.data = DecryptData (response.data)
}
Return response
}, function (error) {
Return Promise.reject (error)
});
So far, we have done an encrypted operation for the entire front-end interactive communication. As long as the encrypted key is not disclosed, it is useless for others to get your data. The question is how to ensure that the key is not leaked?
The security of the server is high, and it can be stored in the database or in the configuration file. After all, on our own server, the most dangerous thing is the front end. App is fine and can be packaged, but it is necessary to prevent decompilation and other problems.
If it is webapp, you can rely on js encryption to achieve it. Let me introduce a way to dynamically obtain encrypted key. However, it is rather complicated to implement. Instead of code, we will only talk about ideas:
Encryption algorithms include symmetric encryption and asymmetric encryption, AES is symmetric encryption, RSA is asymmetric encryption. The reason why AES is used to encrypt data is that it is efficient and RSA is slow and can be used for signature operations.
We can use these two algorithms to complement each other to ensure security. We can use RSA to encrypt the secret key of AES and AES to encrypt data.
In fact, if you understand the principle of HTTPS, you should understand the following content at a glance. The reason why HTTPS is slower than HTTP is because of the need for client and server to safely negotiate a symmetric encryption algorithm. The rest is that both parties use this symmetric encryption algorithm for encryption and decryption when communicating.
The client starts, sends the request to the server, and the server uses the RSA algorithm to generate a pair of public and private keys, which we call pubkey1,prikey1 for short, and return the public key pubkey1 to the client.
After the client gets the public key pubkey1 returned by the server, it uses the RSA algorithm to generate a pair of public and private keys, we call it pubkey2,prikey2 for short, and encrypt the public key pubkey2 through the public key pubkey1, and then transmit it to the server.
At this time, the server receives the ciphertext transmitted by the client and decrypts it with the private key prikey1. Because the data is encrypted with the public key pubkey1, the public key pubkey2 generated by the client can be obtained through decryption.
Then we are generating symmetric encryption, that is, our AES, which is actually relative to the 16-length encrypted key in our configuration. After generating this key, we encrypt it with the public key pubkey2 and return it to the client, because only the client has the private key prikey2 corresponding to pubkey2, and only the client can decrypt it. After the client gets the data, it uses prikey2 to decrypt the operation. Get the encrypted key of the AES, and then encrypt the data transmission with the encrypted key, and the whole process ends.
Spring-boot-starter-encrypt principle
Finally, we will briefly introduce the principle of spring-boot-starter-encrypt, so that we can understand why Spring Boot is so convenient, as long as a simple configuration can achieve a lot of functions.
The @ EnableEncrypt annotation on the startup class is used to turn on the function. Import the auto-configuration class through @ Import
@ Target ({ElementType.TYPE})
@ Retention (RetentionPolicy.RUNTIME)
@ Documented
@ Inherited
@ Import ({EncryptAutoConfiguration.class})
Public @ interface EnableEncrypt {
}
The processing classes for requests and responses are configured in EncryptAutoConfiguration, using RequestBodyAdvice and ResponseBodyAdvice in Spring, so it is convenient to process requests statistically in Spring. If you want to encapsulate it at a lower level, you have to deal with it from servlet.
@ Configuration
@ Component
@ EnableAutoConfiguration
@ EnableConfigurationProperties (EncryptProperties.class)
Public class EncryptAutoConfiguration {
/ * *
* configure request for decryption
* @ return
, /
@ Bean
Public EncryptResponseBodyAdvice encryptResponseBodyAdvice () {
Return new EncryptResponseBodyAdvice ()
}
/ * *
* configure request encryption
* @ return
, /
@ Bean
Public EncryptRequestBodyAdvice encryptRequestBodyAdvice () {
Return new EncryptRequestBodyAdvice ()
}
}
Requests and responses can be processed through RequestBodyAdvice and ResponseBodyAdvice, and that's probably how it works.
This is how the front-end and back-end API interaction shared by Xiaobian ensures data security. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.