Home >Web Front-end >JS Tutorial >Security knowledge sharing of crypto modules in Nodejs

Security knowledge sharing of crypto modules in Nodejs

小云云
小云云Original
2018-01-05 09:21:121520browse

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. This article mainly gives you a detailed introduction to the security knowledge of the crypto module in Nodejs. Friends who need it can follow the editor for reference. I hope it can help everyone.

The crypto 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 the theoretical knowledge behind the API, mainly including the following content:

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

Symmetry Encryption, asymmetric encryption, electronic signature

Block encryption mode

Digest (hash)

Digest (digest): Messages with unfixed length As input, by running the hash function, a fixed-length output is generated. This output is called a summary. 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

Note: In various articles or documents, the words abstract, hash, and hash are often used interchangeably, causing many beginners to look confused. In fact, most of the time they refer to the same thing. Just remember the definition of summary above.

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

Symmetric encryption, asymmetric encryption

Encryption/decryption: Given plain text, use a certain algorithm to generate an encrypted password Text, this 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, a secret key is introduced in the encryption/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)

According to whether the secret keys used for encryption and decryption are the same, encryption algorithms can be divided into symmetric encryption and 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); // 加密
plainText = decrypt(encryptedText, key); // 解密

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.

Add and decrypt pseudo code:

encryptedText = encrypt(plainText, publicKey); // 加密
plainText = decrypt(encryptedText, priviteKey); // 解密

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.

Asymmetric encryption is usually used to encrypt short text, and symmetric encryption is usually used to encrypt long text.

The two can be used in combination. For example, the HTTPS protocol can exchange and generate symmetric keys through RSA 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.

Digital signature

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

Confirm that the information comes from a specific subject.

Confirm that the information is complete and has not been tampered with.

In order to achieve the above purpose, two processes are required:

Sender: Generate signature.

Receiver: Verify signature.

1. The sender generates a signature

Calculate the digest of the original message.

Sign the digest with the private key to obtain an electronic signature.

Send the original information and electronic signature to the recipient.

Attachment: Signature pseudocode

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

2. The receiver verifies the signature

Unlock the electronic signature through the public key and obtain the digest D1. (If it cannot be solved, the verification of the information source body fails)

Calculate the digest D2 of the original information.

Compare D1 and D2. If D1 is equal to D2, it means that the original information is complete and has not been tampered with.

Attachment: Signature verification pseudo code

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

3. Comparison of asymmetric encryption

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

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

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

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

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

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

1、分组加密模式

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

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

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

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

2、初始化向量:IV

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

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

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

3、填充:padding

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

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

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

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

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

如果最后一个分组长度小于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

概括来说

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

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

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

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

写在后面

crypto模块涉及的安全知识较多,篇幅所限,这里没办法一一展开。为了讲解方便,部分内容可能不够严谨,如有错漏敬请指出。

相关推荐:

CryptoJS简单使用方法

M2Crypto RSA加密、解密的实例介绍

nodeJS之crypto加密方式的详解

The above is the detailed content of Security knowledge sharing of crypto modules in Nodejs. For more information, please follow other related articles on the PHP Chinese website!

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