Importance of data security

Keywords: security

data security

Data security has two opposite meanings: one is the security of data itself, which mainly refers to the active protection of data by using modern cryptographic algorithms, such as data confidentiality, data integrity, two-way strong identity authentication, etc.; the other is the security of data protection, which mainly uses modern information storage means to actively protect data, such as disk array, data backup Remote disaster recovery and other means ensure the security of data. Data security is an active inclusion measure. The security of data itself must be based on reliable encryption algorithm and security system, mainly including symmetric algorithm and public key cryptosystem.

Data encryption (Java)

Data is divided into static data and dynamic data. Encryption methods are also different. Protection methods can be divided into encryption, signature, tokenization (Pseudonymization and anonymization), data shielding and transparent file encryption. Data protection should be analyzed according to the type of data and business scenarios. Data encryption cannot be used to protect data. For example, financial companies cannot encrypt financial data, because once encrypted, fuzzy query and ratio query cannot be done. But financial data are also important. Therefore, it is necessary to process the data from the perspective of data protection, rather than data encryption. In addition, DLP (data leakage prevention) is mentioned in the answers of other authors, which I think is slightly inappropriate. DLP is a protection method, which only processes the black-and-white list of data or labels files. Ultimately, it controls the flow of data or files on the communication layer. It can only be called a protection method, not an encryption method.

Common encryption methods in Java

Why should data be encrypted?


Therefore, in today's Internet, data security is very important. For sensitive data, encryption request parameters and various signature verification are also very important. As developers, they need to have security awareness, such as external interface settings and request corresponding isolation at the gateway layer!

Data encryption mode (Alipay encryption)

····Symmetric encryption principle

Symmetric encryption: symmetric encryption uses the same key for encryption and decryption. The encryption process is as follows:

Encryption: original + key = ciphertext

Decryption: ciphertext key = original text


Front end request parameters


Back end parameter processing

·····What is asymmetric encryption?

The key of asymmetric encryption algorithm is a long string of random numbers obtained through a series of algorithms. Generally, the longer the length of random numbers, the more secure the encrypted information is. The public key can be derived from the private key through a series of algorithms, that is, the public key exists based on the private key. However, the private key cannot be pushed back through the public key. This process is one-way.

In the process of information security, the receiver only needs to keep its private key without disclosure.

Similarly, when the receiver sends a message to the sender, the receiver encrypts the ciphertext through the public key of the original sender

Symmetric encryption:

Advantages: simple algorithm, easy encryption and decryption, high efficiency and fast execution.

Disadvantages: relatively speaking, it is not particularly secure. There is only one key. If the ciphertext is intercepted and the key is hijacked, the information is easy to be decoded.

Asymmetric encryption:

Advantages: security, even if the ciphertext is intercepted and the public key is obtained, but the private key cannot be obtained, the ciphertext cannot be decoded. As the receiver, be sure to keep your own key.

Disadvantages: the encryption algorithm is very complex, the security depends on the algorithm and key, and the efficiency of encryption and decryption is very low.

What is a digital certificate?

Digital Certificate is a bit similar to our resident ID card, but digital Certificate is based on Internet communication and is used to mark the identity of both sides of communication. Digital certificates are issued by the authority Certificate
Issued by Authority, also known as Certificate Authorization, or CA for short. People can use it to identify each other's identity information on the Internet.

The digital certificate binds the public key and the real identity of its holder. It is similar to the resident ID card in real life. The difference is that the digital certificate is no longer a paper certificate, but an electronic data containing the identity information of the certificate holder and approved and issued by the certification center. It is widely used in e-commerce and mobile Internet

4: What is a digital signature?

Digital signature means that the abstract information is encrypted with the recipient's public key and sent to the recipient together with the ciphertext. The receiver decrypts the summary information with its own private key, then uses the Hash function to generate a summary information for the received ciphertext, and then compares the summary information with the summary information transmitted and decrypted. If consistent, it indicates that the data information has not been tampered with.

In other words, digital signature can verify the integrity of the received information and avoid hijacking, tampering or loss of Midway information. The other party can judge that the obtained data information is the most original data according to the digital signature

Sign JWT (token at login or generate signature information on demand)

For requests, we need user information. If it can be generated according to certain rules, and the user information is encrypted and placed in the request header, it will be carried in each request. At the back end (the service layer can parse the user information and greatly improve security), and at the gateWay (the gateWay layer has request restrictions), the user information must be carried, This is also in line with today's security information settings!

JWT principle

SON Web Token (or
JWT) is just a JSON string containing some meaningful data. Its most important feature is that in order to confirm whether it is valid, we only need to look at the content of the JWT itself, without the help of a third-party service or saving it in memory between multiple requests - because it carries the information verification code MAC(Message)
Authentication Code).
A JWT consists of three parts: Header, data Payload and Signature. Let's start with Payload one by one.

What does the JWT Payload look like?

Payload is just an ordinary Javascript
Object. JWT has no restrictions on the content of the payload, but it must be noted that JWT is not encrypted. Therefore, if any information placed in the token is intercepted, it is readable to anyone else. Therefore, we should not store any user information that can be used by hackers in the payload.

JWT Header – why is it necessary?

The content of Payload is verified by signature on the receiver side. However, there are many types of signatures. Therefore, the receiver needs to know which type of signature is used.

This metadata information about the token itself is stored in another Javascript object and sent to the customer along with the Payload. This independent object is a JSON object called JWT
Header, which is also an ordinary Javascript object, where we can see the signature type information, such as RS256.

What does the JWT generated token look like? (a string of characters consisting of three parts separated by ".")

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

(Header.Payload.Signature)

package com.taoci.taoci.stu.utils;


import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;

/**
 * @Description: Signature JWT Kit
 * @Author: liaocongcong
 * @Date: 2021/10/17 15:48
 */
public class JwtUtils {


    private static final long EXPIRE = 60 * 1000; //Expiration time

    public static final SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);//Key, dynamically generated key

    /**
     * Generate token
     *
     * @param claims To send a message map
     * @return
     */
    public static String generate(Map<String, Object> claims) {
        Date nowDate = new Date();
        //Expiration time, set to one minute
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRE);
        //Header information, optional
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "jwt");

        //A stronger key can only be used from JDK11
        //  KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
        //  PrivateKey key1 =  keyPair.getPrivate();  //  Private key
        //PublicKey key2 =  keyPair.getPublic();  // Public key

        return Jwts.builder().setHeader(header)
                // . setSubject("weimi") / / subject
                // . setIssuer("weimi") / / sender
                .setClaims(claims)  //Custom claims
                .setIssuedAt(nowDate)//current time 
                .setExpiration(expireDate) //Expiration time
                .signWith(key)//Signature algorithm and key
                .compact();
    }

    /**
     * Generate token
     *
     * @param header Incoming header information map
     * @param claims To send a message map
     * @return
     */
    public static String generate(Map<String, Object> header, Map<String, Object> claims) {
        Date nowDate = new Date();
        //Expiration time, set to one minute
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRE);

        return Jwts.builder().setHeader(header)
                // . setSubject("weimi") / / subject
                //    . setIssuer("weimi") / / sender
                .setClaims(claims)  //Custom claims
                .setIssuedAt(nowDate)//current time 
                .setExpiration(expireDate) //Expiration time
                .signWith(key)//Signature algorithm and key
                .compact();
    }

    /**
     * Verify whether it is jwt signed
     *
     * @param token
     * @return
     */
    public static boolean isSigned(String token) {
        return Jwts.parser()
                .setSigningKey(key)
                .isSigned(token);
    }

    /**
     * Verify that the signature is correct
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token);
            return true;
        } catch (JwtException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    /**
     * Get some contents of the payload (i.e. the information to be transmitted)
     * Usage: for example, get userId: getClaim(token).get("userId");
     *
     * @param token
     * @return
     */
    public static Claims getClaim(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    /**
     * Get header information map
     * Usage: getHeader(token).get("alg");
     *
     * @param token
     * @return
     */
    public static JwsHeader getHeader(String token) {
        JwsHeader header = null;
        try {
            header = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getHeader();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return header;
    }

    /**
     * Get jwt publishing time
     */
    public static Date getIssuedAt(String token) {
        return getClaim(token).getIssuedAt();
    }

    /**
     * Get jwt expiration time
     */
    public static Date getExpiration(String token) {
        return getClaim(token).getExpiration();
    }

    /**
     * Verify whether the token is invalid
     *
     * @param token
     * @return true:Expired false: not expired
     */
    public static boolean isExpired(String token) {
        try {
            final Date expiration = getExpiration(token);
            return expiration.before(new Date());
        } catch (ExpiredJwtException expiredJwtException) {
            return true;
        }
    }

    /**
     * Directly decrypt Base64 to obtain header content
     *
     * @param token
     * @return
     */
    public static String getHeaderByBase64(String token) {
        String header = null;
        if (isSigned(token)) {
            try {
                byte[] header_byte = Base64.getDecoder().decode(token.split("\\.")[0]);
                header = new String(header_byte);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return header;
    }

    /**
     * Decrypt and obtain payload content directly from Base64
     *
     * @param token
     * @return
     */
    public static String getPayloadByBase64(String token) {
        String payload = null;
        if (isSigned(token)) {
            try {
                byte[] payload_byte = Base64.getDecoder().decode(token.split("\\.")[1]);
                payload = new String(payload_byte);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return payload;
    }

    public static void main(String[] args) {
        //User defined information claims
        Map<String, Object> map = new HashMap<>();
        map.put("userId", "test122");
        String token = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJhY2NvdW50S" +
                "WQiOjE0NDk5ODY5OTY1OTk4MDM5MDQsImNyZWF0ZVRpbWUiOjE2MzQ1Mzg5MDYwMDAsInVzZXJu" +
                "YW1lIjoiYWRtaW4iLCJpYXQiOjE2MzQ1NDIwNTQsImV4cCI6MTYzNDU0MjE" +
                "xNH0.xBzAv08zBi31GXgPnc81t9YgJYiqe1wk6GKqGXoRAVw";
        System.out.println(token);

        System.out.println("claim:" + getClaim(token).get("userId"));
        System.out.println("header:" + getHeader(token));
        //    System.out.println(getIssuedAt(token));
        Claims claims = getClaim(token);

        //  System.out.println(getHeaderByBase64(token));
        System.out.println(getPayloadByBase64(token));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy‐MM‐dd hh:mm:ss");
        System.out.println("Time filed :" + sdf.format(claims.getIssuedAt()));
        System.out.println("Expiration time:" + sdf.format(claims.getExpiration()));
        System.out.println("current time :" + sdf.format(new Date()));

    }
}

I feel there are many more. I withdrew from work and the boss is coming. I made up for last week's @lcc

Posted by JimStrosky on Fri, 12 Nov 2021 01:31:04 -0800