I. Implementation principle

Similar to symmetric encryption technology, the key is set on the Nginx side, and then the server side uses the same key for MD5 encryption. After the resource link is generated, Nginx accesses Nginx through the link link, and Nginx verifies the link information before passing.

Nginx configuration

1. Go to the Nginx installation directory

2. Run the./configure –with-http_secure_link_module command to install the secure_link module, and then run make and make install

3. After the command is executed, nginx -v checks whether the installation is successful

4. Access the nginx configuration file nginx.conf and perform the following configuration (secure_link and secure_link_MD5 are added). The secret_key is the secret key and can be modified by yourself. You can add your own interception rules after location

 server {
        listen       80; server_name localhost; location / { secure_link $arg_md5,$arg_expires; # this is configured2The parameters are arg_MD5 and arg_expires secure_link_MD5"secret_key$secure_link_expires$uri"; #secret_key is a custom encrypted stringif ($secure_link = "") {
        return 403; Resource does not exist or hash match failed}if ($secure_link = "0") {
        return 403; # timestamp expired}} error_page500 502 503 504/50x.html; location = /50x.html { root html; }}Copy the code

secure_link

Consists of a checksum and an expiration time, where the checksum is compared with the MD5 hash of the specified parameter in secure_link_MD5.

If the two values do not agree, the value of the variable is null; If the two values are the same, an expiration check is performed. If expired, the variable value is 0; If not, it is 1.

If the link is time-limited, the expiration time is set with the timestamp, stated after the MD5 hash value. If no expiration time is set, the link is permanently valid.

secure_link_md5

The MD5 value will be compared with the MD5 value passed in the URL (so make sure the values are in the same order).

Second, Java code configuration

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

    public class TEST {
    public static void main(String[] args) {
        String time = String.valueOf(System.currentTimeMillis() / 1000 + 600);+600 indicates that the address will become invalid in 600 seconds
        String md5 = Base64.encodeBase64URLSafeString(DigestUtils.md5("secret_key"+time+"/test.mp4"));
        System.out.println("Http://192.168.1.9/test.mp4? md5=" + md5 + "&expires="+ time); }}Copy the code

Note:

Md5 in Java and secure_link_MD5 in Nginx correspond to each other.