deno.com

AES 加密與解密

在 Github 上編輯

此範例示範如何使用 Deno 內建的 SubtleCrypto API 進行 AES 加密與解密。

定義要加密的文字
const text = "Hello, Deno 2!";
使用 TextEncoder 將文字轉換為 Uint8Array(加密時必要)
const encoder = new TextEncoder();
const data = encoder.encode(text);
產生用於加密和解密的 AES-GCM 金鑰。在此範例中,我們使用 AES-GCM,因為它是一種廣泛使用的加密模式,但您也可以針對不同的使用案例使用 AES-CBC 或 AES-CTR 等模式。
const key = await crypto.subtle.generateKey(
  {
    name: "AES-GCM",
    length: 256, // 256-bit encryption key for strong security
  },
  true, // The key is extractable for encryption and decryption
  ["encrypt", "decrypt"], // Key usages: encryption and decryption
);
為 AES-GCM 產生隨機初始化向量 (IV)。IV 每次加密操作都必須是唯一的,但不需要保密。
const iv = crypto.getRandomValues(new Uint8Array(12)); // 12-byte IV for AES-GCM
使用 AES-GCM 加密文字
const encryptedData = await crypto.subtle.encrypt(
  {
    name: "AES-GCM",
    iv: iv, // Initialization vector must be unique for each encryption
  },
  key, // The generated key
  data, // The text data to encrypt
);

console.log("Encrypted Data:", new Uint8Array(encryptedData)); // Log the encrypted result as a byte array
使用相同的 IV 和金鑰將加密資料解密回明文。用於解密的 IV 和金鑰必須與加密時使用的相同
const decryptedData = await crypto.subtle.decrypt(
  {
    name: "AES-GCM",
    iv: iv, // Same IV used for encryption
  },
  key, // The same key used for encryption
  encryptedData, // The encrypted data to decrypt
);
使用 TextDecoder 將解密後的資料轉換回字串
const decryptedText = new TextDecoder().decode(decryptedData);
console.log("Decrypted Text:", decryptedText);

使用 Deno CLI 在本機執行此範例

deno run https://deno-docs.dev.org.tw/examples/scripts/aes_encryption.ts

您找到需要的資訊了嗎?

隱私權政策