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 {
	// 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 {
	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 {
	// 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 {
	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())
	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!")
  • 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
	return ecdsa.Verify(publicKey, hashText[:], &r, &s)


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())
	return buf

// test
func main() {
	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,, ”.

  • 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:


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:

        Version: 3 (0x2)
        Serial Number:
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=BE, O=GlobalSign nv-sa, CN=GlobalSign Organization Validation CA-SHA256-G2
            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=*
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Agreement
            Authority Information Access: 
                CA Issuers - URI:
                OCSP - URI:

            X509v3 Certificate Policies: 

            X509v3 Basic Constraints: 
            X509v3 CRL Distribution Points: 

                Full Name:

            X509v3 Subject Alternative Name: 
                DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*, DNS:*,,,,,,,,,,,,,,
            X509v3 Extended Key Usage: 
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 Subject Key Identifier: 
            X509v3 Authority Key Identifier: 

    Signature Algorithm: sha256WithRSAEncryption

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. 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. 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. 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;


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