하나의 공개 키로 여러 계정에 로그인할 수 있도록 구현

This commit is contained in:
static
2024-12-29 01:37:44 +09:00
parent c16abca832
commit af51f04b94
7 changed files with 131 additions and 71 deletions

View File

@@ -1,44 +1,10 @@
import {
generateRSAKeyPair,
makeRSAKeyNonextractable,
exportRSAKeyToBase64,
} from "$lib/modules/crypto";
import { keyPairStore } from "$lib/stores";
type KeyType = "public" | "private";
const generateRSAKeyPair = async () => {
const keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
} satisfies RsaHashedKeyGenParams,
true,
["encrypt", "decrypt"],
);
return keyPair;
};
const makeRSAKeyNonextractable = async (key: CryptoKey, type: KeyType) => {
const format = type === "public" ? "spki" : "pkcs8";
const keyUsage = type === "public" ? "encrypt" : "decrypt";
return await window.crypto.subtle.importKey(
format,
await window.crypto.subtle.exportKey(format, key),
{
name: "RSA-OAEP",
hash: "SHA-256",
} satisfies RsaHashedImportParams,
false,
[keyUsage],
);
};
const exportKeyToBase64 = async (key: CryptoKey, type: KeyType) => {
const exportedKey = await window.crypto.subtle.exportKey(
type === "public" ? "spki" : "pkcs8",
key,
);
return btoa(String.fromCharCode(...new Uint8Array(exportedKey)));
};
export const generateKeyPair = async () => {
const keyPair = await generateRSAKeyPair();
const privKeySecured = await makeRSAKeyNonextractable(keyPair.privateKey, "private");
@@ -49,7 +15,7 @@ export const generateKeyPair = async () => {
});
return {
pubKeyBase64: await exportKeyToBase64(keyPair.publicKey, "public"),
privKeyBase64: await exportKeyToBase64(keyPair.privateKey, "private"),
pubKeyBase64: await exportRSAKeyToBase64(keyPair.publicKey, "public"),
privKeyBase64: await exportRSAKeyToBase64(keyPair.privateKey, "private"),
};
};