使用subtleCrypto加密API Key时Promise返回undefined的问题求助
问题修复:SubtleCrypto加密后返回undefined及Promise pending问题
问题原因
- encryptKey函数未返回异步操作结果:原函数标记为
async,但内部调用window.crypto.subtle.generateKey()后未return该Promise链,导致函数默认返回一个resolve为undefined的Promise,因此await encryptKey()得到undefined。 - 未正确处理async函数返回值:
encryptMyKey是async函数,直接调用会返回pending状态的Promise,必须通过await(需在async上下文)或.then()获取最终结果。
修复后的代码
1. 修正subtleCrypto.js
改用await简化异步流程,确保函数返回正确的Promise:
const encryptKey = async (storedAPIKey) => { // 生成RSA密钥对 const keyPair = await window.crypto.subtle.generateKey( { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["encrypt", "decrypt"] ); // 加密API密钥 const encryptedKey = await encryptMessage(storedAPIKey, keyPair.publicKey); console.log(encryptedKey); return encryptedKey; }; export { encryptKey };
若坚持使用.then()写法,需确保返回Promise链:
const encryptKey = (storedAPIKey) => { return window.crypto.subtle .generateKey( { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["encrypt", "decrypt"] ) .then(async (keyPair) => { const encryptedKey = await encryptMessage(storedAPIKey, keyPair.publicKey); console.log(encryptedKey); return encryptedKey; }); }; export { encryptKey };
2. 修正Vue组件调用代码
正确处理async函数返回的Promise:
import { encryptKey } from "@/modules/subtleCrypto.js"; let myAPIKey = localStorage.getItem("ai-key"); const encryptMyKey = async () => { const encryptedAPIKey = await encryptKey(myAPIKey); console.log(encryptedAPIKey); return encryptedAPIKey; }; // 方式1:通过.then()获取加密结果 encryptMyKey().then(encryptedKey => { console.log("最终加密密钥:", encryptedKey); // 执行加密后的后续逻辑 }); // 方式2:在Vue异步生命周期钩子中使用await(如mounted) // async mounted() { // const encryptedKey = await encryptMyKey(); // console.log("最终加密密钥:", encryptedKey); // }
内容的提问来源于stack exchange,提问作者Alan
相关产品推荐
相关产品推荐

