RSASSA-PKCS1-v1_5 簽章與驗證
在 Github 上編輯
此範例示範如何使用 Deno 內建的 SubtleCrypto API 進行 RSA 簽章和驗證。
使用 TextEncoder 將文字轉換為 Uint8Array(簽章時需要)
const data = new TextEncoder().encode("Hello, Deno 2.0!");
const { publicKey, privateKey } = await crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048, // 2048-bit key for strong security
publicExponent: new Uint8Array([1, 0, 1]), // Public exponent: 65537
hash: { name: "SHA-256" },
},
true,
["verify", "sign"],
);
使用私鑰簽署資料
const signature = await crypto.subtle.sign(
{ name: "RSASSA-PKCS1-v1_5" },
privateKey,
data,
);
將簽章記錄為位元組陣列
console.log("Signature:", new Uint8Array(signature));
使用公鑰驗證簽章
const verification = await crypto.subtle.verify(
{ name: "RSASSA-PKCS1-v1_5" },
publicKey,
signature,
data,
);
console.log("Verification:", verification);
使用 Deno CLI 在本地執行此範例
deno run https://deno-docs.dev.org.tw/examples/scripts/rsa_signature.ts