Recently, a project needs to provide an interface to the outside world, providing public domain name for access, and the interface is related to transaction orders, so security is very important. Here sorted out some common security measures and specific how to achieve.

Security measures

Personally, I think security measures are mainly in two aspects, on the one hand, how to ensure the security of data in the process of transmission, and on the other hand, the data has arrived at the server side, how to identify the data on the server side, how not to be attacked; Take a look at the following specific security measures.

1. Encrypt data

As we know, packets are easily captured in the process of data transmission. If data is transmitted directly, such as through HTTP, the data transmitted by users can be accessed by anyone. Therefore, data must be encrypted. The common practice is to encrypt key fields, such as the user password is directly encrypted by MD5. Now the mainstream approach is to use HTTPS protocol, between HTTP and TCP to add a layer of encryption layer (SSL layer), this layer is responsible for data encryption and decryption;

2. Data signing

Data signature is a number string that can not be forged by the sender to ensure that the data will not be tampered during transmission. If the data is already encrypted over HTTPS, you might ask, is it still necessary to sign it? Data is encrypted during transmission. Theoretically, even if packets are captured, data cannot be tampered with. However, we should know that the encryption part is actually only on the extranet. Now many services need to go through many service redirection on the Intranet, so the check-in here can prevent the data from being tampered with on the Intranet.

3. Timestamp mechanism

Data is easy to be captured, but after the above encryption, signed processing, even if the data can not see the real data; But there are bad people do not care about the real data, but directly get captured data packets for malicious request; A timestamp mechanism can be used to add the current time to each request. The server will subtract the current time from the time in the message to see if it is within a fixed time range, such as 5 minutes. In this way, the malicious request packet cannot change the time inside, so it is regarded as an illegal request after 5 minutes.

4. The AppId mechanism

Most websites basically require a user name and password to log in, not who can use my site, which is actually a kind of security mechanism; In fact, the corresponding external interface also needs such a mechanism, not everyone can call, users who need to use the interface need to open appID in the background, to provide users with relevant keys; Appid + key needs to be provided in the interface called, and the server side will carry out relevant verification;

5. Flow limiting mechanism

Is a real user, and opened the appID, but frequently call the interface; In this case, traffic limiting is required for the related APPID. The commonly used traffic limiting algorithms include token bucket and leaky bucket algorithms.

6. Blacklist mechanism

If the appID has many illegal operations, or there is a special black system, the appID will be directly blacklisted after analysis, and all requests will directly return error codes;

7. Verify data validity

This can be said that every system will have a processing mechanism, only in the case of legal data will be processed; Each system has its own verification rules, of course there may be some common rules, such as id card length and composition, telephone number length and composition and so on;

How to implement

The above general introduction of some commonly used interface security measures, of course, there may be other ways I do not know, I hope you add, look at the above methods and measures, how to achieve;

1. Encrypt data

Now the mainstream encryption methods have symmetric encryption and asymmetric encryption;

Symmetric encryption: The symmetric key uses the same key during encryption and decryption. Common symmetric encryption algorithms include DES and AES. The advantage is that the calculation speed is fast, the disadvantage is that before data transmission, sender and receiver must agree on a good secret key, and then make both sides can save the secret key, if one party’s secret key is leaked, then encrypted information is not safe;

Asymmetric encryption: the server generates a pair of keys. The private key is stored on the server and the public key can be released to anyone. The advantage is more secure than symmetric encryption, but the speed of encryption and decryption is much slower than symmetric encryption; The RSA algorithm is widely used;

The two encryption methods have their own advantages and disadvantages, while HTTPS is a combination of the two encryption methods, integrating the advantages of both sides, in terms of security and performance.

Symmetric encryption and asymmetric encryption code implementation, THE JDK provides the relevant tool classes can be used directly, here but more introduction;

2. Data signing

The md5 algorithm is widely used for data signature. The data to be submitted is combined with a string in some way, and then md5 is used to generate an encrypted string, which is the signature of the packet. Here is a simple example:

STR: parameter1= {parameter1} & parameters2= {parameter2} &... &parameter n={parameter n}$key={user key}; MD5.encrypt(str);

Copy the code

Note that both the client and server have a copy of the final user key, which is more secure.

3. Timestamp mechanism

After the decrypted data is authenticated by signature, we get the client timestamp field in the data packet, and then subtract the client time from the current server time to see whether the result is within a range. The pseudo-code is as follows:

long interval=5*60*1000;// The timeout period

long clientTime=request.getparameter("clientTime");

long serverTime=System.currentTimeMillis();

if(serverTime-clientTime>interval){

    return new Response("Exceeding processing time")

}

Copy the code

4. The AppId mechanism

A unique AppId can be generated, and the key can be randomly generated using special characters such as letters and numbers. Generate unique AppId to see whether global unique is needed according to the actual situation; However, whether globally unique or not, it is better to generate ids with the following attributes: trending: This gives better performance with indexes when saving the database; Information security: try not to be continuous, easy to find the rules; Globally unique Id generation methods are common, such as snowflake method;

5. Flow limiting mechanism

Common traffic limiting algorithms include: token bucket traffic limiting, leaky bucket traffic limiting, and counter traffic limiting.

1. Traffic limiting of the token bucket

The principle of token bucket algorithm is that the system puts tokens into the bucket at a certain rate and then discards them when it is full. When the request is made, the token will be taken out of the bucket first. If the token can be obtained, the request can continue to be completed, otherwise wait or refuse service. Token bucket allows a certain degree of burst traffic, which can be processed as long as there are tokens, and supports taking multiple tokens at a time.

2. Limit flow in leaky buckets

The principle of the leaky bucket algorithm is that the requests flow out at a constant rate, and the incoming request rate is arbitrary. When the number of requests exceeds the bucket capacity, the new requests wait or refuse service. It can be seen that the leaky bucket algorithm can forcibly limit the data transmission speed.

3. Current limiting of the counter

Counter is a relatively simple and crude algorithm, mainly used to limit the total number of concurrent, such as database connection pool, thread pool, second kill concurrency; Counter current limiting as long as the total number of requests within a certain period of time exceeds the set threshold value for current limiting; Based on how the above algorithm is implemented, Guava provides the RateLimiter tool class based on the token bucket algorithm:

RateLimiter rateLimiter = RateLimiter.create(5);

Copy the code

The above code indicates that only five concurrent requests are allowed to be processed in one second. The above method can only be used for the flow limiting of single application requests, not for full flow limiting. At this time, the need for distributed limiting, can be based on Redis + Lua to achieve;

6. Blacklist mechanism

We will not discuss how and why to set a state for each user, such as: initialization state, normal state, black state, closed state and so on; Or we can directly save the blacklist list through the distributed configuration center and check whether it is in the list each time.

7. Verify data validity

Validity check includes routine check and service check. Regular check: including signature check, mandatory check, length check, type check, format check, etc. Business verification: according to the actual business, for example, the order amount should not be less than 0, etc.

conclusion

This paper lists several common security measures including: data encryption, data signature, timestamp mechanism, AppId mechanism, traffic limiting mechanism, blacklist mechanism and data validity check; Of course there must be other ways, welcome to add.

This article is formatted using MDNICE