Nodejs Advanced: The Security basics you need to master in the crypto module

Source: Internet
Author: User
Tags decrypt hmac asymmetric encryption

I. Overview of the article

In the Internet age, the amount of data on the Web is growing at an alarming rate every day. At the same time, various types of network security problems emerge. Today, as a developer, the importance of information security becomes increasingly important, and the security of the service is enhanced through technical means.

cryptoThe module is one of the core modules of Nodejs, which provides security-related functions such as digest operation, encryption, electronic signature and so on. Many beginners look at the long list of APIs and don't know how to get started, so it involves a lot of knowledge in the field of security.

This article focuses on the theoretical knowledge behind the API, mainly including the following:

    1. Digest (hash), digest-based Message Verification code (HMAC)
    2. Symmetric encryption, asymmetric encryption, electronic signatures
    3. Packet encryption mode
Ii. Abstract (hash)

Abstract (Digest): The length of the message as input, by running the hash function to generate a fixed-length output, this output is called a digest. It is often used to verify that the message is intact and not tampered with.

The digest operation is irreversible. In other words, the input is fixed and produces a fixed output. However, if the output is known, the input cannot be rolled back.

The pseudo code is as follows.

Digest = Hash (message)

The common summary algorithm and the corresponding output bits are as follows:

    • md5:128 bit
    • sha-1:160 bit
    • sha256:256 bit
    • sha512:512 bit

Examples in Nodejs:

var crypto = require(‘crypto‘);var md5 = crypto.createHash(‘md5‘);var message = ‘hello‘;var digest = md5.update(message, ‘utf8‘).digest(‘hex‘);console.log(digest);// 输出如下:注意这里是16进制// 5d41402abc4b2a76b9719d911017c592

Note: In various articles or literature, abstract, hash, hash these words are often mixed, leading to a lot of beginners to see a face, in fact, most of the time refers to is one thing, remember the definition of the face summary is good.

Third, MAC, HMAC

MAC (Message authentication code): Message authentication code to ensure the integrity of the data. The result of the operation depends on the message itself and the secret key.

Macs can be implemented in a number of different ways, such as HMAC.

HMAC (hash-based Message authentication Code): Can be roughly understood as a Hash function with a secret key.

Nodejs examples are as follows:

const crypto = require(‘crypto‘);// 参数一:摘要函数// 参数二:秘钥let hmac = crypto.createHmac(‘md5‘, ‘123456‘);let ret = hmac.update(‘hello‘).digest(‘hex‘);console.log(ret);// 9c699d7af73a49247a239cb0dd2f8139
Four, symmetric encryption, asymmetric encryption

encryption/Decryption : Given clear text, through a certain algorithm, generate encrypted ciphertext, the process is called encryption. The reverse is decryption.

Encryptedtext = Encrypt (plaintext) plaintext = Decrypt (encryptedtext)

secret key : in order to further enhance the security of the encryption/decryption algorithm, the secret key is introduced in the process of adding/decrypting. The secret key can be considered as the parameter of the encryption/decryption algorithm, in the case of known ciphertext, if you do not know the secret key used to decrypt, it will not be able to unlock the ciphertext.

Encryptedtext = Encrypt (plaintext, encryptkey) plaintext = Decrypt (Encryptedtext, Decryptkey)

The encryption algorithm can be divided into symmetric encryption and asymmetric encryption according to whether the secret keys used for encryption and decryption are the same.

1. Symmetric encryption

The secret key used for encryption and decryption is the same, that is encryptKey === decryptKey .

Common symmetric encryption algorithms: DES, 3DES, AES, Blowfish, RC5, idea.

Add and decrypt pseudo-code:

Encryptedtext = Encrypt (plaintext, key); Encryption plaintext = Decrypt (encryptedtext, key); Decrypt

2. Asymmetric encryption

Also known as public secret key encryption. The secret key used for encryption and decryption is different, that is encryptKey !== decryptKey .

The cryptographic key is exposed, called the public key. The decryption key is confidential, called the secret key.

Common asymmetric encryption algorithms: RSA, DSA, ElGamal.

Add and decrypt pseudo-code:

Encryptedtext = Encrypt (plaintext, publickey); Encryption plaintext = Decrypt (encryptedtext, Privitekey); Decrypt

3. Comparison and application

In addition to the secret key differences, there are differences in the speed of operation. Generally speaking:

    1. Symmetric encryption is faster than asymmetric encryption.
    2. Asymmetric encryption is often used to encrypt short texts, and symmetric encryption is often used to encrypt long text.

Both can be used together, such as the HTTPS protocol, which can be exchanged to generate a symmetric key during the handshake phase through RSA. In the subsequent communication phase, the data can be encrypted using a symmetric encryption algorithm, and the secret key is generated during the handshake phase.

Note: Symmetric key exchange is not necessarily through RSA, but also through similar DH to complete, this does not expand.

Five, digital signature

The purpose of the digital signature can be guessed roughly from the signature . The main functions are as follows:

    1. Verify that the information originates from a specific subject.
    2. Verify that the information is complete and not tampered with.

To achieve this, two processes are required:

    1. Sender: Generate signature.
    2. Receiver: Verifies the signature.
1. The sender generates the signature
    1. Calculates a summary of the original information.
    2. The digest is signed by the private key, and an electronic signature is obtained.
    3. Send the original information, electronic signature, to the receiving party.

Attached: Signature Pseudo-code

Digest = hash (message); Calculation Summary DigitalSignature = sign (digest, Privitekey); Calculate digital signatures

2. The receiver verifies the signature
    1. The electronic signature is solved by the public key, and the digest D1 is obtained. (The source body check fails if the solution is not open)
    2. Calculates the summary D2 of the original information.
    3. Compare D1, D2, if D1 equals D2, the original information is intact and not tampered with.

Attached: Signature Verification pseudo-code

Digest1 = Verify (DigitalSignature, PublicKey); Get Digest Digest2 = hash (message); Calculates the summary of the original information digest1 = = = DIGEST2//Verify Equality

3. Contrast Asymmetric encryption

Because of the particularity of the RSA algorithm, encryption/decryption, signature/verification looks particularly like, many students are easily confused. First of all, remember the following conclusions, there is time to explain in detail later.

    1. Encryption/decryption: Public key encryption, private key decryption.
    2. Signature/Authentication: Private key signature, public key authentication.
Six, block encryption mode, padding, initialization vector

The common symmetric encryption algorithms, such as AES and Des, are used in packet encryption mode. Of these, there are three key concepts that need to be mastered: patterns, fills, and initialization vectors.

Figure out these three points to know what the parameters of the symmetric cryptographic API for the Crypto module mean, out of the wrong to know how to troubleshoot.

1. Block Encryption mode

The so-called packet encryption is to split (longer) plaintext into fixed-length blocks, and then encrypt the split blocks according to a specific pattern.

Common packet encryption modes are: ECB (unsecured), CBC (most commonly used), CFB, OFB, CTR, etc.

In the simplest case of the ECB, split the messages into equal modules and encrypt them with a secret key.

Photo Source: Here, more about the packet encryption mode can refer to the wiki.

The following assumes that each block has a length of 128 bits

2. Initialization vector: IV

In order to enhance the security of the algorithm, the initialization vector (IV) is introduced into the partial packet cipher mode (CFB, OFB, CTR), which makes the results of encryption randomized. In other words, the results of encryption are different for the same piece of text, IV.

In CBC, for example, each block of data is then encrypted with the previous block or operation. For the first data block, it is either with IV or.

The size of IV is related to the size of the data block (128 bits), regardless of the length of the secret key.

, picture source here

3, fill: padding

The Block encryption mode requires the encryption of fixed-length blocks. After grouping is split, the last chunk length may be less than 128 bits, at which point it needs to be populated to meet the length requirements.

The Fill method has multiple. The common filling method is PKCS7.

Assuming that the grouping length is k bytes and the last packet length is k-last, you can see:

    1. Regardless of the length of the plaintext, the plaintext is populated before encryption (otherwise the decryption function cannot distinguish whether the last grouping is populated, because the last packet length is exactly equal to K)
    2. If the last packet length equals k-last = = = k, then the fill content is a complete grouping K k K (k bytes)
    3. If the last packet length is less than K-last < K, then the fill content is k-last mod k
                     01 -- if lth mod k = k-1                  02 02 -- if lth mod k = k-2                      .                      .                      .            k k ... k k -- if lth mod k = 0
Generally speaking
    1. Packet encryption: The plaintext is cut into fixed-length blocks (128 bits) before being encrypted.
    2. Several modes of packet encryption: ECB (unsecured), CBC (most commonly used), CFB, OFB, CTR.
    3. Padding (padding): Partial encryption mode, which needs to be populated in a specific way when the last block is less than 128 bits in length. (ECB, CBC needs to be populated, CFB, OFB, CTR does not need to be populated)
    4. Initialization vector (IV): Part of the encryption mode (CFB, OFB, CTR) will either perform or manipulate the plaintext block with the previous ciphertext block. For the first plaintext block, there is no previous ciphertext block, so it is necessary to provide an initialization vector IV (which is used as a cipher block before the first clear block). In addition, the IV also allows the encryption results to be randomized.
Seven, written in the back

Crypto module involves a lot of safety knowledge, space constraints, there is no way to unfold. In order to explain the convenience, part of the content may not be rigorous, if there are mistakes please point out.

Have questions or interested students welcome message exchange, can also pay attention to my GitHub focus on the latest content update "Nodejs-learning-guide".

Viii. RELATED LINKS

Nodejs Study Notes

Cryptographic hash function

Hash-based Message Authentication Code

HMAC vs MAC functions

What is the difference between MAC and HMAC?

Block cipher Mode of operation

Which of the RSA's public and private keys is used for encryption and which is used for decryption? -Liu Weihan-Learn the crisp answer

Nodejs Advanced: The Security basics you need to master in the crypto module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.