• Node.js Video Tutorials

Node.js - 加密


在 Node.js 中,crypto 是一個內建模組,提供必要的加密功能,以將安全方面整合到專案中,例如加密、解密、雜湊函式等等。此模組依賴於 OpenSSL 進行其加密操作。

密碼學是將資料轉換成只有滿足某些預定條件的使用者才能理解的形式的過程。

密碼學不僅僅是關於編碼和解碼訊息,它是在日益全球化的環境中確保資訊保持私密、完整和真實的。

Crypto 類

Crypto 類代表當前上下文中可用的基本密碼學功能。它是 Node.js 內建庫,包含 Crypto 模組。

屬性

以下是 crypto 類的屬性:

序號 屬性及描述
1

crypto.subtle

此屬性返回 SubtleCrypto 介面。

方法

以下是 Crypto 類的使用方法:

序號 方法及描述
1

crypto.getRandomValues(typedArray)

傳遞相同的 typedArray 陣列,但其內容將被替換為新的隨機數。

2

crypto.randomUUID()

此方法返回一個包含隨機生成的字串。

CryptoKey 類

CryptoKey 類用於表示建立和管理加密金鑰的藍圖。

屬性

以下是 CryptoKey 類可用的屬性列表:

序號 屬性及描述
1

cryptoKey.algorithm

返回的物件取決於用於生成金鑰的演算法。

2

cryptoKey.extractable

布林值,如果金鑰可以匯出則為 true,否則為 false。

3

cryptoKey.type

返回一個字串陣列,包含 secret、private 或 public。

4

cryptoKey.usages

返回字串陣列。

CryptoKeyPair 類

CryptoKeyPair 類提供了一種管理和使用公鑰和私鑰對的結構化方法。

屬性

以下是 CryptoKeyPair 類的屬性列表:

序號 屬性及描述
1

cryptoKeyPair.privateKey

此屬性提供對金鑰對私鑰的訪問。

2

cryptoKeyPair.publicKey

此屬性提供對金鑰對公鑰的訪問。

SubtleCrypto 類

SubtleCrypto 類是 Web Cryptography API 的一部分,旨在在 Web 應用程式中執行低階加密操作。它提供生成金鑰的方法。

方法

以下是 SubtleCrypto 類的使用方法列表:

序號 方法及描述
1

subtle.decrypt(algorithm, key, data)

返回一個 Promise,解析為 ArrayBuffer 格式的解密資料。

2

subtle.deriveBits(algorithm, baseKey, length)

返回一個 Promise,解析為 ArrayBuffer 格式的派生位。

3

subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)

返回一個 Promise,解析為 CryptoKey 物件。

4

subtle.digest(algorithm, data)

返回一個 Promise,解析為 ArrayBuffer 格式的給定資料的摘要。

5

subtle.encrypt(algorithm, key, data)

返回一個 Promise,解析為 ArrayBuffer 格式的加密資料。

6

subtle.exportKey(format, key)

返回一個 Promise,解析為指定格式的金鑰資料。

7

subtle.generateKey(algorithm, extractable, keyUsages)

返回一個 Promise,解析為新生成的 CryptoKey 物件,代表生成的金鑰。

8

subtle.importKey(format, keyData, algorithm, extractable, keyUsages)

返回一個 Promise,解析為 CryptoKey 物件,代表匯入的金鑰。

9

subtle.sign(algorithm, key, data)

返回一個 Promise,解析為 ArrayBuffer 格式的給定資料的簽名。

10

subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)

返回一個 Promise,解析為 CryptoKey 物件,代表解開的金鑰。

11

subtle.verify(algorithm, key, signature, data)

返回一個 Promise,解析為布林值,指示提供的簽名是否與給定資料的預期簽名匹配。

12

subtle.wrapKey(format, key, wrappingKey, wrapAlgo)

返回一個 Promise,解析為包含已包裝金鑰資料的 ArrayBuffer 或 TypedArray。

nodejs_built_in_modules.htm
廣告