initial commit with imported utils from old github project
This commit is contained in:
commit
66bb463e23
39 files changed
+1944
No files matched your search
@@ -0,0 +1,62 @@
|
||||
"use server";
|
||||
import { generateKeyPairSync, getRandomValues, subtle } from "crypto";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
import { deriveKey } from "./encryption";
|
||||
|
||||
export async function generateKeyPair(plain_pw: string, user_id: string) {
|
||||
const supabase = await createClient();
|
||||
const { publicKey, privateKey } = generateKeyPairSync("rsa", {
|
||||
modulusLength: 4096,
|
||||
publicKeyEncoding: {
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: "pkcs8",
|
||||
format: "pem",
|
||||
cipher: "aes-256-cbc",
|
||||
passphrase: "",
|
||||
},
|
||||
});
|
||||
|
||||
const salt = getRandomValues(new Uint8Array(16));
|
||||
const iv = getRandomValues(new Uint8Array(32));
|
||||
const key = await deriveKey(plain_pw, salt);
|
||||
const encodedPrivateKey = new TextEncoder().encode(privateKey);
|
||||
const encryptedContent = await subtle.encrypt(
|
||||
{
|
||||
name: "AES-GCM",
|
||||
iv,
|
||||
tagLength: 128, // 128-bit tag length
|
||||
},
|
||||
key,
|
||||
encodedPrivateKey,
|
||||
);
|
||||
|
||||
const encryptedPrivateKey = encryptedContent.slice(
|
||||
0,
|
||||
encryptedContent.byteLength - 16,
|
||||
);
|
||||
const encryptedPrivateKey_Base64 =
|
||||
Buffer.from(encryptedPrivateKey).toString("base64");
|
||||
|
||||
const authTag = encryptedContent.slice(encryptedContent.byteLength - 16);
|
||||
const authTag_Base64 = Buffer.from(authTag).toString("base64");
|
||||
const salt_Base64 = Buffer.from(salt).toString("base64");
|
||||
const iv_Base64 = Buffer.from(iv).toString("base64");
|
||||
|
||||
const { error } = await supabase
|
||||
.from("users")
|
||||
.update({
|
||||
private_key_enc: encryptedPrivateKey_Base64,
|
||||
public_key_dec: publicKey,
|
||||
salt: salt_Base64,
|
||||
iv: iv_Base64,
|
||||
auth_tag: authTag_Base64,
|
||||
})
|
||||
.eq("id", user_id);
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
Reference in new issue
Block a user