Cryptography summary

Keywords: DNS SSL SHA1 less

1, Digital signature

1.1 relationship between digital signature and asymmetric encryption

In fact, there is a very close relationship between digital signature and asymmetric encryption. In short, digital signature is realized by using asymmetric encryption in reverse. Let's summarize the usage of the key into a table:

Private key Public key
Asymmetric encryption Used when the recipient decrypts Use when sender encrypts
digital signature Used when the signer generates a signature Used when verifying signature
holder Individual holding Anyone can hold it

1.2 two ways of digital signature

  • Method 1: sign the message directly
    Because the asymmetric encryption algorithm is very slow, it will be very time-consuming to encrypt the message in mode one, which is not recommended.
  • Method 2: sign the message hash value
    In the second mode, it is not necessary to encrypt the whole message, but only to use the one-way hash function to find the hash value of the message, and then encrypt the hash value. No matter how long the message is, the length of the generated hash value is fixed, so the second method is recommended in practical application.

1.3 use steps of digital signature

Let's use the story of Alice and Bob as an example, and assume that Alice sends remittance to Bob (as shown below).

Step 1: Alice uses the one-way hash function to calculate the hash value of the message;
Step 2: Alice encrypts (signs) the hash value with her private key;
Step 3: Alice sends the message and signature to Bob;
Step 4: Bob uses Alice public key to decrypt the received signature, and gets hash value 1;
Step 5: Bob uses the one-way hash function to calculate the hash value 2 of the received message;
Step 6: Bob compares hash value 1 with hash value 2. If the two hash values are the same, it means that the message is sent by Alice; if the two hash values are different, it means that the message is not sent by Alice;

1.4 digital signature through RSA

  • The implementation steps of digital signature are as follows:
    Step 1: generate a secret key pair and save it to disk;
    Step two: prepare the original data;
    The third step: it carries out hash operation, and finally generates a hash value;
    Step 4: use asymmetric private key to encrypt hash value, which is called signature;
    Step 5: send the signature and original content to the other party;

  • Implementation steps of data validation:
    The first step is to receive the original data and digital signature;
    Step 2: hash the original data until a new hash value;
    The third step: decrypt the signature with public key, and finally get a hash value;
    Step 4: compare the two hash values. If they are equal, the data sent has not been changed;

Example code:

// Generate private and public keys
func generateKey() {
	//==============Generate private key=============
	// 1. Use GenerateKey method in rsa to generate private key
	privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}
	// 2. Serialize the ras private key to ASN.1 DER encoded string through x509 standard
	derText := x509.MarshalPKCS1PrivateKey(privateKey)
	// 3. Set the private key string to the pem format block
	block := pem.Block{
		Type: "rsa private key",
		Bytes: derText,
	}
	// 4. Encode the set data through pem and write it to the disk file
	file, err := os.Create("private.pem")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	pem.Encode(file, &block)

	//==============Generate public key=============
	// 1. Extract the public key information from the obtained private key object
	publicKey := privateKey.PublicKey
	// 2. Serialize the rsa public key to string through x509 standard
	derText, err = x509.MarshalPKIXPublicKey(&publicKey)
	if err != nil {
		panic(err)
	}
	// 3. Set the public key string to the pem format block
	block = pem.Block {
		Type: "rsa public key",
		Bytes: derText,
	}
	// 4. Encode the set data through pem and write it to the disk file
	file, err = os.Create("public.pem")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	pem.Encode(file, &block)
}

// Read key file contents
func ReadKeyFile(keyFile string) []byte {
	file, err := os.Open(keyFile)
	if err != nil {
		panic("Public key file does not exist!")
	}
	defer file.Close()
	fileInfo, err := file.Stat()
	if err != nil {
		panic("file.Stat err!")
	}
	buf := make([]byte, fileInfo.Size())
	file.Read(buf)
	return buf
}

// RSA signature
func SignatureRSA(plainText []byte, priKeyFile string) []byte {
	// Calculate signature content and hash to get a hash value
	res := sha512.Sum512(plainText)
	// Read the contents of the private key file
	buf := ReadKeyFile(priKeyFile)
	// Using PEM decoding to get the pem.Block structure
	block, _ := pem.Decode(buf)
	// Use x509 to parse the data into the private key structure to get the private key
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		panic("x509.ParsePKCS1PrivateKey err!")
	}
	// Using functions in rsa to sign hash values
	sigText, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA512, res[0:len(res)])
	if err != nil {
		panic("rsa.SignPKCS1v15 err!")
	}
	return sigText
}

// Signature verification
func VerifyRSA(plainText, sigText []byte, pubKeyFile string) bool {
	// Hash the original data until a new hash value
	res := sha512.Sum512(plainText)
	// Open the disk public key file and read out the contents of the public key file
	buf := ReadKeyFile(pubKeyFile)
	// Using PEM decoding to get the pem.Block structure
	block, _  := pem.Decode(buf)
	// Use x509 to parse the bytes variable data of pem.Block to get an interface
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic("x509.ParsePKIXPublicKey err!")
	}
	//Make type assertion to get public key
	publicKey, ok := pub.(*rsa.PublicKey)
	if !ok {
		panic("pub is not a public key!")
	}
	// Signature authentication through rsa.VerifyPKCS1v15 function
	err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA512, res[:], sigText)
	// Compare hash values
	return err == nil
}

1.5 digital signature by elliptic curve

The use of Elliptic curve cryptography (ECC) in cryptography was independently proposed by Neal Koblitz and Victor Miller in 1985. The main advantage of ECC is that in some cases, it uses a smaller key than other encryption algorithms and provides a higher level of security. ECC 164 bit key is equivalent to the security strength provided by RSA 1024 bit key, with less computation and faster processing speed. At present, China's second generation ID card is using 256 bit Elliptic curve cryptography, and the virtual currency bitcoin also chooses ECC as the encryption algorithm.

According to FIPS186-2 standard of the United States, it is recommended to use elliptic curves on five prime fields. The five prime modulus are respectively:
P192 = 2192 - 264 - 1
P224 = 2224 - 296 + 1
P256 = 2256 - 2224 + 2192 - 296 -1
P384 = 2384 - 2128 - 296 + 232 -1
P512 = 2512 - 1

  • Implementation steps of ECC signature:
    Step 1: read the private key;
    The second step: using pem to decode;
    Step 3: restore the private key with x509 to get the PrivateKey structure object;
    Step four: hash the original data to get the hash value;
    Step five: use private key to sign hash value;
/**
 * ECC autograph
 * Parameter 1: data to be signed
 * Parameter 2: private key file
 * Return value: coordinates of elliptic curve
 * /
func EccSignature(plainText []byte, priKeyFile string) (rText, sText []byte) {
	// 1. Open the private key file and read the private key
	buf := ReadKey(priKeyFile)
	// 2. Decoding with pem
	block, _ := pem.Decode(buf)
	// 3. Use x509 to restore the private key
	privateKey, err := x509.ParseECPrivateKey(block.Bytes)
	if err != nil {
		panic("x509.ParseECPrivateKey err!")
	}
	// 4. Hash the original data to get the hash value
	hashText := sha1.Sum(plainText)
	// 5. Digital signature
	r, s, err := ecdsa.Sign(rand.Reader, privateKey, hashText[:])
	if err != nil {
		panic("ecdsa.Sign err!")
	}
	// 6. Format r, s
	rText, err = r.MarshalText()
	if err != nil {
		panic("r.MarshalText err!")
	}
	sText, err = s.MarshalText()
	if err != nil {
		panic("s.MarshalText err!")
	}
	return
}
  • Implementation steps of ECC verification:
    Step 1: read the public key;
    The second step: using pem to decode;
    The third step: use x509 to restore the public key and get the public key structure object;
    Step four: hash the original data to get the hash value;
    Step 5: perform signature verification;
/**
 * ECC Signature verification
 * Parameter 1: Certified data
 * Parameters 2 and 3: formatted elliptic curve coordinates
 * Parameter 4: public key file
 * Return value: validation result, true Representative verification successful, false Representative verification failed
 * /
func E
func EccVerify(plainText, rText, sText []byte, pubKeyFile string) bool {
	// 1. Open the public key file and read the public key
	buf := ReadKey(pubKeyFile)
	// 2.pem decoding
	block, _ := pem.Decode(buf)
	// 3. Use x509 to restore public key
	key, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic("x509.ParsePKIXPublicKey err!")
	}
	publicKey, ok := key.(*ecdsa.PublicKey)
	if !ok {
		panic("key is not a ecdsa public key.")
	}
	// 4. Hash the original data
	hashText := sha1.Sum(plainText)
	// 5. Signature authentication
	var r, s big.Int
	// Convert rText and sText to big.Int data
	r.UnmarshalJSON(rText)
	s.UnmarshalJSON(sText)
	return ecdsa.Verify(publicKey, hashText[:], &r, &s)
}

Test:

func GenerateKey() {
	//----------------Generate private key--------------
	// 1. Using ecdsa to generate key pair
	privateKey, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
	if err != nil {
		panic("ecdsa.GenerateKey err!")
	}
	// 2. Serialize with x509
	derText, err := x509.MarshalECPrivateKey(privateKey)
	if err != nil {
		panic("x509.MarshalECPrivateKey err!")
	}
	// 3. Write the detext into the pem.Block block
	block := pem.Block{
		Type:    "ecdsa private key",
		Bytes: derText,
	}
	// 4. Using pem coding
	file, err := os.Create("ecc_private.pem")
	if err != nil {
		panic("os.Create err!")
	}
	defer file.Close()
	pem.Encode(file, &block)

	//----------------Generate public key--------------
	// 1. Get the public key
	publicKey := privateKey.PublicKey
	// 2. Serialize the public key with x509
	derText, err = x509.MarshalPKIXPublicKey(&publicKey)
	if err != nil {
		panic("x509.MarshalPKIXPublicKey err!")
	}
	// 3. Put the detext in the pem.Block block
	block = pem.Block{
		Type : "ecdsa public key",
		Bytes : derText,
	}
	// 4. Using pem coding
	file, err = os.Create("ecc_public.pem")
	if err != nil {
		panic("os.Create err!")
	}
	defer file.Close()
	pem.Encode(file, &block)
}

// Read key file contents
func ReadKey(keyFile string) []byte {
	file, err := os.Open(keyFile)
	if err != nil {
		panic("file does not exist!")
	}
	defer file.Close()
	fileInfo, err := file.Stat()
	if err != nil {
		panic("file.Stat err!")
	}
	buf := make([]byte, fileInfo.Size())
	file.Read(buf)
	return buf
}

// test
func main() {
	GenerateKey()
	src := []byte("hello world")
	rText, sText := EccSignature(src, "ecc_private.pem")
	isSucc := EccVerify(src, rText, sText, "ecc_public.pem")
	fmt.Printf("Whether the signature authentication is successful:%t\n", isSucc)
}

Two. Certificate

The premise of using digital signature correctly is that the public key used to verify the signature must belong to the real sender. Even if the digital signature algorithm is more powerful, if the public key you get is forged, then the digital signature will be completely invalid. In order to be able to confirm whether the public key we get is legal, we need to use a certificate.

2.1 what is a certificate

The so-called certificate is the file obtained by signing the public key as a message by a trusted third party (such as ca). It can be understood as follows:
Certificate = public key + digital signature Certificate = public key + digital signature Certificate = public key + digital signature

The certificate is very similar to the driver's license, which contains personal information such as name, organization, email address and the public key belonging to the person, and is digitally signed by the certification authority (such as ca). As long as we see the certificate, we can know that the certification authority determines that the public key really belongs to this person.

Many people may not have heard of the certification authority. The certification authority is the person or organization that can determine that "the public key really belongs to this person" and generate a digital signature. Among them, there are international organizations and organizations established by the government, as well as general enterprises that make profits by providing certification services. Among them, the world's largest PKI / CA operator is the world's first digital certificate authority.

2.2 application scenario of certificate

The following figure shows the scenario in which Alice sends a ciphertext to Bob. The Bob's public key used in generating the ciphertext is obtained through the certification authority.

Step 1: Bob generates the secret key pair;
Step 2: Bob registers his public key with Trent;
Step three: Trent uses his private key to sign Bob's public key and generate certificate;
Step 4: Alice downloads the certificate, which contains the digital signature of Trent certification authority and Bob's public key;
Step 5: Alice uses the public key of the certification authority to verify the digital signature and confirm the validity of Bob's public key;
Step 6: Alice encrypts the message with Bob's public key to get the ciphertext, and then sends it to Bob;
Step 7: Bob uses his private key to decrypt the ciphertext and get the message sent by Alice;

2.3 Certificate Standard Specification x.509

10. 509 is the format standard of public key certificate in cryptography. It is a standard jointly formulated by ITU (International Telecommunication Union) and ISO (International Organization for Standardization). 10. 509 certificate has been used in many Internet protocols including TLS/SSL, and it is also used in many non online application scenarios, such as electronic signature service. An X.509 certificate is a collection of standard fields that contain information about a user or device and its corresponding public key. 10. The 509 standard defines what information should be included in the certificate and describes the data format of the information. Generally speaking, a digital certificate may include basic data (version, serial number), signed object information (signature algorithm type, signer information, validity period, signee, issued public key), digital signature of CA, etc.

2.3.1 certificate specification

At present, there are different versions of X.509, such as X.509 V2 and x.509 v3, which are relatively new versions at present. They are all functional extensions based on the original version (X.509 V1). Each version must contain the following information:

  • Version number:
    Used to distinguish different version numbers of X.509.

  • Serial number:
    A unique number assigned by a CA to each certificate to track and revoke certificates. As long as you have issuer information and serial number, you can uniquely identify a certificate, which can't exceed 20 bytes at most.

  • Signature algorithm:
    It is used to specify the signature algorithm (such as sha256-with-RSA-Encryption, ccdsa-with-SHA2S6) used when issuing certificate with CA.

  • Issuer:
    Identification information of the issuing unit.

  • Term of validity:
    The valid time of the certificate includes two dates: the effective date of the certificate and the expiration date and time of the certificate. Valid between the two times specified.

  • Main body:
    Identity information of the certificate owner. For example, "C=CN, ST=Beijing, L=Beijing, O=org.example.com, CN=ca.org. example.com ”.

  • Public key information of principal:
    Include the public key that is proved to be valid and the name of the method that uses the public key.

  • Issuer's unique number:
    Unique information representing the issuer, only supported by versions 2 and 3.

  • Unique number of the subject
    Represents the unique information of the owning certificate entity, only supported by version 2 and 3.

  • x.509 extension:

    • Subject Key Identifier: the secret key identifier of an entity, which distinguishes multiple pairs of secret keys of an entity;
    • Basic Constraints: indicates whether it belongs to CA;
    • Authority Key Identifier: the public key identifier of the certificate issuer;
    • CRL Distribution Points: the issuing address of the revocation file;
    • Key Usage: the usage or function information of the certificate.

In addition, the issuer of the certificate also needs to use its own private key to add signature to the content of the certificate to prevent others from tampering with the content of the certificate.

2.3.2 form of certificate

10. In the 509 specification, PEM(Privacy Enhanced Mail) format is generally recommended to store certificate related files. The file name suffix of the certificate file is usually. crt or. cer. The file name suffix of the corresponding private key file is generally. Key. The file name suffix of the certificate request file is. csr. Sometimes pem is used as the suffix of file name.

The following shows the contents of a pem format certificate file:

-----BEGIN CERTIFICATE-----
MIIDyjCCArKgAwIBAgIQdZfkKrISoINLporOrZLXPTANBgkqhkiG9w0BAQsFADBn
MSswKQYDVQQLDCJDcmVhdGVkIGJ5IGh0dHA6Ly93d3cuZmlkZGxlcjIuY29tMRUw
EwYDVQQKDAxET19OT1RfVFJVU1QxITAfBgNVBAMMGERPX05PVF9UUlVTVF9GaWRk
bGVyUm9vdDAeFw0xNzA0MTExNjQ4MzhaFw0yMzA0MTExNjQ4MzhaMFoxKzApBgNV
BAsMIkNyZWF0ZWQgYnkgaHR0cDovL3d3dy5maWRkbGVyMi5jb20xFTATBgNVBAoM
DERPX05PVF9UUlVTVDEUMBIGA1UEAwwLKi5iYWlkdS5jb20wggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQDX0AM198jxwRoKgwWsd9oj5vI0and9v9SB9Chl
gZEu6G9ZA0C7BucsBzJ2bl0Mf6qq0Iee1DfeydfEKyTmBKTafgb2DoQE3OHZjy0B
QTJrsOdf5s636W5gJp4f7CUYYA/3e1nxr/+AuG44Idlsi17TWodVKjsQhjzH+bK6
8ukQZyel1SgBeQOivzxXe0rhXzrocoeKZFmUxLkUpm+/mX1syDTdaCmQ6LT4KYYi
soKe4f+r2tLbUzPKxtk2F1v3ZLOjiRdzCOA27e5n88zdAFrCmMB4teG/azCSAH3g
Yb6vaAGaOnKyDLGunW51sSesWBpHceJnMfrhwxCjiv707JZtAgMBAAGjfzB9MA4G
A1UdDwEB/wQEAwIEsDATBgNVHSUEDDAKBggrBgEFBQcDATAWBgNVHREEDzANggsq
LmJhaWR1LmNvbTAfBgNVHSMEGDAWgBQ9UIffUQSuwWGOm+o74JffZJNadjAdBgNV
HQ4EFgQUQh8IksZqcMVmKrIibTHLbAgLRGgwDQYJKoZIhvcNAQELBQADggEBAC5Y
JndwXpm0W+9SUlQhAUSE9LZh+DzcSmlCWtBk+SKBwmAegbfNSf6CgCh0VY6iIhbn
GlszqgAOAqVMxAEDlR/YJTOlAUXFw8KICsWdvE01xtHqhk1tCK154Otci60Wu+tz
1t8999GPbJskecbRDGRDSA/gQGZJuL0rnmIuz3macSVn6tH7NwdoNeN68Uj3Qyt5
orYv1IFm8t55224ga8ac1y90hK4R5HcvN71aIjMKrikgynK0E+g45QypHRIe/z0S
/1W/6rqTgfN6OWc0c15hPeJbTtkntB5Fqd0sfsnKkW6jPsKQ+z/+vZ5XqzdlFupQ
29F14ei8ZHl9aLIHP5s=
-----END CERTIFICATE-----

PEM format is stored in text mode. Generally, it includes head and tail tags and content blocks, which are encoded by Base64.

By restoring the certificate data, you can get the following:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            10:e6:fc:62:b7:41:8a:d5:00:5e:45:b6
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=BE, O=GlobalSign nv-sa, CN=GlobalSign Organization Validation CA-SHA256-G2
        Validity
            Not Before: Nov 21 08:00:00 2016 GMT
            Not After : Nov 22 07:59:59 2017 GMT
        Subject: C=US, ST=California, L=San Francisco, O=Wikimedia Foundation, Inc., CN=*.wikipedia.org
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub: 
                    04:c9:22:69:31:8a:d6:6c:ea:da:c3:7f:2c:ac:a5:
                    af:c0:02:ea:81:cb:65:b9:fd:0c:6d:46:5b:c9:1e:
                    ed:b2:ac:2a:1b:4a:ec:80:7b:e7:1a:51:e0:df:f7:
                    c7:4a:20:7b:91:4b:20:07:21:ce:cf:68:65:8c:c6:
                    9d:3b:ef:d5:c1
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Agreement
            Authority Information Access: 
                CA Issuers - URI:http://secure.globalsign.com/cacert/gsorganizationvalsha2g2r1.crt
                OCSP - URI:http://ocsp2.globalsign.com/gsorganizationvalsha2g2

            X509v3 Certificate Policies: 
                Policy: 1.3.6.1.4.1.4146.1.20
                  CPS: https://www.globalsign.com/repository/
                Policy: 2.23.140.1.2.2

            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 CRL Distribution Points: 

                Full Name:
                  URI:http://crl.globalsign.com/gs/gsorganizationvalsha2g2.crl

            X509v3 Subject Alternative Name: 
                DNS:*.wikipedia.org, DNS:*.m.mediawiki.org, DNS:*.m.wikibooks.org, DNS:*.m.wikidata.org, DNS:*.m.wikimedia.org, DNS:*.m.wikimediafoundation.org, DNS:*.m.wikinews.org, DNS:*.m.wikipedia.org, DNS:*.m.wikiquote.org, DNS:*.m.wikisource.org, DNS:*.m.wikiversity.org, DNS:*.m.wikivoyage.org, DNS:*.m.wiktionary.org, DNS:*.mediawiki.org, DNS:*.planet.wikimedia.org, DNS:*.wikibooks.org, DNS:*.wikidata.org, DNS:*.wikimedia.org, DNS:*.wikimediafoundation.org, DNS:*.wikinews.org, DNS:*.wikiquote.org, DNS:*.wikisource.org, DNS:*.wikiversity.org, DNS:*.wikivoyage.org, DNS:*.wiktionary.org, DNS:*.wmfusercontent.org, DNS:*.zero.wikipedia.org, DNS:mediawiki.org, DNS:w.wiki, DNS:wikibooks.org, DNS:wikidata.org, DNS:wikimedia.org, DNS:wikimediafoundation.org, DNS:wikinews.org, DNS:wikiquote.org, DNS:wikisource.org, DNS:wikiversity.org, DNS:wikivoyage.org, DNS:wiktionary.org, DNS:wmfusercontent.org, DNS:wikipedia.org
            X509v3 Extended Key Usage: 
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 Subject Key Identifier: 
                28:2A:26:2A:57:8B:3B:CE:B4:D6:AB:54:EF:D7:38:21:2C:49:5C:36
            X509v3 Authority Key Identifier: 
                keyid:96:DE:61:F1:BD:1C:16:29:53:1C:C0:CC:7D:3B:83:00:40:E6:1A:7C

    Signature Algorithm: sha256WithRSAEncryption
         8b:c3:ed:d1:9d:39:6f:af:40:72:bd:1e:18:5e:30:54:23:35:
         ...

2.3.3 CA certificate

CA is the abbreviation of Certificate Authority, also known as "Certificate Authority center". It is a third-party organization responsible for managing and issuing certificates. Generally speaking, CA must be trusted and recognized by all industries and the public. So it must have enough authority.

2.3.3.1 CA certificate

CA certificate, as the name implies, is the certificate issued by ca. Anyone can find a tool to make a certificate. But the certificate made by ourselves is not authoritative, so it will not be recognized by others.

2.3.3.2 certificate trust chain

Trust can be established between multiple certificates. For example, one certificate can prove that another certificate is authentic. Moreover, the trust relationship between certificates can be nested. For example, C trusts a and B, a trusts A1 and A2, B trusts B1 and B2, and so on. This is called the certificate trust chain (as shown below).

The certificate at the top is called the root certificate. In addition to the root certificate, other certificates rely on a higher level certificate to prove their reliability. Root certificate is the foundation of the whole certificate system security. If there is a problem with the root certificate in a certificate system, other certificates trusted by the root certificate will no longer be trusted.

2.3.3.3 function of certificate

  • Verify that the site is trusted
    Generally, if we visit some sensitive web pages (such as the page where the user logs in), the protocol will use HTTPS instead of HTTP. In addition to the encryption mechanism, HTTPS has a set of certificate mechanism. Certificate to ensure that a site is indeed a site. With a certificate, when your browser visits an HTTPS site, it will verify the CA certificate on that site (similar to the official seal of the verification reference letter). If the browser finds that there is no problem with the certificate (the certificate is trusted by a root certificate, the domain name bound on the certificate is consistent with the domain name of the website, and the certificate does not expire), the page will be opened directly; otherwise, the browser will give a warning to tell you that there is a problem with the certificate of the website.

  • Verify that a file is trusted
    The digital signature of a file by certificate can be used to verify whether a file has been tampered with.

2.4 public key infrastructure (PKI)

The specification of certificate is not enough to support the practical application of public key. We need many other specifications, such as who should issue the certificate, how to issue it, how to void the certificate when the private key leaks, and what format should be used for data exchange between computers.

2.4.1 what is public key infrastructure

Public key infrastructure (KPI) is a general term of a series of specifications formulated to make more effective use of public key. For example, the PKCS series specification developed by RSA company is also a kind of PKI, and there are many PKI related documents in RFC. In addition, such a specification as X.509 is also a kind of PKI. When developing PKI program, the API interface and specification design book written by each company is also the relevant specification of PKI.

National, local governments, hospitals, libraries and other public organizations and groups can establish certification bodies to achieve PKI, companies can also achieve PKI in-house for business needs, and even individuals can build PKI for the purpose of experiments.

2.4.2 composition of PKI

The components of PKI are as follows:

  • User: the person using PKI. There are two kinds of users: one is the person who wants to use PKI to register his public key (such as bob); the other is the person who wants to use the registered public key (such as Alice);
  • CA: the person who manages the certificate (such as Trent);
  • Warehouse: the warehouse is also called certificate directory, which is a database for storing certificates. PKI users can obtain certificates from the warehouse when they need to;

3, SSL/TLS

SSL (Secure Socket Layer) and TLS (Transport Layer Security) are the most widely used cryptographic communication methods in the world. SSL/TLS can be used to authenticate the communication object and ensure the confidentiality of the communication content. For example, when inputting the bank card account number in online banking, the browser will use SSL/TLS for password communication.

In SSL/TLS, symmetric cryptography, message authentication code, public key cryptography, digital signature, pseudo-random number generator and other cryptography technologies that have been studied before are used synthetically. Strictly speaking, SSL is different from TLS. TLS is the same as the subsequent version of SSL. But most of the time, SSL and TLS are both available, so SSL/TLS is usually written uniformly.

3.1 main functions of SSL / TLS

  • Authenticating users and servers to ensure that their data are sent to the correct location;
  • Encrypt the data sent and protect the data;
  • Ensure the integrity of data in the process of transmission;

3.2 http and https protocol

SSL/TLS is a layer of encryption based on the data transmission layer, which can ensure the security of the upper layer information transmission. We know that HTTP is not secure. The browser sends data to the server through HTTP protocol, and the data is sent directly to the server through clear text. Therefore, we can use SSL/TLS as the protocol to encrypt communication, and then host HTTP on top of it (as shown in the figure below).

By overlaying the two protocols, we can encrypt HTTP communication to prevent eavesdropping. When communicating over SSL/TLS, the URL does not start with http: / /, but with https: / /.

SSL/TLS can host many other protocols besides HTTP communication. For example, both the SMTP used to send mail and the POP3 used to receive mail can be hosted using SSL/TLS. In this case, SSL/TLS can protect the received and sent mail. The structure of using SSL/TLS to host HTTP, SMTP and POP3 is as follows:

3.3 https transmission process


Step 1: the client sends an https request and connects to port 443 of the server;
Step 2: the server sends the public key and digital signature (certificate) to the client;
The third step: the client starts to parse the certificate and verify the validity of the certificate (such as whether the public key is valid, whether the certificate expires, etc.);
Step 4: if there is no problem with the certificate, the client uses the random number generator to encrypt the generated random number asymmetrically through the certificate, and sends the encrypted ciphertext to the server;
Step five: the server uses the private key to decrypt it asymmetrically, and gets the random number;
Step 6: the server encrypts the response data symmetrically through the random number and sends it to the client;
Step 7: the client decrypts the response data office with the random number generated before, and obtains the clear text;

3.4 differences between HTTP and https

  1. http does not need a certificate, but https protocol needs to apply for a certificate from ca. generally, there are few free certificates, so it needs a certain fee;
  2. http is hypertext transmission protocol, information is plaintext transmission, and https is ssl/tls encryption transmission protocol with security;
  3. http and https use totally different connection methods and different ports. The former is 80 and the latter is 443;
  4. The connection of http is very simple and stateless, and HTTPS protocol is constructed by SSL/TLS+HTTP protocol for encrypted transmission;

3.5 advantages and disadvantages of HTTPS

  • Advantages of https:
  1. Using https protocol can ensure that the data is sent to the right client or server;
  2. https protocol is a network protocol constructed by ssl+http protocol, which can carry out encrypted transmission and identity authentication. It is more secure than http protocol, which can prevent data from being stolen and changed in the transmission process, and ensure the integrity of data;
  3. https is the most secure solution under the current architecture. Although it is not absolutely secure, it greatly increases the cost of man in the middle attack;
  4. For sites with the same weight, the page using https protocol is more secure and will be given priority in ranking.
  • Disadvantages of https:
  1. The handshake phase of https protocol is time-consuming, which will prolong the loading time of the page;
  2. https connection cache is not as efficient as http;
  3. ssl/tls certificate needs money, and the more powerful the certificate, the higher the cost;
  4. ssl/tls certificates usually need to be bound to IP, and cannot bind multiple domain names on the same IP;
  5. The range of encryption of https protocol is also limited, which has little effect on hacker attack, denial of service attack, server hijacking and so on. Moreover, the credit chain system of ssl certificate is not secure, especially when some countries can control ca root certificate, man in the middle attack is as feasible;
115 original articles published, 45 praised, 30000 visitors+
Private letter follow

Posted by thomas777neo on Mon, 09 Mar 2020 03:43:26 -0700