Home > Web Front-end > JS Tutorial > body text

Sharing of basic security knowledge in Nodejs crypto module

小云云
Release: 2018-01-03 14:40:05
Original
1600 people have browsed it

This article mainly shares with you Nodejs advanced: the basic security knowledge you need to master in the crypto module. I hope it can help everyone. In the Internet era, the amount of data on the network is growing at an alarming rate every day. At the same time, various network security issues emerge one after another. Today, as the importance of information security becomes increasingly prominent, as a developer, you need to strengthen your understanding of security and enhance the security of services through technical means.

crypto The module is one of the core modules of nodejs. It provides security-related functions, such as digest operations, encryption, electronic signatures, etc. Many beginners don't know how to get started with the long API list, so it involves a lot of knowledge in the security field.

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

  1. Summary (hash), summary-based message verification code (HMAC)

  2. Symmetric encryption, asymmetric encryption, electronic signature

  3. Block encryption mode

This article is excerpted from "Nodejs Learning Notes", for more chapters and updates, please visit the github homepage address.

2. Digest (hash)

Digest (digest): Take a message with a variable length as input and run the hash function to generate a fixed-length output. This output is called a digest. Usually used to verify that the message is complete and has not been tampered with.

The digest operation is irreversible. In other words, when the input is fixed, a fixed output is produced. But if the output is known, the input cannot be deduced.

The pseudo code is as follows.

digest = Hash(message)

Common digest algorithms and corresponding output digits are as follows:

  • MD5: 128 bits

  • SHA-1: 160 bits

  • SHA256: 256 bits

  • ##SHA512: 512 bits

Example 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
Copy after login
Note: In various articles or documents, the words abstract, hash, and hash are often used interchangeably, causing many beginners to read I looked confused, but in fact, most of the time it refers to the same thing. Just remember the definition of abstract above.
3. MAC, HMAC

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

MAC can be implemented in many different ways, such as HMAC.

HMAC (Hash-based Message Authentication Code): It 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
Copy after login
4. Symmetric encryption, asymmetric encryption

Encryption/decryption: Given plain text, through a certain algorithm, The process of generating encrypted ciphertext 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, add/ The secret key is introduced during the decryption process. The secret key can be regarded as a parameter of the encryption/decryption algorithm. When the ciphertext is known, if the secret key used for decryption is not known, the ciphertext cannot be decrypted.

encryptedText = encrypt(plainText, encryptKey)
plainText = decrypt(encryptedText, decryptKey)
Encryption algorithms can be divided into ## based on whether the secret keys used for encryption and decryption are the same. #Symmetric encryption

, Asymmetric encryption. 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.

Pseudocode for adding and decrypting:

encryptedText = encrypt(plainText, key); // Encryption

plainText = decrypt(encryptedText, key); // Decryption

2. Asymmetric encryption

is also called public key encryption. The secret keys used for encryption and decryption are different, that is,

encryptKey !== decryptKey

. The encryption key is public and is called the public key. The decryption key is kept secret and is called a secret key.

Common asymmetric encryption algorithms: RSA, DSA, ElGamal.

Pseudocode for adding and decrypting:

encryptedText = encrypt(plainText, publicKey); // Encryption

plainText = decrypt(encryptedText, privateKey); // Decryption

3. Comparison and application

In addition to the difference in secret keys, there is also a difference in computing speed. Generally speaking:

    Symmetric encryption is faster than asymmetric encryption.
  1. Asymmetric encryption is usually used to encrypt short text, and symmetric encryption is usually used to encrypt long text.
  2. The two can be used in combination, such as the HTTPS protocol, which can generate symmetric keys through RSA exchange during the handshake phase. 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 does not necessarily need to be done through RSA, but can also be done through something like DH, which will not be expanded here.

5. Digital signature

From

signature

, you can roughly guess the purpose of digital signature. The main functions are as follows:

    Confirm that the information comes from a specific subject.
  1. 确认信息完整、未被篡改。

为了达到上述目的,需要有两个过程:

  1. 发送方:生成签名。

  2. 接收方:验证签名。

1、发送方生成签名

  1. 计算原始信息的摘要。

  2. 通过私钥对摘要进行签名,得到电子签名。

  3. 将原始信息、电子签名,发送给接收方。

附:签名伪代码

digest = hash(message); // 计算摘要
digitalSignature = sign(digest,  priviteKey); // 计算数字签名

2、接收方验证签名

  1. 通过公钥解开电子签名,得到摘要D1。(如果解不开,信息来源主体校验失败)

  2. 计算原始信息的摘要D2。

  3. 对比D1、D2,如果D1等于D2,说明原始信息完整、未被篡改。

附:签名验证伪代码

digest1 = verify(digitalSignature, publicKey); // 获取摘要
digest2 = hash(message); // 计算原始信息的摘要
digest1 === digest2 // 验证是否相等

3、对比非对称加密

由于RSA算法的特殊性,加密/解密、签名/验证 看上去特别像,很多同学都很容易混淆。先记住下面结论,后面有时间再详细介绍。

  1. 加密/解密:公钥加密,私钥解密。

  2. 签名/验证:私钥签名,公钥验证。

六、分组加密模式、填充、初始化向量

常见的对称加密算法,如AES、DES都采用了分组加密模式。这其中,有三个关键的概念需要掌握:模式、填充、初始化向量。

搞清楚这三点,才会知道crypto模块对称加密API的参数代表什么含义,出了错知道如何去排查。

1、分组加密模式

所谓的分组加密,就是将(较长的)明文拆分成固定长度的块,然后对拆分的块按照特定的模式进行加密。

常见的分组加密模式有:ECB(不安全)、CBC(最常用)、CFB、OFB、CTR等。

以最简单的ECB为例,先将消息拆分成等分的模块,然后利用秘钥进行加密。

Sharing of basic security knowledge in Nodejs crypto module

图片来源:这里,更多关于分组加密模式的介绍可以参考 wiki。

后面假设每个块的长度为128位

2、初始化向量:IV

为了增强算法的安全性,部分分组加密模式(CFB、OFB、CTR)中引入了初始化向量(IV),使得加密的结果随机化。也就是说,对于同一段明文,IV不同,加密的结果不同。

以CBC为例,每一个数据块,都与前一个加密块进行亦或运算后,再进行加密。对于第一个数据块,则是与IV进行亦或。

IV的大小跟数据块的大小有关(128位),跟秘钥的长度无关。

如图所示,图片来源 这里

Sharing of basic security knowledge in Nodejs crypto module

3、填充:padding

分组加密模式需要对长度固定的块进行加密。分组拆分完后,最后一个数据块长度可能小于128位,此时需要进行填充以满足长度要求。

填充方式有多重。常见的填充方式有PKCS7。

假设分组长度为k字节,最后一个分组长度为k-last,可以看到:

  1. 不管明文长度是多少,加密之前都会会对明文进行填充 (不然解密函数无法区分最后一个分组是否被填充了,因为存在最后一个分组长度刚好等于k的情况)

  2. 如果最后一个分组长度等于k-last === k,那么填充内容为一个完整的分组 k k k ... k (k个字节)

  3. 如果最后一个分组长度小于k-last < k,那么填充内容为 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
Copy after login

概括来说

  1. 分组加密:先将明文切分成固定长度的块(128位),再进行加密。

  2. 分组加密的几种模式:ECB(不安全)、CBC(最常用)、CFB、OFB、CTR。

  3. 填充(padding):部分加密模式,当最后一个块的长度小于128位时,需要通过特定的方式进行填充。(ECB、CBC需要填充,CFB、OFB、CTR不需要填充)

  4. 初始化向量(IV):部分加密模式(CFB、OFB、CTR)会将 明文块 与 前一个密文块进行亦或操作。对于第一个明文块,不存在前一个密文块,因此需要提供初始化向量IV(把IV当做第一个明文块 之前的 密文块)。此外,IV也可以让加密结果随机化。

Related recommendations:

Simple method of using CryptoJS

Detailed explanation of the crypto encryption method of nodeJS

Detailed introduction about crypto-js

The above is the detailed content of Sharing of basic security knowledge in Nodejs crypto module. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template