preface

Thanks to great mathematicians and cryptographers, our networks are in a relatively safe environment.

In a recent review of HTTPS, all the analysis in this article is based on TLS1.2.

WebTrust

WebTrust is a security audit standard jointly formulated by the world’s two famous CPA associations AICPA (American Institute of Certified Public Accountants) and CICA (Canadian Institute of Certified Public Accountants). It mainly examines and authenticates the security and confidentiality of Internet service providers’ system and business operation logic in a total of seven aspects. Only the root certificate authenticated by WebTrust can be pre-installed in mainstream browsers.

CA institution

CA mechanism Definition

Certificate Authority (CA) is an organization that issues digital certificates. It is the authority responsible for issuing and managing digital certificates, and as a trusted third party in e-commerce transactions, it undertakes the responsibility of verifying the validity of public keys in the public key system.

What CA organizations are there

At present, the mainstream CA organizations in the world include Comodo, Symantec, GeoTrust, DigiCert, Thawte, GlobalSign, RapidSSL, etc. Symantec and GeoTrust are both subsidiaries of DigiCert. At present, the mainstream SSL certificate brands in the market are Comodo certificate, Symantec certificate, GeoTrust certificate, Thawte certificate and RapidSSL certificate, and some unknown certificate bodies can also issue digital certificates.

The main CA institutions in China are CFCA, WoSign, GDCA and AnTruet, etc.

Symmetric encryption

define

In the encryption method of single-key cryptosystem, the same key can be used to encrypt and decrypt information at the same time. This encryption method is called symmetric encryption, also called single-key encryption.

Common encryption algorithms

DES, AES, RC2, RC4, and RC5

The sample

public class DES {
    
    public static String encrypt(String content, String key) {
        try {
            byte[] encryptionBytes = content.getBytes("UTF-8");
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secureKey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, secureKey, random);
            byte[] encryptionBase64Bytes = Base64.getEncoder().encode(cipher.doFinal(encryptionBytes));
            return new String(encryptionBase64Bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String content, String key) {
        try {
            byte[] decryptionBytes = Base64.getDecoder().decode(content);
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secureKey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, secureKey, random);
            return new String(cipher.doFinal(decryptionBytes), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {

        final String key = "this_is_key";
        String content = "Leave at nine.";

        String encryptStr = DES.encrypt(content, key);
        System.out.println("Encrypt:" + encryptStr);

        String decryptStr = DES.decrypt(encryptStr, key);
        System.out.println("Decrypt:"+ decryptStr); }}Copy the code

1. Li Lei wants to send a message to Han Meimei, and they agree to use symmetric encryption to encrypt the message

Li Lei encrypts the message with the key and sends it to Han Meimei

3, Han Meimei decrypts with the same key, and then sees the message sent to her by Li Lei

As you can see, with the above approach, once the key is compromised, the message is easily cracked

Asymmetric encryption

define

Symmetric encryption algorithms use the same secret key for encryption and decryption, whereas asymmetric encryption algorithms require two keys for encryption and decryption: a public key and a private key.

Common encryption algorithms

RSA, ECC, etc

The sample

public class RSA {

    private static Cipher cipher;

    static {
        try {
            cipher = Cipher.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch(NoSuchPaddingException e) { e.printStackTrace(); }}public static void generateKeyPair(a) {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            String publicKeyStr = getKeyString(publicKey);
            String privateKeyStr = getKeyString(privateKey);

            System.out.println("publicKeyStr :" + publicKeyStr);
            System.out.println("privateKeyStr :" + privateKeyStr);
        } catch(Exception e) { e.printStackTrace(); }}public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.decode(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }


    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = Base64.decode(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }


    public static String getKeyString(Key key) {
        byte[] keyBytes = key.getEncoded();
        return Base64.encode(keyBytes);
    }


    public static String encrypt(String publicKey, String content) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
            byte[] encryptBytes = cipher.doFinal(content.getBytes());
            return Base64.encode(encryptBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String decrypt(String privateKey, String content) {
        try {
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKey));
            byte[] decryptBytes = cipher.doFinal(Base64.decode(content));
            return new String(decryptBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {

// generateKeyPair();

        final String publicKey = "Generated using generateKeyPair";
        final String privateKey = "Generated using generateKeyPair";

        String content = "Leave at nine.";
        String encryptStr = encrypt(publicKey, content);
        System.out.println("Encrypt:" + encryptStr);
        String decryptStr = decrypt(privateKey, encryptStr);
        System.out.println("Decrypt:"+ decryptStr); }}Copy the code

1. Li Lei wants to send a message to Han Meimei, and they agree to use asymmetric encryption to encrypt the message

2, Li Lei first to get han Meimei’s public key

2. Li Lei encrypts the message with Han Meimei’s public key and sends it to Han Meimei

3, Han Meimei decrypts with her private key, and then sees the message sent to her by Li Lei

Han Meimei sends a message to Li Lei.

A digital signature

Digital Signature is a method of identifying Digital information that functions like ordinary signatures written on paper but uses public key cryptography. A set of digital signatures typically defines two complementary operations, one for signing and one for validation. Normally we use public key encryption and private key decryption. In digital signatures, we use private key encryption (equivalent to generating a signature) and public key decryption (equivalent to verifying a signature). The message can be signed directly (that is, encrypted with a private key for the purpose of signature, not secrecy), and the verifier decrypts the message correctly with the public key. If it matches the original message, the signature is verified successfully. But we usually sign the hash value of the message, because the hash value is usually much shorter than the original message, making the signature (asymmetric encryption) much more efficient. Note that calculating the hash value of the message is not a necessary step in digital signature.

The TLS and SSL

TLS (Transport Layer Security) and its predecessor SSL (Secure Sockets Layer) are Security protocols designed to ensure the Security and data integrity of Internet communications.

Let’s go to my blog democome.com/ and use WireShark to capture the TLS handshake.

WireShark TLS handshake for packet capture

TLS handshake includes RSA handshake and ECDH handshake. Through my packet capture analysis below, the ECDH handshake is used in the following example. The WireShark is used to filter IP addresses

DST == 185.199.109.153 or ip.src == 185.199.109.153

The TLS handshake process is shown as follows. For now, we only pay attention to the packet capture information with Protocol TLSv1.2:

According to the figure above, we can find that the TLS handshake process is mainly divided into the following steps.

  • Client Hello
  • Server Hello
  • Certificate
  • Server Key Exchange
  • Client Key Exchange

Which involves symmetric encryption, asymmetric encryption and other algorithms, we will analyze each step.

Client Hello

The browser sends it to the server

We need to focus on the following:

  • The TLS version: 1.2
  • Random number: Radnom
  • Cipher Suites supported by the browser

As you can see, there are 17 Cipher Suites supported by the browser, and the server chooses one of them. The random number is used in the final calculation of the master key, which is used for symmetric encryption.

Server Hello

The server sends it to the browser

  • Random number: Radnom
  • Cipher Suite for the server

The encryption suite selected by the server is TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256

Let’s look at what each part means

ECDHE: key negotiation algorithm

RSA: indicates the certificate public key encryption algorithm

AES_128: indicates the password length of the symmetric encryption algorithm and AES

GCM: AES encryption mode

SHA256: Message digest algorithm for validating messages (hash algorithm)

Certificate

The server sends it to the browser

The Server selects an encryption suite during Server Hello. The server delivers a certificate, which carries the CA certificate chain and the certificate public key. There is a root CA certificate at the top of the certificate chain, which is stored in the browser or operating system and trusted by the system.

Let’s look at the certificate chain in the browser as follows:

Then take a look at the macOS system root certificate and you can see that the uppermost certificate is trusted by the system.

The browser validates the server certificate by first finding the intermediate certificate Authority (Let’s Encrypt Authority X3) that found the Democome.com certificate, and then going up to the Root certificate (DST Root CA X3).

The digital signature is then verified from the root certificate down. In this example, DST Root CA X3’s public key is used to verify the digital signature of the Let’s Encrypt Authority X3 certificate. Verify the digital signature of the server certificate Democome.com using the public key of the Let’s Encrypt Authority X3 certificate. If any part of the validation process fails, the certificate is invalid.

The information for the Certificate step is as follows

The public key of the certificate is shown as follows:

The signature of the certificate is as follows:

A certificate’s signature is used to ensure that the certificate has not been tampered with.

Server Key Exchange

The server sends it to the browser

The selected encryption suite is as follows: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 Elliptic Curve Diffie Hellman Ephemeral (ECDHE) is used for key negotiation. Elliptic curve encryption is involved here. Elliptic Curve Cryptography (ECC) is a public key encryption algorithm based on Elliptic Curve mathematics. The main advantage of ECC is that in some cases it uses smaller keys than other algorithms (such as RSA encryption algorithms) and provides an equivalent or higher level of security.

Ecdiffie-hellman Server Params Named Curve X25519 Server Key Exchange Its principle can be simply understood as follows:

Li Lei and Han Meimei are still writing letters

1. Li Lei uses his own private keyLet’s figure out the points on the elliptic curveAnd then put the base pointSend it to Han Meimei

2. Han Meimei uses her own private keyLet’s figure out the points on the elliptic curveSend it to Li Lei

3. According to the calculation rules of elliptic curve, both parties jointly calculate itIt’s the same thing.

This allows symmetric encryption, and the encrypted key has never been passed over the network. This is actually calculatedIt is also not the final symmetric encryption key, which can be understood as the premaster key. Finally, the real symmetric encryption key master key will be obtained through a calculation (PRF) based on the random number of the browser and the server.

The Pubkey in the figure above can be understood as a point on an ellipse calculated by the server.

The following content is mainly about some mathematical principles of elliptic curve encryption algorithm. If you are not interested, you can ignore it and go directly to the Client Key Exchange step.

DH algorithm

Diffie-hellman Key Exchange (DH) Enables two parties to create a key through an insecure channel without any prior information about the other party. This key can be used as a symmetric key to encrypt communication content in subsequent communication.

To explain briefly, suppose the two sides of the correspondence are Li Lei and Han Meimei

Prerequisites:

  • It’s Li Lei’s private key,It’s Han Meimei’s private key.
  • It’s a prime number. It’s public
  • One of the original roots is open

Negotiation process:

Step 1: Li Lei according to his private keyCalculate your own public key

Step 2: Li Leijiang,Send it to Han Meimei

The third step: Han Meimei according to his private keyCalculate your own public key

Step 4: Han Meimei puts her own public keySend it to Li Lei

Step 5: Li Lei calculates the key of symmetric encryption

Step 6: Han Meimei calculates the key of symmetric encryption

From the derivation of the figure above, we know the final calculationIt’s the same thing.

Specific examples:

Li Lei and Han Meimei agreement for useAs well as. Li Lei’s private keyTo calculate theSend it to Han Meimei.Han Meimei’s private keyTo calculate theSend it to Li Lei.Li lei to calculate Han Meimei calculates

You can see the key for symmetric encryptionIt’s not transmitted between Li Lei and Han Meimei, but the calculated result is the same.

ECC algorithm

Elliptic Curve Cryptography (ECC) is a public key encryption algorithm based on Elliptic Curve mathematics. The main advantage of ECC is that in some cases it uses smaller keys than other algorithms (such as RSA encryption algorithms) and provides an equivalent or higher level of security.

The equation of an elliptic curve is as follows:

The function graph of an elliptic curve is as follows:

You can see it’s symmetric about the X axis.

Elliptic curve operation

Points A and B on the curve intersect with the elliptic curve at point C, which is symmetric about axis A and intersects with the elliptic curve at point A+B.

So let’s take A special case of addition, if A is equal to B, if A (B) is the tangent point of the elliptic curve, and then we repeat this and we get A plus A is equal to 2A.

The point at which A is symmetric with respect to the X-axis is defined as minus A.

Here are two motion pictures that illustrate the process:

A+B = C

A+C = D

A+D = E

The overlap between A and B is shown as follows:

There are more than theIf I have a point on an elliptic curveAnd we can solve for that,And…But the other way around if we know thatAnd you want to figure outIs very difficult.

A finite field of elliptic curves

Elliptic curve encryption algorithm does not use real number field, but uses finite field, so we define elliptic curve on finite field.

withRepresents an elliptic curve equation, in a finite domainWhere, represents all the components in congruence (That satisfies this equationPoints.

Example: Add our curve is. then.

pointmeet.

So the pointIt’s on the curve.

So this is the discretized point. The process of using elliptic curve to encrypt communication is as follows (the reasoning process is presented here, which involves complex operation and requires more mathematical knowledge, and I am still studying) :

1. Li Lei chooses a curve, take a point on the elliptic curveAs a base point.

2. Li Lei selects a private keyAnd then generate the public key

3. Li LeibaAnd the public keyAnd bpPass to Han Meimei

4. Han Meimei gets the above information and codes the plaintext toOn a bitAnd generate a random number

5, Han Meimei calculation

6. Han MeimeiTo li lei

7. After Receiving the information, Li Lei calculatedThe result is point

because

Mathematical concept

Finite field

In mathematics, a finite field is a field containing a finite number of elements. Like any other field, a finite field is a set of well-defined operations that satisfy certain rules for addition, subtraction, multiplication and division. The most common example of a finite field is whenIs a pair of integers when it is primeModulus. The number of elements of a finite field is called itsorder.

Group of

A group in mathematics is a set that defines a binary operation (which we call addition, denoted by the sign +). If I want to set the

1. Closure: ifBelong to, thenAlso belong to;

2. Associative law;

3. There is an identity element (note: in binary operations, the identity element refers to the element that does not change its value when operating with any element. Take real numbers as an example, the identity element of multiplication is 1 and that of addition is 0)make;

4. Every element has an inverse element, that is, for any elementThere aremake;

If we add a fifth requirement:

5. Commutative law:

So this group is the Abelian group.

Curve25519

In cryptography, Curve25519 is an elliptic curve designed for use in the elliptic curve diffier-hermann (ECDH) key exchange method. It is one of the fastest ECC curves not covered by any known patent.

Curve25519 elliptic curve equation is:, using base point

ECDH

Taking Li Lei and Han Meimei as examples, the exchange content of DH is changed to the point on the curve

When Curve25519 is selected as an elliptic curve, the parameters are determined and so is G, so only the public keys of both sides can be exchanged.

Client Key Exchange

The browser sends it to the server

Similarly, Pubkey here can be interpreted as a point on an ellipse computed by the browser. This step is similar to Server Key Exchange in that it calculates the Key for symmetric encryption.

Symmetric encrypted communication

With this foundation, the browser can calculate a symmetric encryption key, and the server can calculate a symmetric encryption key, which is guaranteed to be the same even though the two keys are not transmitted over the network. Then you can use this key to encrypt and transfer it over the network.

The above is the basic process of TLS handshake, which ensures the security of data transmission over the network.

X.509

X.509 is the standard format for public key certificates in cryptography. X.509 certificates are used in many network protocols, including TLS/SSL, and in many off-line applications, such as electronic signature services. X.509 certificates contain public keys, identity information (such as network host names, organization names, or individual names), and signature information (either signed by the CA or self-signed). For a certificate that has been signed by a trusted certificate authority or that can be otherwise verified, the certificate owner can use the certificate and the corresponding private key to create secure communication and digitally sign the document.

tool

Online drawing tool

Refer to the article

SSL certificate CA authority

Digital Certificates and network security

What is a digital signature?

Elliptic curve encryption

Curve25519

A simple introduction to elliptic curve cryptography

TLS handshake process

Talk about the HTTPS

ECC elliptic curve encryption and decryption principle

ECC Elliptic curve encryption algorithm: Introduction

Beginner on the road: Elliptic curves and Group Theory on real numbers

Fundamentals of cryptography 2: Analysis of the principles of elliptic curve cryptography

HTTPS — key calculation in TLS

Finite field